@squadico/chatbot 1.7.0 → 1.8.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.
Files changed (42) hide show
  1. package/README.md +4 -4
  2. package/dist/{answer-BO2Hs9k1.cjs → answer-C3IUYu5f.cjs} +3 -3
  3. package/dist/answer-C3IUYu5f.cjs.map +1 -0
  4. package/dist/{answer-DF91dBOx.js → answer-CQWAgbwL.js} +17 -5
  5. package/dist/answer-CQWAgbwL.js.map +1 -0
  6. package/dist/chatbot-widgets.global.js +3 -3
  7. package/dist/chatbot-widgets.global.js.map +1 -1
  8. package/dist/chatbot.global.js +11 -11
  9. package/dist/chatbot.global.js.map +1 -1
  10. package/dist/extras-CFSQMYPh.cjs +4 -0
  11. package/dist/extras-CFSQMYPh.cjs.map +1 -0
  12. package/dist/{extras-D94278IT.js → extras-DP27_4bx.js} +139 -99
  13. package/dist/extras-DP27_4bx.js.map +1 -0
  14. package/dist/index.cjs +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/lib/client.d.ts +2 -0
  17. package/dist/lib/client.d.ts.map +1 -1
  18. package/dist/lib/i18n.d.ts +5 -0
  19. package/dist/lib/i18n.d.ts.map +1 -1
  20. package/dist/lib/useChat.d.ts.map +1 -1
  21. package/dist/react.cjs +1 -1
  22. package/dist/react.js +1 -1
  23. package/dist/src-BXQdw_Q7.cjs +7 -0
  24. package/dist/src-BXQdw_Q7.cjs.map +1 -0
  25. package/dist/{src-Bm_aRvFA.js → src-CwY6PP_H.js} +231 -219
  26. package/dist/src-CwY6PP_H.js.map +1 -0
  27. package/dist/types.d.ts +18 -0
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/widgets/approval/SqcApproval.d.ts.map +1 -1
  30. package/dist/widgets/extras-loader.d.ts +1 -1
  31. package/dist/widgets/parse/confirm.d.ts +1 -1
  32. package/dist/widgets.cjs +1 -1
  33. package/dist/widgets.js +2 -2
  34. package/package.json +1 -1
  35. package/dist/answer-BO2Hs9k1.cjs.map +0 -1
  36. package/dist/answer-DF91dBOx.js.map +0 -1
  37. package/dist/extras-BeCZR-6X.cjs +0 -4
  38. package/dist/extras-BeCZR-6X.cjs.map +0 -1
  39. package/dist/extras-D94278IT.js.map +0 -1
  40. package/dist/src-Bm_aRvFA.js.map +0 -1
  41. package/dist/src-DcPZdalT.cjs +0 -7
  42. package/dist/src-DcPZdalT.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-DcPZdalT.cjs","names":[],"sources":["../src/lib/context.ts","../src/lib/openState.ts","../src/lib/uid.ts","../src/lib/client.ts","../src/lib/conversation.ts","../src/lib/useChat.ts","../src/components/Avatar.tsx","../src/components/AgentRail.tsx","../src/components/Composer.tsx","../src/components/RichText.tsx","../src/components/MessageList.tsx","../src/components/ChatbotWidget.tsx","../src/styles.css?inline","../src/element.tsx","../src/index.ts"],"sourcesContent":["/**\n * Page context: reading an `{ id, name }` entry and shaping it for the wire.\n *\n * A host object can be named in two ways. Its id alone, under a flat key\n * (`orderId: 'ORD-1'`), or the named object under the entity key\n * (`order: { id: 'ORD-1', name: 'Order #1042' }`). The second form exists for\n * display: the chip shows \"Order #1042\" instead of a UUID, and the host is the\n * only one knowing that name without calling the API.\n *\n * On the wire the agent only reads strings, so `wireContext` splits every named\n * object into `<key>Id` + `<key>Name` right before sending. Keeping a single\n * shape on the network makes the request identical however the host filled its\n * context in.\n *\n * Nothing here is domain-specific: the widget has no list of known entities, it\n * only recognises the `{ id, name }` shape wherever the host used it.\n */\nimport type { ChatbotContext, ContextObject } from '../types'\n\n/** Keys the widget owns and never treats as a host object. */\nconst RESERVED_KEYS = new Set<string>(['sessionId'])\n\n/**\n * Reads a context entry, named object or bare id.\n *\n * Returns `undefined` when it carries no usable id — empty string, object with\n * no `id`: \"nothing selected\", not \"something named nowhere\".\n */\nexport function contextObject(value: unknown): ContextObject | undefined {\n if (typeof value === 'string') {\n return value.length > 0 ? { id: value } : undefined\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const { id, name } = value as { id?: unknown; name?: unknown }\n if (typeof id !== 'string' || id.length === 0) return undefined\n return typeof name === 'string' && name.length > 0 ? { id, name } : { id }\n}\n\n/** What a chip displays: the name when the host gave one, the id otherwise. */\nexport function contextLabel(value: unknown): string | undefined {\n const object = contextObject(value)\n if (!object) return undefined\n return object.name ?? object.id\n}\n\n/** Whether an entry carries a named object (`{ id, name? }`) rather than a\n * plain value — the shape the chips and the wire format are built on. */\nexport function isNamedObject(value: unknown): boolean {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Puts the context in the shape the agent reads: `order: { id, name }` becomes\n * `orderId` + `orderName`.\n *\n * Everything else goes through untouched — `sessionId`, an already flat\n * `orderId`, or any free key of the host: the widget does not filter the\n * context, it only translates what it knows how to translate.\n */\nexport function wireContext(context: ChatbotContext): Record<string, unknown> {\n const wire: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(context)) {\n if (RESERVED_KEYS.has(key) || !isNamedObject(value)) {\n wire[key] = value\n continue\n }\n const object = contextObject(value)\n // An empty named key is not sent: it would claim something is selected.\n if (!object) continue\n wire[`${key}Id`] = object.id\n if (object.name) wire[`${key}Name`] = object.name\n }\n return wire\n}\n","/**\n * Remembers whether the user left the panel open or closed, so a reload or a\n * navigation to another page of the host app does not silently undo their last\n * gesture — closing an assistant that reopens itself on the next screen, or\n * losing an open conversation to a route change.\n *\n * `sessionStorage`, not the `localStorage` `useChat` uses for the \"new\n * conversation\" gesture: this is transient UI state belonging to one tab.\n * Reopening the app tomorrow, or in a second tab, starts from the host's own\n * default rather than from a gesture made in another browsing session; the\n * conversation is still there, one click away.\n */\n\n/** One panel state per host origin — enough as long as a page mounts a single\n * widget, which is the case for every current integrator. */\nconst OPEN_STORAGE_KEY = 'squadico-chatbot:open'\n\n/** `undefined` when nothing was ever stored, or storage is unusable — which is\n * distinct from a stored `false` (the user closed the panel) and is what lets\n * a host's `defaultOpen` still apply on a first visit. */\nfunction readOpenState(): boolean | undefined {\n try {\n if (typeof sessionStorage === 'undefined') return undefined\n const raw = sessionStorage.getItem(OPEN_STORAGE_KEY)\n if (raw === '1') return true\n if (raw === '0') return false\n return undefined\n } catch {\n // Storage unavailable (private browsing, blocked cookies…): the panel state\n // stays volatile, as it was before this persistence existed.\n return undefined\n }\n}\n\nexport function writeOpenState(open: boolean): void {\n try {\n if (typeof sessionStorage === 'undefined') return\n sessionStorage.setItem(OPEN_STORAGE_KEY, open ? '1' : '0')\n } catch {\n /* see readOpenState */\n }\n}\n\n/**\n * Resolves the state the panel mounts in.\n *\n * A remembered gesture wins over `defaultOpen`, which is a *default*: the host\n * declares where a first-time visitor starts, the user decides afterwards.\n * A host that needs the panel open on every load calls `openChat()` instead.\n *\n * Shared by both wrappers: `src/react.tsx` applies `defaultOpen` imperatively\n * after mount, so it has to arbitrate the same way or it would reopen a panel\n * the user had closed.\n */\nexport function initialOpen(defaultOpen?: boolean, persist?: boolean): boolean {\n if (persist === false) return defaultOpen ?? false\n return readOpenState() ?? defaultOpen ?? false\n}\n","/**\n * UUID v4. `crypto.randomUUID` only exists in a secure context (https or\n * localhost): the two fallbacks cover an integration served over http:// on a\n * LAN IP, a common staging setup. The API validates `sessionId` as a UUID, so\n * the format has to stay strictly conformant.\n */\nexport function uuid(): string {\n const c = globalThis.crypto as Crypto | undefined\n\n if (c && typeof c.randomUUID === 'function') {\n return c.randomUUID()\n }\n\n const bytes = new Uint8Array(16)\n if (c && typeof c.getRandomValues === 'function') {\n c.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n // Force version 4 and the RFC 4122 variant.\n bytes[6] = (bytes[6] & 0x0f) | 0x40\n bytes[8] = (bytes[8] & 0x3f) | 0x80\n\n const hex: string[] = []\n for (let i = 0; i < 16; i++) hex.push(bytes[i].toString(16).padStart(2, '0'))\n return (\n hex.slice(0, 4).join('') +\n '-' +\n hex.slice(4, 6).join('') +\n '-' +\n hex.slice(6, 8).join('') +\n '-' +\n hex.slice(8, 10).join('') +\n '-' +\n hex.slice(10, 16).join('')\n )\n}\n","/**\n * HTTP client of the Squadico public API.\n *\n * Five calls, and they are the routes the backend actually serves:\n * - `previewApplication` → `GET /public/applications/{embedKey}`\n * - `openConversation` → `POST /public/applications/{embedKey}/conversations`\n * - `replayConversation` → `GET /public/conversations/{id}`\n * - `sendMessage` → `POST /public/conversations/{id}/messages` (SSE)\n * - `resolveApproval` → `POST /public/conversations/{id}/approvals` (SSE)\n *\n * **The widget authenticates nobody.** It is the public surface: the embed key says\n * which application, and the visitor token handed back at open is the whole of the\n * authorization afterwards. The token travels in a header and never in a cookie —\n * third-party cookies are blocked or on their way out, and a header cannot be sent\n * ambiently, which removes CSRF as a class.\n *\n * **The server names the conversation.** Its id comes back from the open call: a\n * visitor allowed to name their own conversation is a visitor choosing which one to\n * read.\n *\n * **The author claim travels once, at open.** A panel has one person in front of it,\n * so one claim per conversation is auditable while one per message would be an\n * annotation anybody could change halfway through. It is attribution and never\n * authorization: what a visitor may read is decided by their token.\n *\n * **Everything is streamed the same way.** Five frame types — `token`, `progress`,\n * `done`, `error`, `approval_required` — for a fresh question and for a resumed\n * approval alike, plus three a team adds: `handoff` (another agent of the team answers\n * from here, and signs the `done` that follows), `escalated` (the agent handed the\n * conversation to a human) and `held` (a human handles it: the message was kept\n * for them and nothing answers). `done` carries the stored turn (the one a reload would show), on a surface\n * that can hold several agents which one answered, and — when the message addressed\n * a name nobody answers to — that name with the ones that do. That last one is a\n * hint beside an answer and never a refusal: the default agent replied, because a\n * visitor typing `@sale` should get help rather than a 404.\n *\n * **A handle is never routed from here.** The message text is what the server\n * parses, so the picker and the `agent` option both work by putting a handle in\n * front of what somebody types. A client naming its own agent would be a client\n * choosing its own router.\n *\n * No dependency: `fetch` + `ReadableStream`, available everywhere the widget runs.\n */\nimport type {\n AgentHandle,\n ChatActivity,\n ChatAttachment,\n ChatMessage,\n ChatRole,\n PendingApproval,\n} from '../types'\nimport { uuid } from './uid'\n\n/** The Squadico API, written in at build time (`config/api-url.ts`). Not an\n * option: a page embedding the widget does not choose the server it talks to. */\nexport const API_URL: string = __SQUADICO_API_URL__\n\n/** Aligned on `MESSAGE_MAX_LENGTH` in the API's own schema: a message longer than\n * this is a 422 from the form rather than a 400 from a vendor at the first token. */\nexport const MAX_MESSAGE_LENGTH = 20_000\n\nexport class ChatHttpError extends Error {\n readonly status?: number\n /** The API's machine-readable name for the refusal, when it sent one.\n *\n * What a panel branches on: `origin_not_allowed` means stop embedding,\n * `application_has_no_agent` means nothing answers there yet, and\n * `conversation_retired` means open a new conversation. Three reactions a bare\n * status cannot tell apart. */\n readonly code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'ChatHttpError'\n this.status = status\n this.code = code\n }\n}\n\nexport interface HostUser {\n id: string\n name?: string\n /** The HMAC the host's *server* computed over `id`, where the application asks\n * for one. Never computed in the page: a digest a browser can produce is a\n * digest anybody can produce, and the secret would be in the page's source. */\n digest?: string\n}\n\nexport interface OpenConversationInit {\n apiUrl: string\n embedKey: string\n /** Who the embedding application has signed in, when it has anybody. */\n user?: HostUser\n /** The handle the page wants to open on. Unknown here opens on the default rather\n * than refusing: a page carrying a renamed handle must keep working. */\n agent?: string\n signal?: AbortSignal\n}\n\n/** What opening a panel answers with. */\nexport interface OpenedConversation {\n conversationId: string\n visitorToken: string\n /** The agent that answers a message addressing nobody. */\n agentName: string\n agentSlug: string\n welcomeMessage?: string\n /** Shortcuts drawn under the welcome message, each sent as written. */\n welcomeSuggestions: string[]\n /** The transcript as it stands — the welcome message, on a fresh conversation. */\n messages: ChatMessage[]\n /** The handles this application offers, which is empty until somebody ticks one. */\n handles: AgentHandle[]\n /** The handle the conversation really opened on — which may not be the one that\n * was asked for, if the server fell back to the default. */\n agentHandle?: string\n /** A human of the organization handles it: no agent answers, and the panel\n * reads the conversation again to show their replies. */\n withHuman?: boolean\n /** Whether the panel shows \"Powered by Squadico\" — the organization's plan says. */\n branding: boolean\n}\n\n/** The shortcuts an answer names: its non-empty strings, and nothing for the rest. */\nfunction toSuggestions(raw: unknown): string[] {\n if (!Array.isArray(raw)) return []\n return raw.filter((item): item is string => typeof item === 'string' && item.trim() !== '')\n}\n\nexport interface PreviewApplicationInit {\n apiUrl: string\n embedKey: string\n /** The handle the page wants to open on, so the welcome message is that agent's. */\n agent?: string\n signal?: AbortSignal\n}\n\n/** What a panel draws before anybody has said anything in it. */\nexport interface ApplicationPreview {\n welcomeMessage?: string\n /** Shortcuts drawn under the welcome message, each sent as written. */\n welcomeSuggestions: string[]\n /** Who the welcome message is drawn as — the badge the stored greeting gets. */\n agent?: AgentHandle\n handles: AgentHandle[]\n agentHandle?: string\n branding: boolean\n}\n\nexport interface ReplayConversationInit {\n apiUrl: string\n conversationId: string\n visitorToken: string\n signal?: AbortSignal\n}\n\nexport interface SendMessageInit {\n apiUrl: string\n conversationId: string\n visitorToken: string\n message: string\n /** The files this question carries, named rather than implied: anything else\n * the conversation is still holding stays where it is. */\n attachmentIds?: string[]\n /** What the page knows about where the visitor is. Sent as data, never as\n * instructions — see `ChatbotContext`. */\n context?: Record<string, unknown>\n /** The access token the host site holds for its signed-in user — see\n * `getSubjectToken` on the props. */\n subjectToken?: string\n onToken: (token: string) => void\n /** Told what the agent is busy with while it has written nothing yet. */\n onProgress?: (activity: ChatActivity) => void\n signal?: AbortSignal\n}\n\nexport interface ResolveApprovalInit {\n apiUrl: string\n conversationId: string\n visitorToken: string\n /** The call the panel is answering for. Checked against what the conversation is\n * actually waiting on, so a stale decision is refused rather than resuming the\n * wrong thing. */\n toolCallId: string\n approved: boolean\n subjectToken?: string\n onToken: (token: string) => void\n /** Told what the agent is busy with while it has written nothing yet. */\n onProgress?: (activity: ChatActivity) => void\n signal?: AbortSignal\n}\n\n/** What a turn produced: the stored answer, who wrote it, and what it stopped on. */\nexport interface ChatTurn {\n answer: string\n /** Which agent answered, on a surface that can hold several. */\n agent?: AgentHandle\n /** Set when the turn paused: one tool call is waiting on a decision, and nothing\n * has been written until one is sent. */\n approval?: PendingApproval\n /** The name the message addressed and nobody on this application answers to. The\n * answer came from the default agent all the same. */\n unknownHandle?: string\n /** The handles that *do* answer, to say instead of the mistyped one. Empty when\n * the organization has ticked none — the panel then says only that nobody\n * answers to that name. */\n offered?: AgentHandle[]\n /** The agent the conversation was passed to during this turn, when it has no\n * handle on the application to be announced by — what signs its answer. */\n authorName?: string\n /** The agent handed the conversation to a human of the organization, or one\n * already handles it: no agent answers what comes next. */\n withHuman?: boolean\n /** The message was kept for the human handling the conversation; no agent ran,\n * so there is no answer to draw. */\n held?: boolean\n}\n\ninterface ApiMessage {\n id?: unknown\n role?: unknown\n content?: unknown\n agent?: unknown\n attachments?: unknown\n created_at?: unknown\n kind?: unknown\n author_name?: unknown\n}\n\ninterface ApiAttachment {\n id?: unknown\n kind?: unknown\n filename?: unknown\n content_type?: unknown\n}\n\nfunction endpoint(apiUrl: string, path: string): string {\n return `${apiUrl.replace(/\\/+$/, '')}${path}`\n}\n\nfunction headers(visitorToken?: string, subjectToken?: string): HeadersInit {\n return {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream, application/json',\n ...(visitorToken ? { 'X-Visitor-Token': visitorToken } : {}),\n ...(subjectToken ? { 'X-Subject-Token': subjectToken } : {}),\n }\n}\n\n/**\n * One validation problem, as FastAPI writes it: where it is, and what is wrong.\n *\n * `loc` is the path to the field, `body` first — the last segment is the name an\n * integrator recognises.\n */\nfunction readProblem(entry: unknown): string | undefined {\n if (!entry || typeof entry !== 'object') return undefined\n const { loc, msg } = entry as { loc?: unknown; msg?: unknown }\n if (typeof msg !== 'string' || !msg) return undefined\n const path = Array.isArray(loc) ? loc.filter((part) => typeof part === 'string') : []\n const field = path.at(-1)\n return field && field !== 'body' ? `${field}: ${msg}` : msg\n}\n\n/**\n * The API answers its refusals as `{ detail, code }`; a proxy in front of it may\n * answer `{ message }`. Both are read, because a bare HTTP status is what makes an\n * integration undiagnosable — and the `code` is what a panel reacts to.\n *\n * A validation refusal answers a *list* of problems, one per field. Joined as\n * objects it reads \"[object Object]\" in a console, which is the difference between\n * a five-minute fix and an afternoon — so each one is rendered as the field it is\n * about and what it says.\n */\nasync function readError(response: Response): Promise<ChatHttpError> {\n let detail = ''\n let code: string | undefined\n try {\n const text = await response.text()\n if (text) {\n try {\n const parsed = JSON.parse(text) as {\n detail?: unknown\n code?: unknown\n message?: unknown\n }\n const raw = parsed.detail ?? parsed.message\n if (Array.isArray(raw)) {\n const problems = raw\n .map((entry) => readProblem(entry) ?? (typeof entry === 'string' ? entry : undefined))\n .filter((problem): problem is string => problem !== undefined)\n detail = problems.length > 0 ? problems.join(', ') : text\n } else {\n detail = typeof raw === 'string' ? raw : text\n }\n code = typeof parsed.code === 'string' ? parsed.code : undefined\n } catch {\n detail = text\n }\n }\n } catch {\n /* unreadable body — fall back to the status alone */\n }\n return new ChatHttpError(detail || `The API answered ${response.status}`, response.status, code)\n}\n\n/** Normalises the agent of a `done` frame. Absent on a surface with one agent.\n *\n * The avatar arrives as a path on the API and is drawn by a page on another\n * origin, so it is made absolute here, against the API the panel talks to. */\nfunction toHandle(raw: unknown, apiUrl: string): AgentHandle | undefined {\n if (!raw || typeof raw !== 'object') return undefined\n const source = raw as {\n handle?: unknown\n name?: unknown\n avatar_url?: unknown\n color?: unknown\n }\n if (typeof source.handle !== 'string' || !source.handle) return undefined\n return {\n handle: source.handle,\n name: typeof source.name === 'string' ? source.name : source.handle,\n avatarUrl:\n typeof source.avatar_url === 'string' && source.avatar_url\n ? endpoint(apiUrl, source.avatar_url)\n : undefined,\n color: typeof source.color === 'string' ? source.color : undefined,\n }\n}\n\n/** Normalises a list of handles — the open response's, or a `done` frame's hint. */\nfunction toHandles(raw: unknown, apiUrl: string): AgentHandle[] {\n return (Array.isArray(raw) ? raw : [])\n .map((one) => toHandle(one, apiUrl))\n .filter((handle): handle is AgentHandle => handle !== undefined)\n}\n\nconst ACTIVITIES: readonly ChatActivity[] = ['knowledge', 'skill', 'delegation', 'tool']\n\n/** The kind of work a `progress` frame names. One this release has no words for\n * is still work: it reads as a tool rather than as nothing. */\nfunction toActivity(raw: unknown): ChatActivity {\n return ACTIVITIES.find((known) => known === raw) ?? 'tool'\n}\n\n/** Normalises the pause of an `approval_required` frame. */\nfunction toApproval(raw: unknown): PendingApproval | undefined {\n if (!raw || typeof raw !== 'object') return undefined\n const source = raw as {\n tool_call_id?: unknown\n tool?: unknown\n arguments?: unknown\n labels?: unknown\n }\n // With no call id no decision can be sent back for it, which makes the buttons a\n // dead end: better to render nothing than a control that cannot answer.\n if (typeof source.tool_call_id !== 'string' || !source.tool_call_id) return undefined\n const approval: PendingApproval = {\n toolCallId: source.tool_call_id,\n tool: typeof source.tool === 'string' ? source.tool : '',\n arguments:\n source.arguments && typeof source.arguments === 'object'\n ? (source.arguments as Record<string, unknown>)\n : {},\n }\n if (source.labels && typeof source.labels === 'object') {\n approval.labels = Object.fromEntries(\n Object.entries(source.labels).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string',\n ),\n )\n }\n return approval\n}\n\nconst TRANSCRIPT_ROLES = new Set<string>(['user', 'assistant'])\n\n/** One stored turn, as a panel renders it. */\nfunction toMessage(raw: ApiMessage, apiUrl: string): ChatMessage | null {\n if (typeof raw.role !== 'string' || !TRANSCRIPT_ROLES.has(raw.role)) return null\n if (typeof raw.content !== 'string' || !raw.content) return null\n const at = typeof raw.created_at === 'string' ? Date.parse(raw.created_at) : Number.NaN\n return {\n id: typeof raw.id === 'string' && raw.id ? raw.id : uuid(),\n role: raw.role as ChatRole,\n content: raw.content,\n createdAt: Number.isNaN(at) ? Date.now() : at,\n agent: toHandle(raw.agent, apiUrl),\n attachments: toAttachments(raw.attachments),\n // A member of the organization answering instead of an agent, by name.\n authorName:\n raw.kind === 'human' && typeof raw.author_name === 'string' && raw.author_name\n ? raw.author_name\n : undefined,\n }\n}\n\n/**\n * The files of one turn, as the API listed them.\n *\n * Read defensively like everything else off the wire, and dropped rather than\n * guessed at: a file this panel cannot name is a file it cannot draw either, and\n * an entry with half a shape would be a chip with no label.\n */\nfunction toAttachments(raw: unknown): ChatAttachment[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const files = raw\n .map((entry) => toAttachment(entry))\n .filter((file): file is ChatAttachment => file !== null)\n return files.length > 0 ? files : undefined\n}\n\nfunction toAttachment(raw: unknown): ChatAttachment | null {\n if (!raw || typeof raw !== 'object') return null\n const { id, kind, filename, content_type: contentType } = raw as ApiAttachment\n if (typeof id !== 'string' || !id) return null\n if (typeof filename !== 'string' || !filename) return null\n return {\n id,\n // Anything the panel does not know how to show is shown as a document,\n // which is a named chip — never as a picture it would fail to draw.\n kind: kind === 'image' || kind === 'chart' ? kind : 'document',\n filename,\n contentType: typeof contentType === 'string' ? contentType : 'application/octet-stream',\n }\n}\n\n/**\n * Reads what a panel draws when it is shown, and opens nothing.\n *\n * A panel shown is not a conversation had: the conversation is opened on the first\n * message, and until then the welcome message, the picker and the branding come\n * from here.\n */\nexport async function previewApplication(init: PreviewApplicationInit): Promise<ApplicationPreview> {\n const query = init.agent ? `?agent=${encodeURIComponent(init.agent)}` : ''\n const response = await fetch(\n endpoint(init.apiUrl, `/public/applications/${encodeURIComponent(init.embedKey)}${query}`),\n { method: 'GET', headers: headers(), signal: init.signal },\n )\n if (!response.ok) throw await readError(response)\n\n const data = (await response.json()) as {\n welcome_message?: unknown\n welcome_suggestions?: unknown\n agent?: unknown\n handles?: unknown\n agent_handle?: unknown\n branding?: unknown\n }\n return {\n welcomeMessage:\n typeof data.welcome_message === 'string' && data.welcome_message\n ? data.welcome_message\n : undefined,\n welcomeSuggestions: toSuggestions(data.welcome_suggestions),\n agent: toHandle(data.agent, init.apiUrl),\n handles: toHandles(data.handles, init.apiUrl),\n agentHandle:\n typeof data.agent_handle === 'string' && data.agent_handle ? data.agent_handle : undefined,\n branding: data.branding === true,\n }\n}\n\n/**\n * Opens a conversation for a page carrying this application's embed key.\n *\n * The body carries the host's author claim and nothing else. No bearer token: the\n * widget is the public surface, and the key plus the visitor token it gets back are\n * the whole credential story.\n */\nexport async function openConversation(init: OpenConversationInit): Promise<OpenedConversation> {\n const response = await fetch(\n endpoint(init.apiUrl, `/public/applications/${encodeURIComponent(init.embedKey)}/conversations`),\n {\n method: 'POST',\n headers: headers(),\n body: JSON.stringify({\n ...(init.user ? { user: init.user } : {}),\n // Omitted rather than sent empty: the API tells an absent field from a\n // cleared one, and an application always has an agent answering plain text.\n ...(init.agent ? { agent: init.agent } : {}),\n }),\n signal: init.signal,\n },\n )\n if (!response.ok) throw await readError(response)\n\n const data = (await response.json()) as {\n id?: unknown\n visitor_token?: unknown\n agent_name?: unknown\n agent_slug?: unknown\n welcome_message?: unknown\n welcome_suggestions?: unknown\n messages?: unknown\n handles?: unknown\n agent_handle?: unknown\n handling?: unknown\n branding?: unknown\n }\n if (typeof data.id !== 'string' || typeof data.visitor_token !== 'string') {\n throw new ChatHttpError('The API opened a conversation without an id or a token')\n }\n const messages = (Array.isArray(data.messages) ? (data.messages as ApiMessage[]) : [])\n .map((raw) => toMessage(raw, init.apiUrl))\n .filter((message): message is ChatMessage => message !== null)\n return {\n conversationId: data.id,\n visitorToken: data.visitor_token,\n agentName: typeof data.agent_name === 'string' ? data.agent_name : '',\n agentSlug: typeof data.agent_slug === 'string' ? data.agent_slug : '',\n welcomeMessage:\n typeof data.welcome_message === 'string' && data.welcome_message\n ? data.welcome_message\n : undefined,\n welcomeSuggestions: toSuggestions(data.welcome_suggestions),\n messages,\n handles: toHandles(data.handles, init.apiUrl),\n agentHandle:\n typeof data.agent_handle === 'string' && data.agent_handle ? data.agent_handle : undefined,\n withHuman: typeof data.handling === 'string' && data.handling !== 'agents',\n branding: data.branding === true,\n }\n}\n\n/**\n * Reads a conversation back, on the token it was opened with.\n *\n * What makes a reloaded page keep its conversation instead of opening a second one.\n * The answer is the open response minus the credential — the transcript, the handles\n * the composer offers, and the handle the conversation is on — because the token is\n * handed over once and the caller already holds it.\n */\nexport async function replayConversation(init: ReplayConversationInit): Promise<OpenedConversation> {\n const response = await fetch(\n endpoint(init.apiUrl, `/public/conversations/${encodeURIComponent(init.conversationId)}`),\n { method: 'GET', headers: headers(init.visitorToken), signal: init.signal },\n )\n if (!response.ok) throw await readError(response)\n\n const data = (await response.json()) as {\n id?: unknown\n agent_name?: unknown\n agent_slug?: unknown\n welcome_message?: unknown\n welcome_suggestions?: unknown\n messages?: unknown\n handles?: unknown\n agent_handle?: unknown\n handling?: unknown\n branding?: unknown\n }\n if (typeof data.id !== 'string') {\n throw new ChatHttpError('The API replayed a conversation without an id')\n }\n return {\n conversationId: data.id,\n // The one field a replay cannot answer with, and must not: the caller presented\n // it to get here.\n visitorToken: init.visitorToken,\n agentName: typeof data.agent_name === 'string' ? data.agent_name : '',\n agentSlug: typeof data.agent_slug === 'string' ? data.agent_slug : '',\n welcomeMessage:\n typeof data.welcome_message === 'string' && data.welcome_message\n ? data.welcome_message\n : undefined,\n welcomeSuggestions: toSuggestions(data.welcome_suggestions),\n messages: (Array.isArray(data.messages) ? (data.messages as ApiMessage[]) : [])\n .map((raw) => toMessage(raw, init.apiUrl))\n .filter((message): message is ChatMessage => message !== null),\n handles: toHandles(data.handles, init.apiUrl),\n agentHandle:\n typeof data.agent_handle === 'string' && data.agent_handle ? data.agent_handle : undefined,\n withHuman: typeof data.handling === 'string' && data.handling !== 'agents',\n branding: data.branding === true,\n }\n}\n\nexport interface AttachmentInit {\n apiUrl: string\n conversationId: string\n visitorToken: string\n signal?: AbortSignal\n}\n\n/**\n * Puts one file on the conversation, before the question that will carry it.\n *\n * Uploaded as it is picked rather than held until the message is sent: a format\n * the product does not take is refused here, in front of somebody who has not\n * written their question yet.\n *\n * What comes back is what was *accepted* — the kind and the type read off the\n * bytes on the server. The panel never decides what a file is.\n */\nexport async function uploadAttachment(\n init: AttachmentInit & { file: File },\n): Promise<ChatAttachment> {\n const body = new FormData()\n body.append('file', init.file)\n const response = await fetch(attachmentsUrl(init), {\n method: 'POST',\n // No content type of our own: the boundary belongs to the `FormData`, and a\n // header written over it hands the API a multipart body labelled otherwise.\n headers: { 'X-Visitor-Token': init.visitorToken },\n body,\n signal: init.signal,\n })\n if (!response.ok) throw await readError(response)\n const accepted = toAttachment(await response.json())\n if (!accepted) throw new ChatHttpError('The upload could not be read', response.status)\n return accepted\n}\n\n/** Takes a file back out of the conversation, bytes and all. */\nexport async function deleteAttachment(\n init: AttachmentInit & { attachmentId: string },\n): Promise<void> {\n const response = await fetch(\n `${attachmentsUrl(init)}/${encodeURIComponent(init.attachmentId)}`,\n {\n method: 'DELETE',\n headers: { 'X-Visitor-Token': init.visitorToken },\n signal: init.signal,\n },\n )\n if (!response.ok) throw await readError(response)\n}\n\n/**\n * The bytes of one file, as something a browser can draw.\n *\n * Fetched rather than linked, and this is the whole reason attachments carry no\n * URL: the route is opened by the visitor token, which travels in a header, and\n * a header is exactly what an `<img src>` cannot send. So the panel reads the\n * file itself and hands the caller an object URL — which the caller owns, and\n * has to revoke.\n */\nexport async function fetchAttachment(\n init: AttachmentInit & { attachmentId: string },\n): Promise<Blob> {\n const response = await fetch(\n `${attachmentsUrl(init)}/${encodeURIComponent(init.attachmentId)}/content`,\n { headers: { 'X-Visitor-Token': init.visitorToken }, signal: init.signal },\n )\n if (!response.ok) throw await readError(response)\n return response.blob()\n}\n\nfunction attachmentsUrl(init: AttachmentInit): string {\n return endpoint(\n init.apiUrl,\n `/public/conversations/${encodeURIComponent(init.conversationId)}/attachments`,\n )\n}\n\n/** Sends one message, and streams the answer as it is written. */\nexport async function sendMessage(init: SendMessageInit): Promise<ChatTurn> {\n return stream(\n endpoint(init.apiUrl, `/public/conversations/${encodeURIComponent(init.conversationId)}/messages`),\n {\n content: init.message,\n attachment_ids: init.attachmentIds ?? [],\n // Omitted rather than sent empty: the API tells an absent field from a\n // cleared one, and a page with nothing to say should say nothing.\n ...(init.context && Object.keys(init.context).length > 0\n ? { context: init.context }\n : {}),\n },\n init,\n )\n}\n\n/**\n * Answers the tool call a turn paused on, and lets the turn carry on.\n *\n * Streamed like a message, because it *is* the same turn continuing: the tokens the\n * agent writes after the call, then the stored answer — or another pause, if it asks\n * for a second tool needing a decision.\n */\nexport async function resolveApproval(init: ResolveApprovalInit): Promise<ChatTurn> {\n return stream(\n endpoint(init.apiUrl, `/public/conversations/${encodeURIComponent(init.conversationId)}/approvals`),\n { tool_call_id: init.toolCallId, approved: init.approved },\n init,\n )\n}\n\ninterface StreamInit {\n /** Where avatars named in the frames are read from. */\n apiUrl: string\n visitorToken: string\n subjectToken?: string\n onToken: (token: string) => void\n /** Told what the agent is busy with while it has written nothing yet. */\n onProgress?: (activity: ChatActivity) => void\n signal?: AbortSignal\n}\n\n/**\n * Plays one server-sent event stream, whatever started it.\n *\n * Frames are separated by a blank line, but a relay may forward the chunks as it\n * received them — so the buffer is split on lines and the remainder kept, which can\n * be a `data:` line cut in the middle.\n *\n * An `error` frame rejects: once the response is a 200 there is no status code left\n * to fail with, so the failure travels inside the stream and has to become one here.\n * Whatever tokens arrived before it are kept — half an answer already on somebody's\n * screen is not something to erase.\n */\nasync function stream(\n url: string,\n body: Record<string, unknown>,\n init: StreamInit,\n): Promise<ChatTurn> {\n const response = await fetch(url, {\n method: 'POST',\n headers: headers(init.visitorToken, init.subjectToken),\n // Every turn says which chat widgets this panel draws (level 1: since\n // 1.4.0). The backend teaches an agent the widget syntax only when it is\n // told so: an older panel would show the fences as code.\n body: JSON.stringify({ ...body, widgets: 1 }),\n signal: init.signal,\n })\n if (!response.ok) throw await readError(response)\n if (!response.body) throw new ChatHttpError('Answer with no stream body')\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n let event = ''\n let streamed = ''\n let failure: string | undefined\n let handedTo: string | undefined\n const turn: ChatTurn = { answer: '' }\n\n try {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n\n for (const raw of lines) {\n const line = raw.trim()\n if (!line) {\n // A blank line ends a frame; the name does not carry over to the next.\n event = ''\n continue\n }\n if (line.startsWith('event:')) {\n event = line.slice(6).trim()\n continue\n }\n if (!line.startsWith('data:')) continue\n\n const payload = line.slice(5).trim()\n if (!payload) continue\n let frame: Record<string, unknown>\n try {\n frame = JSON.parse(payload) as Record<string, unknown>\n } catch {\n continue\n }\n\n if (event === 'token' && typeof frame.text === 'string') {\n streamed += frame.text\n init.onToken(frame.text)\n } else if (event === 'progress') {\n init.onProgress?.(toActivity(frame.activity))\n } else if (event === 'done') {\n turn.answer = typeof frame.content === 'string' ? frame.content : streamed\n turn.agent = toHandle(frame.agent, init.apiUrl)\n if (typeof frame.unknown_handle === 'string' && frame.unknown_handle) {\n turn.unknownHandle = frame.unknown_handle\n turn.offered = toHandles(frame.handles, init.apiUrl)\n }\n } else if (event === 'handoff') {\n // Another agent of the team answers from here; whatever came before it\n // was the other agent's, and the answer is what follows.\n if (typeof frame.to_agent_name === 'string') handedTo = frame.to_agent_name\n streamed = ''\n } else if (event === 'escalated') {\n turn.withHuman = true\n } else if (event === 'held') {\n turn.held = true\n turn.withHuman = true\n } else if (event === 'approval_required') {\n turn.approval = toApproval(frame)\n } else if (event === 'error') {\n failure = typeof frame.detail === 'string' ? frame.detail : 'The turn failed'\n }\n }\n if (failure) break\n }\n } finally {\n // Releases the connection even on abort or mid-stream failure.\n void reader.cancel().catch(() => undefined)\n }\n\n if (failure) throw new ChatHttpError(failure)\n if (!turn.answer && !turn.approval) turn.answer = streamed\n if (handedTo && !turn.agent) turn.authorName = handedTo\n return turn\n}\n","/**\n * Remembers which conversation this panel is having, so a reload keeps it.\n *\n * Without this, refreshing the host page silently opened a second conversation and\n * left the first one unreachable — the visitor's own transcript, gone, with no way\n * back to it. What is stored is the pair the API needs to read it again: the id it\n * named, and the visitor token that is the whole of the authorization on it.\n *\n * `sessionStorage`, like the panel's open state and for a sharper reason: that token\n * *is* the credential. One tab's lifetime covers the reload and a navigation inside\n * the host app, which is what this exists for, and it does not leave a working key\n * to somebody's conversation on a shared machine for weeks. Reopening the browser\n * tomorrow starts a new conversation, which for a support panel is the honest\n * default.\n *\n * The embed key and the claimed user id travel with it, and both are checked before\n * anything is replayed. A remembered conversation belongs to one application and to\n * one person: a page that switched applications, or on which somebody else signed\n * in, has to start again — relabelling a transcript is exactly what the author claim\n * exists to prevent.\n */\n\n/** One entry per host origin — enough while a page mounts a single widget, which\n * is the case for every current integrator. */\nconst CONVERSATION_KEY = 'squadico-chatbot:conversation'\n\nexport interface StoredConversation {\n sessionId: string\n visitorToken: string\n /** Which application it was opened on. A different one is a different panel. */\n embedKey: string\n /** Who the host said was in front of it, when it said anybody. */\n user?: string\n /** The host's own partition of its users' conversations (an organization, a\n * workspace), when it gave one. */\n scope?: string\n /** The agent of the rail this conversation is with. Absent on entries written\n * before a panel had one conversation per agent. */\n agent?: string\n}\n\n/** The pair that reads a conversation back. */\ninterface Credentials {\n sessionId: string\n visitorToken: string\n}\n\n/**\n * What is stored: the conversation the panel was last showing — read back on a\n * reload — and, beside it, every agent's conversation, so going back to an agent\n * of the rail finds its own. One key rather than one per agent, so starting over\n * forgets them all at once.\n */\ninterface Entry extends Partial<StoredConversation> {\n threads?: Record<string, Credentials>\n}\n\nfunction readEntry(): Entry | undefined {\n try {\n if (typeof sessionStorage === 'undefined') return undefined\n const raw = sessionStorage.getItem(CONVERSATION_KEY)\n if (!raw) return undefined\n const parsed: unknown = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : undefined\n } catch {\n // Storage unavailable (private browsing, blocked cookies…) or unparseable.\n return undefined\n }\n}\n\nfunction writeEntry(entry: Entry): void {\n try {\n if (typeof sessionStorage === 'undefined') return\n sessionStorage.setItem(CONVERSATION_KEY, JSON.stringify(entry))\n } catch {\n /* see readConversation: the conversation stays volatile, as it used to be */\n }\n}\n\nfunction credentials(value: unknown): Credentials | undefined {\n if (!value || typeof value !== 'object') return undefined\n const { sessionId, visitorToken } = value as Partial<Credentials>\n return typeof sessionId === 'string' && sessionId && typeof visitorToken === 'string' && visitorToken\n ? { sessionId, visitorToken }\n : undefined\n}\n\n/** The conversation this page was having — with `agent`, the one it was having\n * with that agent of the rail — if it is still the same page's.\n *\n * `undefined` for anything that does not read back as a conversation: nothing\n * stored, storage refused, a half-written entry from an interrupted write. None of\n * those is worth an error — the panel opens a new conversation, which is what it\n * did before it remembered any. */\nexport function readConversation(agent?: string): StoredConversation | undefined {\n const entry = readEntry()\n if (!entry || typeof entry.embedKey !== 'string' || !entry.embedKey) return undefined\n const active = typeof entry.agent === 'string' ? entry.agent : undefined\n // An entry naming no agent was written before the rail kept one conversation\n // per agent: it is the conversation the panel was having, whoever it is with.\n const pair =\n agent === undefined || active === undefined || agent === active\n ? credentials(entry)\n : credentials(entry.threads?.[agent])\n if (!pair) return undefined\n return {\n ...pair,\n embedKey: entry.embedKey,\n user: typeof entry.user === 'string' ? entry.user : undefined,\n scope: typeof entry.scope === 'string' ? entry.scope : undefined,\n agent: agent ?? active,\n }\n}\n\n/** Remembers `conversation` as the one the panel is showing, and as its agent's. */\nexport function writeConversation(conversation: StoredConversation): void {\n const previous = readEntry()\n // Another application's or another person's conversations are not kept beside\n // this one: they could never be read back here.\n const kept = previous && belongsTo(previous, conversation) ? (previous.threads ?? {}) : {}\n const threads = conversation.agent\n ? {\n ...kept,\n [conversation.agent]: {\n sessionId: conversation.sessionId,\n visitorToken: conversation.visitorToken,\n },\n }\n : kept\n writeEntry({ ...conversation, threads })\n}\n\n/** Forgets every conversation — or, with `agent`, only the one with that agent. */\nexport function forgetConversation(agent?: string): void {\n if (agent !== undefined) {\n const entry = readEntry()\n if (!entry) return\n const threads = { ...(entry.threads ?? {}) }\n delete threads[agent]\n const active = entry.agent === undefined || entry.agent === agent\n writeEntry(\n active\n ? {\n embedKey: entry.embedKey,\n user: entry.user,\n scope: entry.scope,\n threads,\n }\n : { ...entry, threads },\n )\n return\n }\n try {\n if (typeof sessionStorage === 'undefined') return\n sessionStorage.removeItem(CONVERSATION_KEY)\n } catch {\n /* see readConversation */\n }\n}\n\n/**\n * Whether a remembered conversation is one *this* panel may carry on.\n *\n * Checked here rather than at each call site so the two reasons to drop one stay\n * together: it belongs to another application, or to another person.\n */\nexport function belongsTo(\n conversation: Pick<Partial<StoredConversation>, 'embedKey' | 'user' | 'scope'>,\n { embedKey, user, scope }: { embedKey: string; user?: string; scope?: string },\n): boolean {\n return conversation.embedKey === embedKey && conversation.user === user && conversation.scope === scope\n}\n","/**\n * State machine of a conversation: opening it, playing turns, deciding a paused\n * tool call, aborting, starting over. Kept out of the rendering so it stays\n * testable and reusable by both wrappers (custom element and React wrapper).\n *\n * **The conversation is opened by the server, once, on the first message.** A panel\n * shown is not a conversation had: opening one when the launcher was clicked filled\n * the back office with conversations holding a welcome message and nothing else. So\n * showing the panel only reads what it draws — the welcome message, the picker, the\n * branding — and the open call waits for the first message or the first file. The\n * id and the visitor token both come back from it: a visitor allowed to name their\n * own conversation is a visitor choosing which one to read.\n *\n * **And it survives a reload.** The pair is remembered for the tab, and a panel that\n * finds one replays it instead of opening a second conversation and orphaning the\n * first. A remembered conversation belongs to one application and to one person: a\n * page that switched either starts again, and one the API no longer knows about is\n * dropped rather than left to break every turn.\n *\n * **A paused turn is answered, not talked around.** The agent stops before calling a\n * tool and says what it would do; the buttons release it. Typing something else\n * instead is a decision too — the call was never approved, so it never runs, and the\n * backend closes it as the new question goes out. That is why what the user types is\n * always a new message here and never a correction squeezed into a pending decision.\n *\n * **Changing who the host says is in front of the panel opens a new conversation.**\n * Relabelling the old one would put two people's turns under one name, which is\n * exactly what the author claim exists to prevent.\n *\n * **The page context is translated, not forwarded.** A host writes\n * `order: { id, name }` because the chip shows the name; the API takes scalars. The\n * pair goes on the wire and the object stays on screen.\n *\n * **One conversation per agent of the rail.** Switching to an agent shows its own\n * conversation: its welcome message while nothing was said, what was said when\n * something was. Each is opened on its agent, the server keeps it with them, and\n * the one left behind is kept — in memory and for the tab — to be found again.\n *\n * **A handle is text, never a field.** The server parses the message for the agent\n * it addresses, so `agent` opens the conversation on one and the picker writes one\n * into what somebody is typing. Nothing here routes: a client naming its own agent\n * would be a client choosing its own router.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks'\n\nimport type {\n AgentHandle,\n ChatActivity,\n ChatAttachment,\n ChatbotContext,\n ChatbotEvent,\n ChatMessage,\n HostUser,\n PendingApproval,\n SubjectTokenSource,\n} from '../types'\nimport {\n ChatHttpError,\n API_URL,\n openConversation,\n previewApplication,\n replayConversation,\n resolveApproval,\n deleteAttachment,\n fetchAttachment,\n sendMessage,\n uploadAttachment,\n} from './client'\nimport type { OpenedConversation } from './client'\nimport { belongsTo, forgetConversation, readConversation, writeConversation } from './conversation'\nimport { wireContext } from './context'\nimport { resolveLocale, type Locale } from './i18n'\nimport { uuid } from './uid'\n\n/**\n * Asks the page for the token it holds for its signed-in user, right before a turn\n * goes out. A page with nobody signed in — or a source that fails — sends none,\n * and the turn goes on without acting as anybody.\n */\nasync function subjectTokenOf(source: SubjectTokenSource | undefined): Promise<string | undefined> {\n if (!source) return undefined\n try {\n return (await source()) || undefined\n } catch {\n return undefined\n }\n}\n\nexport interface UseChatOptions {\n /** Where the calls go. Not reachable from the element or the React wrapper:\n * the built-in `API_URL` is the only server a page gets, and this exists for\n * the tests to name theirs. */\n apiUrl?: string\n /** Public key of the application this page embeds. Nothing happens without it. */\n embedKey?: string\n /** Who the host application has signed in, when it has anybody. */\n user?: HostUser\n /** The host's partition of conversations (an organization, a workspace): a\n * conversation opened under another scope is never replayed or continued. */\n scope?: string\n /** Hands over the access token the host site holds for its signed-in user, asked\n * before every message so it is always fresh. See `ChatbotProps`. */\n getSubjectToken?: SubjectTokenSource\n /** The handle to open the conversation on, for a page that knows who should\n * answer. The visitor can still address somebody else afterwards. */\n agent?: string\n context?: ChatbotContext\n greeting?: string\n /** Language of the error bubble — the only text this module writes. Resolved by\n * the widget; the package's default language otherwise. */\n locale?: Locale\n onEvent?: (event: ChatbotEvent) => void\n /** How often a conversation a human handles is read again, in ms: their replies\n * are not streamed. */\n humanPollMs?: number\n}\n\nexport interface UseChatResult {\n messages: ChatMessage[]\n /** A turn is in flight (request sent, answer not finished yet). */\n busy: boolean\n /** The conversation's id, as the server named it. Empty until it is opened. */\n sessionId: string\n /** Counts the times the conversation was dropped, so a panel that stays open\n * can tell it has to read what an empty panel draws again. */\n resets: number\n /** The handles this application offers a visitor. Empty until an organization\n * ticks one, which is the ordinary case. */\n handles: AgentHandle[]\n /** The handle the conversation opened on, as the server resolved it — not the one\n * that was asked for, which it may have fallen back from. Empty until it opens,\n * and empty when the page named nobody: the default agent needs no announcing. */\n addressee: string\n /** The agent this panel is talking to: the one a rail click switched to, else\n * the one the conversation opened on, as the server resolved it. What the agent\n * rail marks. */\n agentHandle: string\n /** The shortcuts the agent talked to offers under its welcome message. Empty\n * when it names none. */\n welcomeSuggestions: string[]\n /** The tool call awaiting a decision, or `null` the rest of the time. */\n approval: PendingApproval | null\n /** Whether the panel shows \"Powered by Squadico\": the organization's plan says,\n * and nothing does until the panel is shown. */\n branding: boolean\n /** An agent handed the conversation to a human of the organization: no agent\n * answers, and what they reply shows as the conversation is read again. */\n withHuman: boolean\n /** What the panel calls when it is shown: replays the conversation remembered for\n * this tab, or reads the welcome message, the handles and the branding — and opens\n * nothing. Idempotent. */\n start: () => void\n send: (text: string) => void\n /** The files the next question will carry, in the order they were picked. */\n attachments: ChatAttachment[]\n /** The names of the files still going up, so a slow upload is visible. */\n uploading: string[]\n /** Why the last upload was refused, as a key the panel translates. Null when\n * the last one was accepted — a refusal is about the file just picked, not a\n * state the conversation stays in. */\n attachmentError: AttachmentRefusal | null\n /** Puts one file on the conversation, opening it if it is not open yet. */\n attach: (file: File) => void\n /** Takes one back out, bytes and all. */\n detach: (attachmentId: string) => void\n /** Reads the bytes of a file a turn carried — what draws a picture back. */\n loadAttachment: (attachmentId: string) => Promise<Blob>\n /** Answers the paused call. `label` is what is shown on the user's side in the\n * history (\"Yes\" or \"No\"). */\n decide: (approved: boolean, label: string) => void\n stop: () => void\n /** Forget this conversation and open another one on the next message. */\n reset: () => void\n /** Shows the conversation with another agent of the application: the one had\n * with them earlier, else their welcome message and a conversation opened on\n * them at the first message. Ignored while a turn is in flight. */\n switchTo: (handle: string) => void\n}\n\n/** Id of the welcome message drawn from the preview, before any conversation\n * exists. The stored one replaces it once the conversation opens. */\nconst PREVIEW_WELCOME_ID = 'preview-welcome'\n\n/** One key for who is in front of the panel and under which scope. */\nfunction scopeKey(user?: string, scope?: string): string | undefined {\n return user === undefined && scope === undefined ? undefined : JSON.stringify([user, scope])\n}\n\n/** Where the calls go and who they are for, read off the props when they are made. */\ninterface Target {\n opts: UseChatOptions\n apiUrl: string\n embedKey: string\n claim?: HostUser\n scope?: string\n}\n\n/** What a conversation with one agent of the rail holds while another is shown. */\ninterface Thread {\n conversation: OpenConversation | null\n messages: ChatMessage[]\n welcomeSuggestions: string[]\n approval: PendingApproval | null\n withHuman: boolean\n attachments: ChatAttachment[]\n}\n\ninterface OpenConversation {\n /** The conversation's id. Still named `sessionId` because it is what\n * `sessionStorage` holds and what the host page is told in every event. */\n sessionId: string\n visitorToken: string\n}\n\n/** Why an upload was refused, in terms a panel can translate. */\nexport type AttachmentRefusal = 'unsupported' | 'tooLarge' | 'tooMany' | 'unreadable' | 'failed'\n\n/**\n * What a refused upload means, read off the status.\n *\n * Each one is a different instruction to whoever picked the file — send another\n * format, send something smaller, remove one first — which is why they are not\n * one message with a number in it.\n */\nfunction refusalOf(error: unknown): AttachmentRefusal {\n const status = error instanceof ChatHttpError ? error.status : undefined\n if (status === 415) return 'unsupported'\n if (status === 413) return 'tooLarge'\n if (status === 409) return 'tooMany'\n if (status === 422) return 'unreadable'\n return 'failed'\n}\n\n/** What a turn came back with, beyond its text: who answered, what it stopped on,\n * and the name it addressed that nobody here answers to. */\ntype TurnResult = {\n answer: string\n agent?: AgentHandle\n approval?: PendingApproval\n unknownHandle?: string\n offered?: AgentHandle[]\n authorName?: string\n withHuman?: boolean\n held?: boolean\n}\n\n/** How often a conversation a human handles is read again, by default. */\nconst HUMAN_POLL_MS = 5_000\n\n/** Whether a refusal means \"this conversation is over, open another one\".\n *\n * The code and not the status: 409 is also what an application with nothing\n * answering on it replies, and reopening would not help there. */\nfunction retired(error: unknown): boolean {\n return error instanceof ChatHttpError && error.code === 'conversation_retired'\n}\n\nexport function useChat(options: UseChatOptions): UseChatResult {\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [busy, setBusy] = useState(false)\n const [sessionId, setSessionId] = useState('')\n const [resets, setResets] = useState(0)\n const [handles, setHandles] = useState<AgentHandle[]>([])\n const [addressee, setAddressee] = useState('')\n const [agentHandle, setAgentHandle] = useState('')\n const [approval, setApproval] = useState<PendingApproval | null>(null)\n const [welcomeSuggestions, setWelcomeSuggestions] = useState<string[]>([])\n const [withHuman, setWithHuman] = useState(false)\n const [branding, setBranding] = useState(false)\n const [attachments, setAttachments] = useState<ChatAttachment[]>([])\n const [uploading, setUploading] = useState<string[]>([])\n const [attachmentError, setAttachmentError] = useState<AttachmentRefusal | null>(null)\n const abortRef = useRef<AbortController | null>(null)\n\n // Async closures read the props through a ref: without it, a turn started before\n // a context update would send the stale value.\n const latest = useRef(options)\n latest.current = options\n\n // The open call, kept as a promise so two turns starting at once — a click on a\n // suggestion while the panel is opening — share one conversation instead of\n // opening two.\n const opening = useRef<Promise<OpenConversation> | null>(null)\n const conversation = useRef<OpenConversation | null>(null)\n // The replay of the remembered conversation, shared the same way: the panel shown\n // and a message sent at once must not replay it twice and draw it twice.\n const resuming = useRef<Promise<OpenConversation | null> | null>(null)\n // What showing the panel set off, kept so showing it again reads nothing twice.\n const showing = useRef<Promise<void> | null>(null)\n // Which claim the current conversation was opened under, so a change of host user\n // can be told from a re-render.\n const openedFor = useRef<string | undefined>(undefined)\n // The agent of the rail this panel is talking to — undefined until something\n // says who: the page, the remembered conversation, the preview.\n const thread = useRef<string | undefined>(undefined)\n // The agent the panel first landed on: a conversation with them opens as the\n // page asked, without naming anybody the page did not.\n const home = useRef<string | undefined>(undefined)\n // The conversations with the other agents, as they were left.\n const threads = useRef(new Map<string, Thread>())\n // What the shown conversation holds, read synchronously when switching away.\n const shown = useRef<Thread>({\n conversation: null,\n messages: [],\n welcomeSuggestions: [],\n approval: null,\n withHuman: false,\n attachments: [],\n })\n shown.current = { conversation: conversation.current, messages, welcomeSuggestions, approval, withHuman, attachments }\n\n const greeting = options.greeting\n const greetingMessage = useMemo<ChatMessage | null>(\n () =>\n greeting\n ? { id: 'greeting', role: 'assistant', content: greeting, createdAt: Date.now() }\n : null,\n [greeting],\n )\n\n const emit = useCallback((event: ChatbotEvent) => {\n latest.current.onEvent?.(event)\n }, [])\n\n const patch = useCallback((id: string, changes: Partial<ChatMessage>) => {\n setMessages((current) =>\n current.map((message) => (message.id === id ? { ...message, ...changes } : message)),\n )\n }, [])\n\n const fail = useCallback(\n (error: unknown, replyId?: string) => {\n const status = error instanceof ChatHttpError ? error.status : undefined\n const detail = error instanceof Error ? error.message : String(error)\n const message = (latest.current.locale ?? resolveLocale(undefined)).t.error\n if (replyId) {\n patch(replyId, { content: message, streaming: false, error: true, activity: undefined })\n }\n emit({\n type: 'chatbot-error',\n message: detail,\n status,\n sessionId: conversation.current?.sessionId ?? '',\n })\n if (typeof console !== 'undefined') {\n console.error('[squadico-chatbot]', detail)\n }\n },\n [emit, patch],\n )\n\n const target = useCallback((): Target => {\n const opts = latest.current\n if (!opts.embedKey) {\n throw new ChatHttpError('No embed key: nothing says which application to open')\n }\n return { opts, apiUrl: opts.apiUrl ?? API_URL, embedKey: opts.embedKey, claim: opts.user, scope: opts.scope }\n }, [])\n\n /** Makes a conversation the API answered with the one this panel is having. */\n const adopt = useCallback((t: Target, opened: OpenedConversation, agent?: string): OpenConversation => {\n const open = { sessionId: opened.conversationId, visitorToken: opened.visitorToken }\n conversation.current = open\n openedFor.current = scopeKey(t.claim?.id, t.scope)\n // Kept under the agent it was opened with, not the one holding it now: a\n // conversation an agent passed on is still the one found under the first.\n const owner = agent ?? thread.current ?? opened.agentHandle\n thread.current = owner\n home.current ??= owner\n writeConversation({ ...open, embedKey: t.embedKey, user: t.claim?.id, scope: t.scope, agent: owner })\n setSessionId(opened.conversationId)\n setHandles(opened.handles)\n // Announced only when the page asked for somebody: showing the default\n // agent's own handle would put an `@support` in every composer.\n setAddressee(t.opts.agent && opened.agentHandle ? opened.agentHandle : '')\n setAgentHandle(owner ?? '')\n setWelcomeSuggestions(opened.welcomeSuggestions)\n setWithHuman(Boolean(opened.withHuman))\n setBranding(opened.branding)\n // Prepended rather than appended: whatever the panel put on screen while it\n // was opening comes after what the conversation already held. The welcome\n // message drawn from the preview gives way to the one the conversation stored.\n setMessages((current) => [\n ...opened.messages,\n ...current.filter((message) => message.id !== PREVIEW_WELCOME_ID),\n ])\n return open\n }, [])\n\n /**\n * The conversation remembered for this tab, replayed — or null when there is none\n * this panel may pick up.\n *\n * A conversation the API no longer knows about — deleted, or opened against an\n * application that is gone — is dropped rather than retried: a panel that gave\n * up here is a panel one reload broke for good.\n */\n const resume = useCallback(\n (t: Target): Promise<OpenConversation | null> => {\n if (resuming.current) return resuming.current\n const asked = thread.current\n const remembered = readConversation(asked)\n if (!remembered || !belongsTo(remembered, { embedKey: t.embedKey, user: t.claim?.id, scope: t.scope })) {\n return Promise.resolve(null)\n }\n const play = replayConversation({\n apiUrl: t.apiUrl,\n conversationId: remembered.sessionId,\n visitorToken: remembered.visitorToken,\n })\n // Switched to another agent while this was read: theirs is shown now,\n // and this one is read again when somebody comes back to it.\n .then((opened) => (thread.current === asked ? adopt(t, opened, remembered.agent) : null))\n .catch(() => {\n forgetConversation(remembered.agent)\n return null\n })\n .finally(() => {\n resuming.current = null\n })\n resuming.current = play\n return play\n },\n [adopt],\n )\n\n /**\n * The conversation this panel is having, opening it if it has none.\n *\n * Only what a visitor *does* calls this — a message, a file. Showing the panel\n * does not: a panel shown is not a conversation had.\n */\n const conversationNow = useCallback(async (): Promise<OpenConversation> => {\n if (conversation.current) return conversation.current\n if (opening.current) return opening.current\n\n const t = target()\n const play = resume(t).then(\n (resumed) =>\n resumed ??\n openConversation({\n apiUrl: t.apiUrl,\n embedKey: t.embedKey,\n user: t.claim,\n // The agent switched to, else only the one the page named: an\n // application always has an agent answering plain text, and the panel\n // has nothing to announce for it.\n agent: thread.current && thread.current !== home.current ? thread.current : t.opts.agent,\n }).then((opened) => adopt(t, opened)),\n )\n\n opening.current = play\n try {\n return await play\n } finally {\n opening.current = null\n }\n }, [adopt, resume, target])\n\n /**\n * What the panel calls when it is shown.\n *\n * Replays the remembered conversation if there is one, and otherwise reads what\n * an empty panel draws: the welcome message — an empty panel with a name on it\n * says nothing about what may be asked — the handles and the branding. Nothing\n * is opened, so a visitor who clicks the launcher and leaves leaves no trace.\n */\n const start = useCallback(() => {\n if (conversation.current || opening.current || showing.current) return\n let t: Target\n try {\n t = target()\n } catch (error: unknown) {\n fail(error)\n return\n }\n const asked = thread.current\n const show = resume(t).then(async (resumed) => {\n if (resumed || conversation.current || opening.current) return\n const preview = await previewApplication({\n apiUrl: t.apiUrl,\n embedKey: t.embedKey,\n agent: asked ?? t.opts.agent,\n })\n // A message sent while this was on its way opened the conversation, and\n // what it answered with already drew all of this. Or somebody switched to\n // another agent, whose welcome message is the one to draw.\n if (conversation.current || opening.current || thread.current !== asked) return\n thread.current = asked ?? preview.agentHandle\n home.current ??= thread.current\n setHandles(preview.handles)\n setAddressee(t.opts.agent && preview.agentHandle ? preview.agentHandle : '')\n setAgentHandle(thread.current ?? '')\n setWelcomeSuggestions(preview.welcomeSuggestions)\n setBranding(preview.branding)\n const welcome = preview.welcomeMessage\n if (welcome) {\n setMessages((current) =>\n current.length > 0\n ? current\n : [\n {\n id: PREVIEW_WELCOME_ID,\n role: 'assistant',\n content: welcome,\n createdAt: Date.now(),\n agent: preview.agent,\n },\n ],\n )\n }\n })\n showing.current = show\n show.catch((error: unknown) => {\n // Read again the next time the panel is shown, rather than never.\n showing.current = null\n fail(error)\n })\n }, [fail, resume, target])\n\n /**\n * Common body of a turn: appends the pair of bubbles, plays `run`, and publishes\n * what came back — the answer, and the call it stopped on if it stopped.\n */\n const turn = useCallback(\n (\n userText: string,\n run: (\n open: OpenConversation,\n onToken: (text: string) => void,\n signal: AbortSignal,\n onProgress: (activity: ChatActivity) => void,\n ) => Promise<TurnResult>,\n { retry = false, carried = [] }: { retry?: boolean; carried?: ChatAttachment[] } = {},\n ) => {\n if (abortRef.current) return\n\n const controller = new AbortController()\n abortRef.current = controller\n setBusy(true)\n // The buttons of the previous turn are worth nothing now: the decision has\n // just been made, or the user moved on and the backend closed the call.\n setApproval(null)\n\n const replyId = uuid()\n setMessages((current) => [\n ...current,\n {\n id: uuid(),\n role: 'user',\n content: userText,\n createdAt: Date.now(),\n // Drawn from what the composer was holding rather than waited for: the\n // files were accepted before the message left, and a question whose\n // picture appears two seconds later reads as one that failed.\n attachments: carried.length > 0 ? carried : undefined,\n },\n { id: replyId, role: 'assistant', content: '', createdAt: Date.now(), streaming: true },\n ])\n\n const play = async (): Promise<void> => {\n let open = await conversationNow()\n emit({\n type: 'chatbot-message',\n role: 'user',\n content: userText,\n sessionId: open.sessionId,\n })\n let streamed = ''\n const onToken = (chunk: string): void => {\n streamed += chunk\n // The first word is the end of the wait: what the agent was busy with\n // gives way to what it says.\n patch(replyId, { content: streamed, activity: undefined })\n }\n const onProgress = (activity: ChatActivity): void => {\n // Only while nothing is written: a tool called halfway through an\n // answer does not cover the words already on the screen.\n if (!streamed) patch(replyId, { activity })\n }\n let result: TurnResult\n try {\n result = await run(open, onToken, controller.signal, onProgress)\n } catch (error: unknown) {\n if (!retired(error)) throw error\n // The organization rotated the embed key, so this conversation is over\n // and the remembered one is worthless. Refused before anything was\n // stored or streamed, which is what makes replaying it here safe rather\n // than a second question the visitor did not ask.\n forgetConversation(thread.current)\n conversation.current = null\n opening.current = null\n if (!retry) throw error\n open = await conversationNow()\n streamed = ''\n patch(replyId, { content: '', activity: undefined })\n result = await run(open, onToken, controller.signal, onProgress)\n }\n if (result.withHuman) setWithHuman(true)\n if (result.held) {\n // Kept for the human: no agent ran, so there is no answer to draw.\n setMessages((current) => current.filter((message) => message.id !== replyId))\n return\n }\n patch(replyId, {\n content: result.answer,\n streaming: false,\n activity: undefined,\n agent: result.agent,\n authorName: result.authorName,\n approval: result.approval,\n // Kept on the answer it arrived with: the question was answered, and\n // what the panel adds is who could have been asked instead.\n unknownHandle: result.unknownHandle,\n offered: result.offered,\n })\n setApproval(result.approval ?? null)\n emit({\n type: 'chatbot-message',\n role: 'assistant',\n content: result.answer,\n sessionId: open.sessionId,\n agent: result.agent?.handle,\n })\n }\n\n void play()\n .catch((error: unknown) => {\n // A deliberate abort is not an error: keep the text already received.\n if (controller.signal.aborted) {\n patch(replyId, { streaming: false, activity: undefined })\n return\n }\n fail(error, replyId)\n })\n .finally(() => {\n abortRef.current = null\n setBusy(false)\n })\n },\n [conversationNow, emit, fail, patch],\n )\n\n const send = useCallback(\n (raw: string) => {\n const text = raw.trim()\n // A file on its own is a turn, and a question about the file. What is\n // refused is the turn carrying neither words nor a file.\n if (!text && attachments.length === 0) return\n // Emptied before the run rather than after it: the files have left with the\n // question, and a composer still showing them would offer to remove part of\n // a turn already on its way.\n const carried = attachments\n setAttachments([])\n setAttachmentError(null)\n turn(\n text,\n async (open, onToken, signal, onProgress) =>\n sendMessage({\n subjectToken: await subjectTokenOf(latest.current.getSubjectToken),\n apiUrl: latest.current.apiUrl ?? API_URL,\n conversationId: open.sessionId,\n visitorToken: open.visitorToken,\n message: text,\n attachmentIds: carried.map((file) => file.id),\n // Shaped for the wire here and not by the host: `order: { id, name }`\n // is how a page writes it — the chip shows the name — while the API\n // takes text, numbers and booleans, so the pair `orderId` +\n // `orderName` is what travels. Sending the nested object earns a 422\n // and no answer.\n context: latest.current.context ? wireContext(latest.current.context) : undefined,\n onToken,\n onProgress,\n signal,\n }),\n // A question refused because the key was rotated is asked again on the\n // fresh conversation: the visitor typed it once, and nothing was stored.\n //\n // Its files are not carried over: they belong to the conversation that\n // was retired, and the ids mean nothing on the new one. The question is\n // asked again, without them, rather than failing on an id nobody knows.\n { retry: true, carried },\n )\n },\n [attachments, turn],\n )\n\n /**\n * Puts one file on the conversation, before the question that will carry it.\n *\n * Opens the conversation if it is not open yet: a visitor may well pick a file\n * before typing anything, and a file has to belong to a conversation to exist\n * at all.\n */\n const attach = useCallback(\n (file: File) => {\n setAttachmentError(null)\n setUploading((waiting) => [...waiting, file.name])\n void conversationNow()\n .then((open) =>\n uploadAttachment({\n apiUrl: latest.current.apiUrl ?? API_URL,\n conversationId: open.sessionId,\n visitorToken: open.visitorToken,\n file,\n }),\n )\n .then((accepted) => setAttachments((files) => [...files, accepted]))\n .catch((error: unknown) => setAttachmentError(refusalOf(error)))\n .finally(() =>\n setUploading((waiting) => {\n const at = waiting.indexOf(file.name)\n return at < 0 ? waiting : [...waiting.slice(0, at), ...waiting.slice(at + 1)]\n }),\n )\n },\n [conversationNow],\n )\n\n /**\n * Takes a file back out of the draft.\n *\n * Dropped from the list first and asked of the server second: the visitor\n * clicked a cross, and a chip that lingers until a round trip finishes reads as\n * a click that did nothing. A delete that fails leaves a file the draft no\n * longer names — an abandoned draft, which the API already knows what to do\n * with.\n */\n const detach = useCallback(\n (attachmentId: string) => {\n setAttachments((files) => files.filter((file) => file.id !== attachmentId))\n const open = conversation.current\n if (!open) return\n void deleteAttachment({\n apiUrl: latest.current.apiUrl ?? API_URL,\n conversationId: open.sessionId,\n visitorToken: open.visitorToken,\n attachmentId,\n }).catch(() => {\n // Nothing to tell anybody: the file is out of the draft either way.\n })\n },\n [],\n )\n\n const loadAttachment = useCallback(async (attachmentId: string): Promise<Blob> => {\n const open = conversation.current\n if (!open) throw new ChatHttpError('No conversation to read that file from')\n return fetchAttachment({\n apiUrl: latest.current.apiUrl ?? API_URL,\n conversationId: open.sessionId,\n visitorToken: open.visitorToken,\n attachmentId,\n })\n }, [])\n\n const decide = useCallback(\n (approved: boolean, label: string) => {\n const waiting = approval\n if (!waiting) return\n turn(label, async (open, onToken, signal, onProgress) =>\n resolveApproval({\n subjectToken: await subjectTokenOf(latest.current.getSubjectToken),\n apiUrl: latest.current.apiUrl ?? API_URL,\n conversationId: open.sessionId,\n visitorToken: open.visitorToken,\n toolCallId: waiting.toolCallId,\n approved,\n onToken,\n onProgress,\n signal,\n }),\n )\n },\n [approval, turn],\n )\n\n const stop = useCallback(() => {\n abortRef.current?.abort()\n abortRef.current = null\n setBusy(false)\n }, [])\n\n const reset = useCallback(() => {\n abortRef.current?.abort()\n abortRef.current = null\n conversation.current = null\n opening.current = null\n resuming.current = null\n showing.current = null\n openedFor.current = undefined\n // Every agent's conversation, not only the one shown: starting over is\n // starting over, and a new person in front of the panel must find none.\n threads.current.clear()\n // Forgotten as well as dropped: a reload that replayed the conversation\n // somebody just started over would undo the gesture.\n forgetConversation()\n setBusy(false)\n setApproval(null)\n setWithHuman(false)\n setSessionId('')\n setResets((count) => count + 1)\n setAddressee('')\n setAttachments([])\n setMessages([])\n setWelcomeSuggestions([])\n emit({ type: 'chatbot-reset', sessionId: '' })\n }, [emit])\n\n const switchTo = useCallback(\n (handle: string) => {\n if (abortRef.current || opening.current || handle === thread.current) return\n if (thread.current !== undefined) threads.current.set(thread.current, shown.current)\n thread.current = handle\n setAgentHandle(handle)\n setAttachmentError(null)\n const parked = threads.current.get(handle)\n threads.current.delete(handle)\n conversation.current = parked?.conversation ?? null\n resuming.current = null\n showing.current = null\n setMessages(parked?.messages ?? [])\n setWelcomeSuggestions(parked?.welcomeSuggestions ?? [])\n setApproval(parked?.approval ?? null)\n setWithHuman(parked?.withHuman ?? false)\n setAttachments(parked?.attachments ?? [])\n setSessionId(parked?.conversation?.sessionId ?? '')\n if (parked?.conversation) {\n // Shown again, so it is the one a reload brings back.\n try {\n const t = target()\n writeConversation({\n ...parked.conversation,\n embedKey: t.embedKey,\n user: t.claim?.id,\n scope: t.scope,\n agent: handle,\n })\n } catch {\n /* no embed key: nothing was ever opened, so nothing to remember */\n }\n return\n }\n // Never shown yet: its remembered conversation, else its welcome message.\n start()\n },\n [start, target],\n )\n\n // A human handles the conversation: their replies arrive with nobody streaming\n // them, so the conversation is read again until the agents have it back.\n const pollMs = options.humanPollMs ?? HUMAN_POLL_MS\n useEffect(() => {\n if (!withHuman || !sessionId) return\n const timer = setInterval(() => {\n const open = conversation.current\n if (!open || abortRef.current) return\n void replayConversation({\n apiUrl: latest.current.apiUrl ?? API_URL,\n conversationId: open.sessionId,\n visitorToken: open.visitorToken,\n })\n .then((replayed) => {\n // Another agent's conversation shown since: this one is not on screen.\n if (conversation.current !== open) return\n setMessages(replayed.messages)\n setWithHuman(Boolean(replayed.withHuman))\n })\n .catch(() => {\n // A missed read is caught up by the next one.\n })\n }, pollMs)\n return () => clearInterval(timer)\n }, [withHuman, sessionId, pollMs])\n\n // A different person in front of the panel is a different conversation: their\n // turns must not land under somebody else's name.\n const claimId = scopeKey(options.user?.id, options.scope)\n useEffect(() => {\n if (conversation.current) {\n if (openedFor.current !== claimId) reset()\n return\n }\n // Shown before the host said who and where — a framework sets properties in\n // an effect, after the element mounted: the conversation remembered for them\n // can only be found now. A reload or a link inside the host app lands here.\n if (!showing.current || opening.current) return\n let t: Target\n try {\n t = target()\n } catch {\n return\n }\n void resume(t)\n }, [claimId, reset, resume, target])\n\n const visible = useMemo(\n () => (messages.length === 0 && greetingMessage ? [greetingMessage] : messages),\n [greetingMessage, messages],\n )\n\n return {\n messages: visible,\n busy,\n sessionId,\n resets,\n handles,\n addressee,\n agentHandle,\n welcomeSuggestions,\n approval,\n withHuman,\n branding,\n start,\n send,\n attachments,\n uploading,\n attachmentError,\n attach,\n detach,\n loadAttachment,\n decide,\n stop,\n reset,\n switchTo,\n }\n}\n","/**\n * An agent, as the panel draws it: the picture it was given, or its initial on\n * its own colour.\n *\n * Always a rounded square, so a transcript, the `@` picker and the agent rail read the\n * same whether a picture loaded or not — and one that fails to load (a host's\n * strict CSP, a network blip) is drawn as if there had been none rather than as\n * a broken image. Decorative: the name is always written or announced beside it.\n */\nimport type { JSX } from 'preact'\nimport { useState } from 'preact/hooks'\n\nexport interface AvatarProps {\n name: string\n color?: string\n url?: string\n /** Its side, in pixels. */\n size?: number\n}\n\nexport function Avatar({ name, color, url, size = 16 }: AvatarProps): JSX.Element {\n // Keyed on the address: a different picture deserves a new attempt.\n const [failed, setFailed] = useState<string | undefined>(undefined)\n const showImage = Boolean(url) && failed !== url\n\n return (\n <span\n class=\"sqc-avatar\"\n aria-hidden=\"true\"\n style={{\n width: `${size}px`,\n height: `${size}px`,\n fontSize: `${Math.round(size * 0.45)}px`,\n // A quarter of the side: the same squircle at every size it is drawn.\n borderRadius: `${Math.round(size * 0.25)}px`,\n ...(showImage || !color ? {} : { backgroundColor: color }),\n }}\n >\n {showImage ? <img src={url} alt=\"\" onError={() => setFailed(url)} /> : initialOf(name)}\n </span>\n )\n}\n\n/** The first letter of a name, as a reader would see it — or \"?\" for none. */\nfunction initialOf(name: string): string {\n const first = Array.from(name.trim())[0]\n return first ? first.toLocaleUpperCase() : '?'\n}\n","/**\n * The column of agents a panel shows when its application offers several — the\n * way a chat app lists its workspaces.\n *\n * One round face per agent with a short name under it and its full name in a\n * tooltip, the one being talked to marked by a pill on the edge. Pressing another\n * switches to the conversation with that agent — its welcome message when\n * nothing was said yet.\n */\nimport type { JSX } from 'preact'\n\nimport type { AgentHandle } from '../types'\nimport { Avatar } from './Avatar'\n\nexport interface AgentRailProps {\n handles: AgentHandle[]\n /** The handle being talked to, when anything says who. */\n active?: string\n /** A turn is on its way: switching now would leave its answer nowhere. */\n disabled: boolean\n onPick: (handle: string) => void\n label: string\n}\n\nexport function AgentRail({ handles, active, disabled, onPick, label }: AgentRailProps): JSX.Element {\n return (\n <nav class=\"sqc-rail\" aria-label={label}>\n {handles.map((handle) => (\n <button\n key={handle.handle}\n type=\"button\"\n class=\"sqc-rail__item\"\n aria-label={handle.name}\n aria-pressed={handle.handle === active}\n data-tip={handle.name}\n disabled={disabled}\n onClick={() => onPick(handle.handle)}\n >\n <Avatar name={handle.name} color={handle.color} url={handle.avatarUrl} size={40} />\n <span class=\"sqc-rail__label\" aria-hidden=\"true\">\n {shortName(handle.handle)}\n </span>\n </button>\n ))}\n </nav>\n )\n}\n\n/** What fits under a face: the handle, as a word — `sales` reads \"Sales\". */\nfunction shortName(handle: string): string {\n const word = handle.split(/[-_]/)[0] ?? handle\n return word.charAt(0).toUpperCase() + word.slice(1)\n}\n","import type { JSX } from 'preact'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks'\nimport { MAX_MESSAGE_LENGTH } from '../lib/client'\nimport type { Locale } from '../lib/i18n'\nimport type { AgentHandle, ChatAttachment } from '../types'\nimport { Avatar } from './Avatar'\n\nconst MAX_ROWS_PX = 132\n\n/**\n * What the picker offers, mirroring what the API accepts.\n *\n * A hint and nothing else: the bytes decide, on the server, and a file renamed\n * past this list is refused there rather than here.\n */\nconst ACCEPTED_FILES =\n 'image/png,image/jpeg,image/gif,image/webp,application/pdf,.docx,.txt,.md,.csv,.json'\n\n/** A handle being typed: where its `@` sits, and what has been written after it. */\ninterface Mention {\n start: number\n query: string\n}\n\n/** What a handle may hold, mirroring the API's own alphabet. */\nconst HANDLE_CHARS = /^[a-zA-Z0-9_-]*$/\n\n/**\n * The handle under the caret, if the caret is in one.\n *\n * An `@` only starts a handle at the beginning of the field or after whitespace:\n * `contact@acme.example` is an address somebody is typing, and opening a picker over\n * it would be the widget interrupting a sentence it misread. Same rule as the\n * server's, which reads a handle only at the head of a message.\n */\nfunction mentionAt(value: string, caret: number): Mention | null {\n const upto = value.slice(0, caret)\n const start = upto.lastIndexOf('@')\n if (start < 0) return null\n if (start > 0 && !/\\s/.test(upto[start - 1] ?? '')) return null\n const query = upto.slice(start + 1)\n return HANDLE_CHARS.test(query) ? { start, query } : null\n}\n\nexport interface ComposerProps {\n placeholder: string\n locale: Locale\n busy: boolean\n /** Focuses the field when the sidebar opens. */\n autoFocus: boolean\n /**\n * The handles this application offers, as the open response returned them.\n *\n * Empty is the ordinary case — a deployment is unlisted until somebody ticks it —\n * and it ships no affordance at all: an empty popup is worse than no popup, and\n * the default agent answers plain text anyway.\n */\n handles?: AgentHandle[]\n /** The handle the conversation opened on, written into the field once so the\n * visitor can see who is being addressed — and delete it. */\n addressee?: string\n /** The files already accepted for this question. */\n attachments?: ChatAttachment[]\n /** The names of the ones still on their way up, so a slow upload is visible. */\n uploading?: string[]\n /** Why the last upload was refused, in the visitor's own language. */\n attachmentError?: string\n /** Absent where a conversation cannot take files — which is also what hides\n * the paperclip rather than showing one that refuses. */\n onAttach?: (file: File) => void\n onDetach?: (attachmentId: string) => void\n onSend: (text: string) => void\n onStop: () => void\n}\n\nexport function Composer({\n placeholder,\n locale,\n busy,\n autoFocus,\n handles,\n addressee,\n attachments = [],\n uploading = [],\n attachmentError,\n onAttach,\n onDetach,\n onSend,\n onStop,\n}: ComposerProps): JSX.Element {\n const [value, setValue] = useState('')\n const [mention, setMention] = useState<Mention | null>(null)\n const [active, setActive] = useState(0)\n const [hovering, setHovering] = useState(false)\n const input = useRef<HTMLTextAreaElement | null>(null)\n const picker = useRef<HTMLInputElement | null>(null)\n const canAttach = Boolean(onAttach)\n const waiting = uploading.length > 0\n\n // What the picker offers right now: the offered handles whose name starts with\n // what is being typed. Nothing matching closes it rather than showing an empty\n // list — at that point the text is a name the panel knows nothing about, and the\n // server will say so once it is sent.\n const matches = useMemo(() => {\n if (!mention || !handles || handles.length === 0) return []\n const query = mention.query.toLowerCase()\n return handles.filter((handle) => handle.handle.startsWith(query))\n }, [handles, mention])\n const picking = matches.length > 0\n\n const grow = useCallback(() => {\n const node = input.current\n if (!node) return\n node.style.height = 'auto'\n const overflowing = node.scrollHeight > MAX_ROWS_PX\n node.style.height = `${Math.min(node.scrollHeight, MAX_ROWS_PX)}px`\n // No scrollbar while the text fits in the max height: otherwise a single\n // line already reserves the scroll gutter.\n node.style.overflowY = overflowing ? 'auto' : 'hidden'\n }, [])\n\n useEffect(() => {\n if (autoFocus) input.current?.focus()\n // Sets the real height at mount: without it the textarea keeps its default\n // `rows=1` height until the first keystroke.\n grow()\n }, [autoFocus, grow])\n\n // A page that opened on a handle starts the visitor off addressing it — as text,\n // which is the only thing that routes, and which they can delete. Never over\n // something already typed: whatever is in the field is theirs.\n useEffect(() => {\n if (!addressee) return\n setValue((current) => (current ? current : `@${addressee} `))\n requestAnimationFrame(grow)\n }, [addressee, grow])\n\n /** Reads the handle under the caret after anything that may have moved it. */\n const scan = useCallback((node: HTMLTextAreaElement) => {\n setMention(mentionAt(node.value, node.selectionStart ?? node.value.length))\n setActive(0)\n }, [])\n\n /**\n * Writes a picked handle where the one being typed was.\n *\n * Text, and only text: the server parses the message, so a name chosen from the\n * list is indistinguishable from one somebody spelled out — which is what keeps\n * the picker a convenience rather than a second router.\n */\n const pick = useCallback(\n (handle: string) => {\n const node = input.current\n if (!node || !mention) return\n const caret = node.selectionStart ?? node.value.length\n const next = `${value.slice(0, mention.start)}@${handle} ${value.slice(caret)}`\n const at = mention.start + handle.length + 2\n setValue(next)\n setMention(null)\n requestAnimationFrame(() => {\n node.focus()\n node.setSelectionRange(at, at)\n grow()\n })\n },\n [grow, mention, value],\n )\n\n /** Hands every picked file up, one round trip each. */\n const take = useCallback(\n (files: FileList | null) => {\n if (!onAttach || !files) return\n for (const file of Array.from(files)) onAttach(file)\n },\n [onAttach],\n )\n\n const submit = useCallback(() => {\n const text = value.trim()\n // Not while a file is still going up: a message names the files it carries,\n // and one that has not landed has no id to name. A file already up is a turn\n // on its own — a question about the file — so only the turn carrying neither\n // words nor a file is held here.\n if ((!text && attachments.length === 0) || busy || waiting) return\n onSend(text)\n setValue('')\n setMention(null)\n // The textarea keeps the sent message's height without this manual reset:\n // `grow` only fires again on the next keystroke.\n requestAnimationFrame(grow)\n }, [attachments.length, busy, grow, onSend, value, waiting])\n\n const onKeyDown = useCallback(\n (event: JSX.TargetedKeyboardEvent<HTMLTextAreaElement>) => {\n // The picker takes the keys it needs while it is open, and only then: with no\n // list on screen every key means what it has always meant.\n if (picking && !event.isComposing) {\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n const step = event.key === 'ArrowDown' ? 1 : matches.length - 1\n setActive((current) => (current + step) % matches.length)\n return\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n event.preventDefault()\n pick((matches[active] ?? matches[0]).handle)\n return\n }\n if (event.key === 'Escape') {\n event.preventDefault()\n // Kept out of the host page: Escape closes the whole panel from a\n // `document` listener, and closing a popup must not close the panel too.\n event.stopPropagation()\n setMention(null)\n return\n }\n }\n // Enter sends, Shift+Enter inserts a line break. `isComposing` avoids\n // sending during an IME composition (CJK keyboards, long accents).\n if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {\n event.preventDefault()\n submit()\n }\n },\n [active, matches, pick, picking, submit],\n )\n\n const remaining = MAX_MESSAGE_LENGTH - value.length\n\n return (\n <form\n class={`sqc-composer${hovering ? ' sqc-composer--dropping' : ''}`}\n onSubmit={(event) => {\n event.preventDefault()\n submit()\n }}\n onDragOver={(event) => {\n if (!canAttach) return\n event.preventDefault()\n setHovering(true)\n }}\n onDragLeave={() => setHovering(false)}\n onDrop={(event) => {\n if (!canAttach) return\n event.preventDefault()\n setHovering(false)\n take(event.dataTransfer?.files ?? null)\n }}\n >\n {(attachments.length > 0 || waiting || attachmentError) && (\n <div class=\"sqc-attachments\">\n {attachments.map((file) => (\n <span key={file.id} class=\"sqc-chip\" data-kind={file.kind}>\n <span class=\"sqc-chip__name\">{file.filename}</span>\n <button\n type=\"button\"\n class=\"sqc-chip__remove\"\n aria-label={locale.t.composer.remove.replace('{name}', file.filename)}\n onClick={() => onDetach?.(file.id)}\n >\n ×\n </button>\n </span>\n ))}\n {uploading.map((name) => (\n <span key={name} class=\"sqc-chip sqc-chip--waiting\">\n <span class=\"sqc-chip__name\">{name}</span>\n </span>\n ))}\n {attachmentError && (\n <p class=\"sqc-attachments__error\" role=\"status\">\n {attachmentError}\n </p>\n )}\n </div>\n )}\n <div class=\"sqc-composer__field\">\n {picking && (\n <ul class=\"sqc-mentions\" role=\"listbox\" aria-label={locale.t.handles.picker}>\n {matches.map((handle, index) => (\n <li\n key={handle.handle}\n role=\"option\"\n aria-selected={index === active}\n class={`sqc-mention${index === active ? ' sqc-mention--active' : ''}`}\n // The list is clicked while the field has the focus: without this\n // the mousedown blurs the textarea and the caret is gone before\n // there is anywhere to write the handle.\n onMouseDown={(event) => event.preventDefault()}\n onMouseEnter={() => setActive(index)}\n onClick={() => pick(handle.handle)}\n >\n <span class=\"sqc-mention__icon\">\n <Avatar name={handle.name} color={handle.color} url={handle.avatarUrl} size={18} />\n </span>\n <span class=\"sqc-mention__handle\">@{handle.handle}</span>\n <span class=\"sqc-mention__name\">{handle.name}</span>\n </li>\n ))}\n </ul>\n )}\n <textarea\n ref={input}\n class=\"sqc-composer__input\"\n rows={1}\n value={value}\n placeholder={placeholder}\n maxLength={MAX_MESSAGE_LENGTH}\n aria-label={locale.t.composer.label}\n onInput={(event) => {\n setValue(event.currentTarget.value)\n scan(event.currentTarget)\n grow()\n }}\n onKeyDown={onKeyDown}\n // The caret can move without the text changing — a click, an arrow key —\n // and the picker follows the caret, not the keystrokes.\n onClick={(event) => scan(event.currentTarget)}\n // A screenshot pasted straight into the field. Only the files are\n // taken, so pasting text still pastes text.\n onPaste={(event) => {\n const files = event.clipboardData?.files\n if (!canAttach || !files || files.length === 0) return\n event.preventDefault()\n take(files)\n }}\n />\n {remaining <= 200 && (\n <span class=\"sqc-composer__count\" aria-live=\"polite\">\n {remaining}\n </span>\n )}\n </div>\n\n {canAttach && (\n <>\n <input\n ref={picker}\n type=\"file\"\n multiple\n accept={ACCEPTED_FILES}\n class=\"sqc-file-input\"\n onChange={(event) => {\n take(event.currentTarget.files)\n // Cleared so picking the same file twice in a row still fires a\n // change event — otherwise the second attempt does nothing.\n event.currentTarget.value = ''\n }}\n />\n <button\n type=\"button\"\n class=\"sqc-btn sqc-btn--attach\"\n onClick={() => picker.current?.click()}\n aria-label={locale.t.composer.attach}\n title={locale.t.composer.attachTitle}\n >\n {/* Paperclip. */}\n <svg\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"1.9\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M21 11.5l-8.8 8.8a5 5 0 01-7.1-7.1l9-9a3.3 3.3 0 014.7 4.7l-9 9a1.6 1.6 0 01-2.3-2.3l8.3-8.3\" />\n </svg>\n </button>\n </>\n )}\n\n {busy ? (\n <button\n type=\"button\"\n class=\"sqc-btn sqc-btn--stop\"\n onClick={onStop}\n aria-label={locale.t.composer.stop}\n title={locale.t.composer.stopTitle}\n >\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\">\n <rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"2\" fill=\"currentColor\" />\n </svg>\n </button>\n ) : (\n <button\n type=\"submit\"\n class=\"sqc-btn sqc-btn--send\"\n disabled={(!value.trim() && attachments.length === 0) || waiting}\n aria-label={locale.t.composer.send}\n title={locale.t.composer.sendTitle}\n >\n {/* Send glyph of the design system. */}\n <svg\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"1.9\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M5 12l14-7-5 14-2.5-5.5L5 12z\" />\n </svg>\n </button>\n )}\n </form>\n )\n}\n","/**\n * Minimal Markdown rendering of the agent's answers.\n *\n * The agent answers with a stable subset of Markdown: headings, lists\n * (sometimes nested), tables (record listings), identifiers in backticks, links.\n * That subset is covered and nothing more: no Markdown library (weight), and\n * above all **never** any injected HTML — everything is produced as Preact\n * nodes, hence escaped by construction.\n */\nimport { Fragment, type JSX } from 'preact'\nimport { useLayoutEffect, useRef } from 'preact/hooks'\nimport type { Locale } from '../lib/i18n'\nimport { loadWidgetExtras } from '../widgets/extras-loader'\nimport { inline } from '../widgets/inline'\nimport { parseAnswer } from '../widgets/parse/answer'\nimport type { FormSpec, WidgetBlock } from '../widgets/types'\n\nconst BULLET = /^(\\s*)[-*•]\\s+/\nconst ORDERED = /^(\\s*)\\d+[.)]\\s+/\nconst HEADING = /^\\s{0,3}(#{1,6})\\s+(.+?)#*\\s*$/\nconst RULE = /^\\s*([-*_])(?:\\s*\\1){2,}\\s*$/\nconst QUOTE = /^\\s*>\\s?(.*)$/\nconst FENCE = /^\\s*```/\n\ninterface ListItem {\n depth: number\n ordered: boolean\n text: string\n}\n\n/**\n * Rebuilds nested lists from flat items carrying their indentation depth.\n * Returns the list and the index of the first item left unconsumed.\n */\nfunction buildList(\n items: ListItem[],\n start: number,\n depth: number,\n key: string,\n): [JSX.Element, number] {\n const ordered = items[start].ordered\n const entries: { key: string; text: string | null; nested: JSX.Element[] }[] = []\n let index = start\n\n while (index < items.length && items[index].depth >= depth) {\n const item = items[index]\n // A marker of another kind at the same level opens a separate list rather\n // than mixing bullets and numbers.\n if (item.depth === depth && item.ordered !== ordered) break\n\n if (item.depth > depth) {\n const [nested, next] = buildList(items, index, item.depth, `${key}-${index}`)\n const last = entries[entries.length - 1]\n // A sub-list with no parent (first line already indented) is held in an\n // empty item rather than lost.\n if (last) last.nested.push(nested)\n else entries.push({ key: `${key}-${index}`, text: null, nested: [nested] })\n index = next\n continue\n }\n\n entries.push({ key: `${key}-${index}`, text: item.text, nested: [] })\n index += 1\n }\n\n const children = entries.map((entry) => (\n <li key={entry.key}>\n {entry.text === null ? null : inline(entry.text, entry.key)}\n {entry.nested}\n </li>\n ))\n\n const list = ordered ? (\n <ol key={key}>{children}</ol>\n ) : (\n <ul key={key}>{children}</ul>\n )\n return [list, index]\n}\n\nexport interface RichTextProps {\n text: string\n locale: Locale\n /** The widgets still await an answer; false freezes them (answered, older, in flight). */\n live?: boolean\n /** May close with Yes / No when the answer ends on a closed question. Absent: never. */\n confirmable?: boolean\n}\n\n/** Renders a run of plain Markdown lines (no table, no option group, no widget fence). */\nfunction markdown(text: string): JSX.Element[] {\n const lines = text.split('\\n')\n const blocks: JSX.Element[] = []\n\n let paragraph: string[] = []\n let items: ListItem[] = []\n let quote: string[] = []\n\n const flushParagraph = (): void => {\n if (!paragraph.length) return\n const key = `p${blocks.length}`\n blocks.push(<p key={key}>{inline(paragraph.join('\\n'), key)}</p>)\n paragraph = []\n }\n\n const flushList = (): void => {\n if (!items.length) return\n let index = 0\n while (index < items.length) {\n const key = `l${blocks.length}`\n const [list, next] = buildList(items, index, items[index].depth, key)\n blocks.push(list)\n index = next\n }\n items = []\n }\n\n const flushQuote = (): void => {\n if (!quote.length) return\n const key = `q${blocks.length}`\n blocks.push(<blockquote key={key}>{inline(quote.join('\\n'), key)}</blockquote>)\n quote = []\n }\n\n const flushAll = (): void => {\n flushParagraph()\n flushList()\n flushQuote()\n }\n\n for (let cursor = 0; cursor < lines.length; cursor += 1) {\n const line = lines[cursor]\n\n // Code block: everything is taken literally until the closing fence. An\n // unclosed block (answer cut mid-stream) is rendered as-is rather\n // than lost.\n if (FENCE.test(line)) {\n flushAll()\n const fence: string[] = []\n cursor += 1\n while (cursor < lines.length && !FENCE.test(lines[cursor])) {\n fence.push(lines[cursor])\n cursor += 1\n }\n const key = `c${blocks.length}`\n blocks.push(\n <pre key={key}>\n <code>{fence.join('\\n')}</code>\n </pre>,\n )\n continue\n }\n\n if (!line.trim()) {\n flushAll()\n continue\n }\n\n const heading = HEADING.exec(line)\n if (heading) {\n flushAll()\n // In a chat bubble a typographic h1 makes no sense: the six Markdown\n // levels are compressed onto h3–h5.\n const depth = heading[1].length\n const Tag = (depth <= 2 ? 'h3' : depth === 3 ? 'h4' : 'h5') as 'h3'\n const key = `h${blocks.length}`\n blocks.push(<Tag key={key}>{inline(heading[2], key)}</Tag>)\n continue\n }\n\n if (RULE.test(line)) {\n flushAll()\n blocks.push(<hr key={`r${blocks.length}`} />)\n continue\n }\n\n const quoted = QUOTE.exec(line)\n if (quoted) {\n flushParagraph()\n flushList()\n quote.push(quoted[1])\n continue\n }\n\n const bullet = BULLET.exec(line)\n const ordered = bullet ? null : ORDERED.exec(line)\n const marker = bullet ?? ordered\n\n if (marker) {\n flushParagraph()\n flushQuote()\n items.push({\n // The raw indentation serves as relative depth: only the comparison\n // between items matters, not the absolute value.\n depth: marker[1].replace(/\\t/g, ' ').length,\n ordered: Boolean(ordered),\n text: line.slice(marker[0].length),\n })\n continue\n }\n\n flushList()\n flushQuote()\n paragraph.push(line)\n }\n\n flushAll()\n\n return blocks\n}\n\n/**\n * `<sqc-form>` is defined late, once its code has loaded. Its properties are\n * set on the node rather than through JSX: on an element not yet upgraded,\n * Preact would write an object as an attribute, while an own property is\n * handed back to the element when it upgrades.\n */\nfunction FormBlock(props: { form: FormSpec; locked: boolean; language: Locale['code'] }): JSX.Element {\n const node = useRef<HTMLElement>(null)\n const { form, locked, language } = props\n\n useLayoutEffect(() => {\n void loadWidgetExtras()\n }, [])\n\n useLayoutEffect(() => {\n if (node.current) Object.assign(node.current, { form, locked, language })\n }, [form, locked, language])\n\n // The labels, as light DOM: what a page reads if the element never loads.\n // Its shadow root has no slot, so they are hidden once it does.\n return (\n <sqc-form ref={node}>\n {form.fields.map((field) => (\n <p key={field.name}>{field.label}</p>\n ))}\n </sqc-form>\n )\n}\n\nfunction renderBlock(block: WidgetBlock, locale: Locale, locked: boolean): JSX.Element {\n switch (block.kind) {\n case 'markdown':\n return <>{markdown(block.text)}</>\n\n case 'table':\n return (\n <sqc-table\n table={{ header: block.header, rows: block.rows }}\n locked={locked}\n language={locale.code}\n />\n )\n\n case 'choices':\n return (\n <sqc-choices\n options={block.options}\n multiple={block.multiple}\n checked={block.checked}\n locked={locked}\n language={locale.code}\n />\n )\n\n case 'form':\n return <FormBlock form={block.form} locked={locked} language={locale.code} />\n }\n}\n\nexport function RichText({ text, locale, live, confirmable }: RichTextProps): JSX.Element {\n const { blocks, confirm } = parseAnswer(text, locale.code, confirmable === true)\n const locked = !live\n return (\n <>\n {blocks.map((block, index) => (\n <Fragment key={`b${index}`}>{renderBlock(block, locale, locked)}</Fragment>\n ))}\n {confirm && <sqc-confirm locked={locked} language={locale.code} />}\n </>\n )\n}\n","import type { JSX } from 'preact'\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks'\nimport { readable } from '../widgets/approval/name'\nimport { loadWidgetExtras } from '../widgets/extras-loader'\nimport { isLive } from '../widgets/live'\nimport type { Locale } from '../lib/i18n'\nimport type { ChatAttachment, ChatMessage, PendingApproval } from '../types'\nimport { Avatar } from './Avatar'\nimport { RichText } from './RichText'\n\n/** Below this distance (px) from the bottom of the list, the user is taken to\n * be following the stream and the list keeps scrolling for them. Beyond it,\n * they have scrolled back through the history: their scroll is left alone. */\nconst STICK_THRESHOLD = 80\n\nfunction Time({ at, locale }: { at: number; locale: Locale }): JSX.Element {\n const date = new Date(at)\n return (\n <time class=\"sqc-msg__time\" dateTime={date.toISOString()}>\n {date.toLocaleTimeString(locale.tag, { hour: '2-digit', minute: '2-digit' })}\n </time>\n )\n}\n\n/**\n * `<sqc-approval>` with its properties set from here. It ships in the extras,\n * loaded here on first use — and asked for again whenever the call changes\n * state, so a failed load is retried; properties set on the node survive its\n * late upgrade. The decision leaves it as `sqc-decision`, heard by the list.\n *\n * Until it loads (or if it never does), its light DOM is a plain fallback: the\n * tool named as text and Yes / No buttons sending the same `sqc-decision`, so\n * the decision still goes through the list's gate. The element's shadow root\n * has no slot: the fallback is hidden once it has upgraded.\n */\nfunction ApprovalHost(props: { call?: PendingApproval; locked: boolean; locale: Locale }): JSX.Element {\n const { call, locked, locale } = props\n const language = locale.code\n const node = useRef<HTMLElement>(null)\n useLayoutEffect(() => {\n void loadWidgetExtras()\n }, [call, locked])\n useLayoutEffect(() => {\n if (node.current) Object.assign(node.current, { call, locked, language })\n }, [call, locked, language])\n const decide = (approved: boolean) => (event: Event) =>\n event.currentTarget?.dispatchEvent(\n new CustomEvent('sqc-decision', { detail: { approved }, bubbles: true, composed: true }),\n )\n const { yes, no } = locale.t.confirm\n return (\n <sqc-approval ref={node}>\n {call && <p>{readable(call.tool)}</p>}\n <button type=\"button\" disabled={locked} onClick={decide(true)}>\n {yes}\n </button>\n <button type=\"button\" disabled={locked} onClick={decide(false)}>\n {no}\n </button>\n </sqc-approval>\n )\n}\n\n/** Reads one file's bytes, as a URL this component owns and revokes. */\nexport type AttachmentLoader = (attachmentId: string) => Promise<Blob>\n\n/**\n * One attached picture, drawn once its bytes have arrived.\n *\n * Fetched rather than linked, because the route that serves it is opened by the\n * visitor token — which travels in a header, and a header is what an `<img src>`\n * cannot send. The object URL is revoked when the bubble goes: without that,\n * every picture of a long conversation stays in memory until the page does.\n *\n * A file that will not load draws as its name. The panel is a chat window, not\n * a file manager, and a broken image icon says less than the filename does.\n */\nfunction Picture({ file, load }: { file: ChatAttachment; load: AttachmentLoader }): JSX.Element {\n const [src, setSrc] = useState<string | null>(null)\n\n useEffect(() => {\n let url: string | null = null\n let alive = true\n void load(file.id)\n .then((blob) => {\n if (!alive) return\n url = URL.createObjectURL(blob)\n setSrc(url)\n })\n .catch(() => {\n // Drawn as its name below, which is what a file nobody can open is.\n })\n return () => {\n alive = false\n if (url) URL.revokeObjectURL(url)\n }\n }, [file.id, load])\n\n if (!src) return <span class=\"sqc-chip sqc-chip--waiting\">{file.filename}</span>\n return <img class=\"sqc-attachment__image\" src={src} alt={file.filename} />\n}\n\n/**\n * A chart an agent drew, handed to `<sqc-chart>` as the text of its file: the\n * element and its reader ship in the extras, loaded here on first use. Set as\n * properties on the node, which survive the element's late upgrade.\n */\nfunction Chart(props: {\n file: ChatAttachment\n load: AttachmentLoader\n language: Locale['code']\n}): JSX.Element {\n const { file, load, language } = props\n const node = useRef<HTMLElement>(null)\n // A file that will not load reads as no chart: the element names it.\n const body = useMemo(\n () =>\n load(file.id)\n .then((blob) => blob.text())\n .catch(() => ''),\n [file.id, load],\n )\n\n useLayoutEffect(() => {\n void loadWidgetExtras()\n }, [])\n\n useLayoutEffect(() => {\n if (node.current) Object.assign(node.current, { body, filename: file.filename, language })\n }, [body, file.filename, language])\n\n // The filename, as light DOM: what a page reads if the element never loads.\n return (\n <sqc-chart class=\"sqc-attachment__chart\" ref={node}>\n {file.filename}\n </sqc-chart>\n )\n}\n\n/** The files one turn was sent with, under what was written. */\nfunction Attachments({\n files,\n load,\n language,\n}: {\n files: ChatAttachment[]\n load?: AttachmentLoader\n language: Locale['code']\n}): JSX.Element | null {\n if (files.length === 0 || !load) return null\n return (\n <div class=\"sqc-attachments sqc-attachments--sent\">\n {files.map((file) =>\n file.kind === 'image' ? (\n <Picture key={file.id} file={file} load={load} />\n ) : file.kind === 'chart' ? (\n <Chart key={file.id} file={file} load={load} language={language} />\n ) : (\n <span key={file.id} class=\"sqc-chip\" data-kind=\"document\">\n <span class=\"sqc-chip__name\">{file.filename}</span>\n </span>\n ),\n )}\n </div>\n )\n}\n\nfunction Bubble({\n message,\n locale,\n assistantName,\n live,\n onDecide,\n onLoadAttachment,\n}: {\n message: ChatMessage\n locale: Locale\n /** Name the assistant signs its messages with. */\n assistantName: string\n /** The widgets of this message still await an answer. */\n live: boolean\n onDecide?: (approved: boolean, label: string) => void\n onLoadAttachment?: AttachmentLoader\n}): JSX.Element {\n const pending = message.streaming && !message.content\n // A paused call carries its own buttons: the \"Do you confirm?\" of the recap\n // must not bring up a second pair.\n const awaiting = Boolean(message.approval)\n\n return (\n <div class={`sqc-msg sqc-msg--${message.role}${message.error ? ' sqc-msg--error' : ''}`}>\n {/* The design system does not put the agent's answer in a bubble: it is\n signed by this line, then set in serif flat on the panel background. */}\n {message.role === 'assistant' && (\n <div class=\"sqc-msg__who\">\n {/* Whoever answered, where an application holds several agents: the\n face and the name are what tell them apart in a transcript, and\n a single-agent panel keeps signing with the name it was given. */}\n {message.agent ? (\n <Avatar\n name={message.agent.name}\n color={message.agent.color}\n url={message.agent.avatarUrl}\n />\n ) : (\n <ChatIcon />\n )}\n {message.authorName ?? message.agent?.name ?? assistantName}\n </div>\n )}\n <div class=\"sqc-msg__bubble\">\n {pending ? (\n <span class=\"sqc-waiting\">\n <span class=\"sqc-typing\" aria-label={locale.t.typing}>\n <i />\n <i />\n <i />\n </span>\n {/* What a tool round is busy with, since it writes nothing: said\n politely to assistive tech too, as it replaces a long silence. */}\n {message.activity && (\n <span class=\"sqc-activity\" role=\"status\">\n {locale.t.activity[message.activity]}\n </span>\n )}\n </span>\n ) : (\n <div class=\"sqc-msg__body\">\n {/* Only under the agent's answer: a visitor whose own question\n reads as one has nobody to say yes to. */}\n <RichText\n text={message.content}\n locale={locale}\n live={live}\n confirmable={\n message.role === 'assistant' && !awaiting && !message.streaming && !message.error\n }\n />\n {message.streaming && <span class=\"sqc-caret\" aria-hidden=\"true\" />}\n {/* The call describes itself only where the agent did not: several\n models ask for a tool with nothing said, and two buttons under an\n empty bubble are a decision nobody can take. */}\n {awaiting && (\n <ApprovalHost\n locale={locale}\n call={message.content.trim() === '' ? message.approval : undefined}\n locked={!onDecide}\n />\n )}\n {message.unknownHandle && !message.streaming && (\n <Unaddressed message={message} locale={locale} />\n )}\n <Attachments\n files={message.attachments ?? []}\n load={onLoadAttachment}\n language={locale.code}\n />\n </div>\n )}\n {!pending && <Time at={message.createdAt} locale={locale} />}\n </div>\n </div>\n )\n}\n\n/**\n * The note under an answer whose message addressed a name nobody answers to.\n *\n * Under the answer and not in place of it: the question *was* answered, by the\n * agent that answers plain text, so this adds who could have been asked instead. A\n * mistyped name deserves help rather than a refusal.\n *\n * With nothing offered it says only that nobody answers to that name — an\n * organization that ticked no handle has chosen not to publish its list, and\n * quoting it here would undo that.\n */\nfunction Unaddressed({\n message,\n locale,\n}: {\n message: ChatMessage\n locale: Locale\n}): JSX.Element {\n const offered = message.offered ?? []\n return (\n <p class=\"sqc-msg__unaddressed\">\n <span>{locale.t.handles.unknown}</span> <code>@{message.unknownHandle}</code>\n {offered.length > 0 && (\n <>\n {' '}\n <span>{locale.t.handles.instead}</span>{' '}\n {offered.map((handle) => (\n <code key={handle.handle}>@{handle.handle}</code>\n ))}\n </>\n )}\n </p>\n )\n}\n\n/** Lucide `message-circle`: the launcher, the panel title and every answer\n * coming from the assistant. */\nexport function ChatIcon(): JSX.Element {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719\" />\n </svg>\n )\n}\n\nexport interface MessageListProps {\n messages: ChatMessage[]\n locale: Locale\n /** Name displayed above each answer. */\n assistantName: string\n suggestions?: string[]\n /** Suggestions are only shown on the first turn, as long as the user has\n * written nothing. */\n showSuggestions: boolean\n /** A turn is in flight: the last message's options are disabled. */\n busy?: boolean\n /** A human of the organization handles the conversation: said under the\n * transcript, since no agent will answer what comes next. */\n withHuman?: boolean\n onSuggestion: (text: string) => void\n /** Sends the label of a ticked option as the turn's answer. */\n onChoice: (label: string) => void\n /** Decides the tool call the last message put on hold. */\n onDecide: (approved: boolean, label: string) => void\n /** A widget asked for the composer (`sqc-compose`): the visitor will write\n * their own answer. */\n onCompose?: () => void\n /** Reads the bytes of a file a turn carried. Absent where nothing can. */\n onLoadAttachment?: AttachmentLoader\n}\n\nexport function MessageList({\n messages,\n locale,\n assistantName,\n suggestions,\n showSuggestions,\n busy,\n withHuman,\n onSuggestion,\n onChoice,\n onDecide,\n onCompose,\n onLoadAttachment,\n}: MessageListProps): JSX.Element {\n const scroller = useRef<HTMLDivElement | null>(null)\n const stick = useRef(true)\n\n // Measured before paint: at that point the DOM already carries the new\n // content, so the distance to the bottom only reflects the pre-render position\n // if it is updated on scroll — hence the handler below.\n useLayoutEffect(() => {\n const node = scroller.current\n if (node && stick.current) node.scrollTop = node.scrollHeight\n }, [messages])\n\n // One listener for every widget: they answer with a `sqc-reply` event, which\n // is a message sent like any other. Stopped here, so the host page does not\n // see the widget's inner traffic.\n // `sqc-compose` (Yes / No's \"something else\") sends nothing: it asks for the\n // composer, which the host owns.\n const choose = useRef({ onChoice, onCompose })\n choose.current = { onChoice, onCompose }\n useEffect(() => {\n const node = scroller.current\n if (!node) return\n const onReply = (event: Event): void => {\n event.stopPropagation()\n const text = (event as CustomEvent<{ text?: unknown }>).detail?.text\n if (typeof text === 'string') choose.current.onChoice(text)\n }\n const onComposeEvent = (event: Event): void => {\n event.stopPropagation()\n choose.current.onCompose?.()\n }\n node.addEventListener('sqc-reply', onReply)\n node.addEventListener('sqc-compose', onComposeEvent)\n return () => {\n node.removeEventListener('sqc-reply', onReply)\n node.removeEventListener('sqc-compose', onComposeEvent)\n }\n }, [])\n\n // A decision leaves `<sqc-approval>` as `sqc-decision`. Only the last answer\n // can be decided, and not while a turn is in flight.\n const last = messages[messages.length - 1]\n const decidable = !busy && last?.role === 'assistant' && Boolean(last.approval)\n const decide = useRef({ onDecide, decidable, locale })\n decide.current = { onDecide, decidable, locale }\n useEffect(() => {\n const node = scroller.current\n if (!node) return\n const onDecision = (event: Event): void => {\n event.stopPropagation()\n const approved = (event as CustomEvent<{ approved?: unknown }>).detail?.approved\n const current = decide.current\n if (typeof approved !== 'boolean' || !current.decidable) return\n const { yes, no } = current.locale.t.confirm\n current.onDecide(approved, approved ? yes : no)\n }\n node.addEventListener('sqc-decision', onDecision)\n return () => node.removeEventListener('sqc-decision', onDecision)\n }, [])\n\n useEffect(() => {\n const node = scroller.current\n if (!node) return\n const onScroll = (): void => {\n stick.current = node.scrollHeight - node.scrollTop - node.clientHeight < STICK_THRESHOLD\n }\n node.addEventListener('scroll', onScroll, { passive: true })\n return () => node.removeEventListener('scroll', onScroll)\n }, [])\n\n return (\n <div class=\"sqc-messages\" ref={scroller} role=\"log\" aria-live=\"polite\" aria-atomic=\"false\">\n {messages.map((message, index) => (\n <Bubble\n key={message.id}\n message={message}\n locale={locale}\n assistantName={assistantName}\n // Only the last answer's widgets are live: those of earlier turns\n // have already been answered, and a turn in flight answers nothing.\n live={!busy && isLive(index, messages)}\n onDecide={\n !busy && message.role === 'assistant' && index === messages.length - 1\n ? onDecide\n : undefined\n }\n onLoadAttachment={onLoadAttachment}\n />\n ))}\n\n {withHuman && (\n <p class=\"sqc-with-human\" role=\"status\">\n {locale.t.withHuman}\n </p>\n )}\n\n {showSuggestions && suggestions && suggestions.length > 0 && (\n <div class=\"sqc-suggestions\">\n {suggestions.map((suggestion) => (\n <button\n key={suggestion}\n type=\"button\"\n class=\"sqc-suggestion\"\n onClick={() => onSuggestion(suggestion)}\n >\n {suggestion}\n </button>\n ))}\n </div>\n )}\n </div>\n )\n}\n","import type { JSX } from 'preact'\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks'\nimport { contextLabel, isNamedObject } from '../lib/context'\nimport { resolveLocale, type Locale } from '../lib/i18n'\nimport { initialOpen, writeOpenState } from '../lib/openState'\nimport { useChat } from '../lib/useChat'\nimport type { ChatbotContext, ChatbotEvent, ChatbotOptions } from '../types'\nimport { AgentRail } from './AgentRail'\nimport { Composer } from './Composer'\nimport { defineChatWidgets } from '../widgets/define'\nimport { ChatIcon, MessageList } from './MessageList'\n\n// Sidebar width of the design system. No accent here: left unset, the\n// stylesheet picks it — black, or white in the dark theme — and a page's own\n// `--sqc-accent` on the element is not overwritten by a default.\nconst DEFAULTS = {\n width: 'min(392px, 100vw)',\n} as const\n\n/** Imperative surface exposed to the wrapper (custom element / React). */\nexport interface ChatbotControls {\n open(): void\n close(): void\n toggle(): void\n reset(): void\n send(text: string): void\n isOpen(): boolean\n sessionId(): string\n}\n\nexport interface ChatbotWidgetProps extends ChatbotOptions {\n onEvent?: (event: ChatbotEvent) => void\n /** Receives the imperative API on mount, `null` on unmount. */\n bind?: (controls: ChatbotControls | null) => void\n}\n\n/** Keys the widget owns: they name the conversation, not the host's page, so\n * they never become a chip. */\nconst HIDDEN_CONTEXT_KEYS = new Set<string>(['sessionId'])\n\n/** Turns a context key into a chip title: `orderId` and `order` both read\n * \"Order\", `deliveryDate` reads \"Delivery date\". The host names its own\n * entities — the widget knows no domain and only makes the key readable. */\nfunction chipLabel(key: string): string {\n const words = key\n .replace(/Id$|Ref$/, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .trim()\n .toLowerCase()\n if (!words) return key\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\n/**\n * Chips to display: one per context entry carrying a usable value.\n *\n * The value shown is the name when the host provided one\n * (`order: { id, name }`), the id otherwise — a UUID means nothing to the user,\n * but it is all there is when only the id was passed. Anything that is neither a\n * non-empty string nor a `{ id, … }` object is skipped: a chip claims something\n * is selected.\n */\nfunction contextChips(context: ChatbotContext | undefined): { label: string; value: string }[] {\n if (!context) return []\n const chips: { label: string; value: string }[] = []\n for (const [key, entry] of Object.entries(context)) {\n if (HIDDEN_CONTEXT_KEYS.has(key)) continue\n if (typeof entry !== 'string' && !isNamedObject(entry)) continue\n const value = contextLabel(entry)\n if (value) chips.push({ label: chipLabel(key), value })\n }\n return chips\n}\n\n/** An empty label replaces nothing: `heading=\"\"`, or a settings field cleared\n * by the host, hands it back to the translation instead of showing a blank\n * header. */\nfunction override(value: string | undefined, fallback: string): string {\n return value?.trim() ? value : fallback\n}\n\n/** Resolves `theme: 'auto'` to light/dark and follows the system changes. */\nfunction useResolvedTheme(theme: ChatbotOptions['theme']): 'light' | 'dark' {\n const [systemDark, setSystemDark] = useState(false)\n\n useEffect(() => {\n if (theme !== 'auto' || typeof matchMedia !== 'function') return\n const query = matchMedia('(prefers-color-scheme: dark)')\n setSystemDark(query.matches)\n const onChange = (event: MediaQueryListEvent): void => setSystemDark(event.matches)\n query.addEventListener('change', onChange)\n return () => query.removeEventListener('change', onChange)\n }, [theme])\n\n if (theme === 'dark') return 'dark'\n if (theme === 'light') return 'light'\n return systemDark ? 'dark' : 'light'\n}\n\nexport function ChatbotWidget(props: ChatbotWidgetProps): JSX.Element {\n // Before the first render: the answers draw their tables and options with them.\n defineChatWidgets()\n const persistOpen = props.persistOpen ?? true\n const [open, setOpen] = useState(() => initialOpen(props.defaultOpen, persistOpen))\n const [unread, setUnread] = useState(false)\n const panel = useRef<HTMLDivElement | null>(null)\n const launcher = useRef<HTMLButtonElement | null>(null)\n\n const theme = useResolvedTheme(props.theme ?? 'light')\n // All the widget's copy comes from here: the language is the one the host\n // declares, and the labels it provides itself (`heading`, `greeting`…) win\n // over the translation.\n const locale: Locale = useMemo(() => resolveLocale(props.locale), [props.locale])\n const t = locale.t\n const heading = override(props.heading, t.heading)\n const assistantName = override(props.assistantName, t.assistant)\n const greeting = override(props.greeting, t.greeting)\n\n const onEvent = props.onEvent\n const chat = useChat({\n embedKey: props.embedKey,\n user: props.user,\n scope: props.scope,\n getSubjectToken: props.getSubjectToken,\n agent: props.agent,\n context: props.context,\n greeting,\n locale,\n onEvent,\n })\n\n const {\n send: sendChat,\n reset: resetChat,\n decide,\n stop,\n start,\n resets,\n busy,\n messages,\n withHuman,\n branding,\n sessionId,\n handles,\n addressee,\n agentHandle,\n welcomeSuggestions,\n attachments,\n uploading,\n attachmentError,\n attach,\n detach,\n loadAttachment,\n switchTo,\n } = chat\n\n // A message received while the sidebar is closed lights the badge on the\n // floating button: it is the only notification channel when the panel is\n // hidden (the case of a `sendMessage()` triggered by the host page).\n useEffect(() => {\n if (!open && messages.some((message) => message.role === 'assistant' && message.id !== 'greeting')) {\n setUnread(true)\n }\n }, [messages, open])\n\n // Synchronous mirror of `open`: `openPanel`/`closePanel` have to know whether\n // they really change the state, so the event is emitted once, without slipping\n // a side effect into the `setOpen` updater.\n const isOpen = useRef(open)\n isOpen.current = open\n\n const openPanel = useCallback(() => {\n setUnread(false)\n if (isOpen.current) return\n isOpen.current = true\n setOpen(true)\n if (persistOpen) writeOpenState(true)\n onEvent?.({ type: 'chatbot-open', sessionId })\n }, [onEvent, persistOpen, sessionId])\n\n const closePanel = useCallback(() => {\n if (!isOpen.current) return\n isOpen.current = false\n setOpen(false)\n if (persistOpen) writeOpenState(false)\n onEvent?.({ type: 'chatbot-close', sessionId })\n // Hand the focus back to the floating button: without it the focus falls\n // back to the host page's `<body>` and keyboard navigation starts over.\n launcher.current?.focus()\n }, [onEvent, persistOpen, sessionId])\n\n // Showing the panel reads what it draws — the welcome message, the picker, the\n // branding — and opens nothing: a panel shown is not a conversation had, and\n // the conversation is opened on the first message. Idempotent, so re-opening\n // the panel reads nothing twice. Read again after a reset while the panel stays\n // open: starting over, or a new scope, leaves an empty panel that must say what\n // the first one said.\n useEffect(() => {\n if (open) start()\n }, [open, resets, start])\n\n // The agent rail: shown once there is somebody to switch to. Each agent of it\n // is a conversation of its own, and a click shows that one.\n const showRail = handles.length >= 2\n\n const send = sendChat\n\n const reset = useCallback(() => {\n setUnread(false)\n resetChat()\n }, [resetChat])\n\n // The object exposed to the host has to be stable (a React `ref` must not\n // change identity on every render): it delegates to the fresh closures stored\n // in `handlers`.\n const handlers = useRef({ openPanel, closePanel, send, reset, sessionId })\n handlers.current = { openPanel, closePanel, send, reset, sessionId }\n\n const controls = useRef<ChatbotControls>({\n open: () => handlers.current.openPanel(),\n close: () => handlers.current.closePanel(),\n // `isOpen` (the synchronous mirror) rather than the render value: the host\n // has to be able to read `chatbot.open` right after `openChat()`, before the\n // next render.\n toggle: () => (isOpen.current ? handlers.current.closePanel() : handlers.current.openPanel()),\n reset: () => handlers.current.reset(),\n send: (text: string) => {\n handlers.current.openPanel()\n handlers.current.send(text)\n },\n isOpen: () => isOpen.current,\n sessionId: () => handlers.current.sessionId,\n })\n\n const bind = props.bind\n // `useLayoutEffect` rather than `useEffect`: plain Preact effects are deferred\n // until after paint, whereas the wrapper has to be able to call\n // `sendMessage()` as soon as `connectedCallback()` returns.\n useLayoutEffect(() => {\n bind?.(controls.current)\n return () => bind?.(null)\n }, [bind])\n\n // Escape closes the panel. The listener sits on `document`: shadow DOM\n // keyboard events bubble up to it, and it also covers the case where the focus\n // stayed in the host page.\n useEffect(() => {\n if (!open) return\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') {\n event.stopPropagation()\n closePanel()\n }\n }\n document.addEventListener('keydown', onKeyDown)\n return () => document.removeEventListener('keydown', onKeyDown)\n }, [closePanel, open])\n\n // Somebody already said something to this agent. The suggestions have no place\n // under it: they open a conversation, they do not continue one. The welcome\n // message is not something said — it is what they sit under.\n const hasConversation = useMemo(() => messages.some((message) => message.role === 'user'), [messages])\n // The agent's own, else what the page offers whoever answers.\n const suggestions = welcomeSuggestions.length > 0 ? welcomeSuggestions : props.suggestions\n\n const chips = useMemo(() => contextChips(props.context), [props.context])\n const rootStyle = {\n ...(props.accent ? { '--sqc-accent': props.accent } : {}),\n '--sqc-width': props.width ?? DEFAULTS.width,\n } as JSX.CSSProperties\n\n return (\n <div\n class=\"sqc\"\n data-theme={theme}\n data-position={props.position ?? 'bottom-right'}\n data-layout={props.layout ?? 'sidebar'}\n data-open={open ? 'true' : 'false'}\n style={rootStyle}\n >\n <button\n ref={launcher}\n type=\"button\"\n class=\"sqc-launcher\"\n aria-label={heading}\n aria-expanded={open}\n aria-haspopup=\"dialog\"\n onClick={openPanel}\n >\n <span class=\"sqc-launcher__icon\">\n {/* The icon can be replaced by an element of the host page:\n `<squadico-chatbot><svg slot=\"launcher-icon\" /></…>`, or the\n `launcherIcon` prop of the React wrapper. A slot, not an option:\n the widget renders inside a shadow root, where a host component\n cannot be mounted — projected through a slot it stays in its own\n tree, with its own CSS, and inherits the button colour here through\n `currentColor`. The content below is the slot fallback, hence the\n default icon. */}\n <slot name=\"launcher-icon\" class=\"sqc-slot-icon\">\n <ChatIcon />\n </slot>\n </span>\n {unread && <span class=\"sqc-launcher__badge\" aria-hidden=\"true\" />}\n </button>\n\n <aside\n ref={panel}\n class=\"sqc-panel\"\n role=\"dialog\"\n aria-modal=\"false\"\n aria-label={heading}\n // `inert` removes the whole subtree from focus and accessibility when\n // the panel is slid off screen — otherwise tabbing would land in an\n // invisible panel.\n {...(open ? {} : { inert: true })}\n >\n <header class=\"sqc-header\">\n <span class=\"sqc-header__icon\" aria-hidden=\"true\">\n <ChatIcon />\n </span>\n <div class=\"sqc-header__titles\">\n <p class=\"sqc-header__heading\">{heading}</p>\n <p class=\"sqc-header__sub\">{override(props.subheading, t.subheading)}</p>\n </div>\n <button\n type=\"button\"\n class=\"sqc-icon-btn\"\n onClick={reset}\n aria-label={t.newConversation}\n data-tip={t.newConversation}\n >\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\">\n <path d=\"M20 12a8 8 0 1 1-2.6-5.9M20 4v4h-4\" stroke-linecap=\"round\" />\n </svg>\n </button>\n <button\n type=\"button\"\n class=\"sqc-icon-btn\"\n onClick={closePanel}\n aria-label={t.close}\n data-tip={t.closeTitle}\n >\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\">\n <path d=\"M6 6l12 12M18 6L6 18\" stroke-linecap=\"round\" />\n </svg>\n </button>\n </header>\n\n {/* The header spans the panel; under it, the rail sits beside the\n conversation. Always wrapped, so the rail showing up once the handles\n arrive does not remount the transcript and the composer. */}\n <div class=\"sqc-panel__body\">\n {showRail && (\n <AgentRail\n handles={handles}\n active={agentHandle || undefined}\n disabled={busy}\n onPick={switchTo}\n label={t.handles.rail}\n />\n )}\n <div class=\"sqc-panel__main\">\n\n {(props.showContext ?? true) && chips.length > 0 && (\n <div class=\"sqc-context\" aria-label={t.context.region}>\n {chips.map((chip) => (\n <span key={chip.label} class=\"sqc-chip\" title={`${chip.label}: ${chip.value}`}>\n <b>{chip.label}</b>\n {chip.value}\n </span>\n ))}\n </div>\n )}\n\n <MessageList\n messages={messages}\n locale={locale}\n assistantName={assistantName}\n suggestions={suggestions}\n showSuggestions={!hasConversation}\n busy={busy}\n withHuman={withHuman}\n onSuggestion={send}\n onChoice={send}\n onDecide={decide}\n onCompose={() =>\n panel.current?.querySelector<HTMLTextAreaElement>('.sqc-composer__input')?.focus()\n }\n onLoadAttachment={loadAttachment}\n />\n\n <Composer\n placeholder={override(props.placeholder, t.placeholder)}\n locale={locale}\n busy={busy}\n autoFocus={open}\n handles={handles}\n addressee={addressee}\n attachments={attachments}\n uploading={uploading}\n // Translated here rather than in the hook: the hook knows why an upload\n // was refused, and this is where the panel's language lives.\n attachmentError={attachmentError ? t.attachments[attachmentError] : undefined}\n onAttach={attach}\n onDetach={detach}\n onSend={send}\n onStop={stop}\n />\n\n <p class=\"sqc-hint\">{t.hint}</p>\n {branding && (\n <p class=\"sqc-powered\">\n <a href=\"https://squadico.com\" target=\"_blank\" rel=\"noopener noreferrer\">\n {t.poweredBy}\n </a>\n </p>\n )}\n </div>\n </div>\n </aside>\n </div>\n )\n}\n","/*\n * Stylesheet of the widget — injected into the shadow root (constructable\n * stylesheet where supported, `<style>` otherwise). It never leaks into the host\n * page, and the host page cannot override it: the only entry points for an\n * integrator are the `--sqc-*` variables, set on the custom element.\n *\n * `:host` uses `position: fixed; inset: 0; pointer-events: none`: a single\n * element depends on fixed positioning (hence a single breaking point should an\n * ancestor carry a `transform`), and the page stays entirely clickable through\n * the overlay.\n *\n * ── Design system ────────────────────────────────────────────\n * The Squadico design system (v2): near-monochrome. Action is black (hover\n * slate-800), everything around it is slate — white surfaces, slate-200 rules,\n * slate-900 text, slate-500 for what is secondary — and links are blue-600. One\n * sans-serif family, Plus Jakarta Sans. Radii follow its hierarchy: 16px for\n * what holds content (the bubbles), 12px for what is pressed or typed into,\n * 8px for utility icon buttons, full for badges and the launcher. The values\n * are hard-copied here under internal `--sqc-*` names: the widget is a\n * standalone npm package and cannot depend on the host application's CSS\n * variables (they do not exist inside the shadow root of the other\n * integrations).\n *\n * The accent is black by default and the page's to change (`accent`, or\n * `--sqc-accent` on the element). Left unset, the stylesheet decides, which is\n * what lets the dark theme — a derivation on the slate scale, kept because\n * `theme: 'dark' | 'auto'` is part of the public contract — turn it white. The\n * text drawn on it is worked out from its lightness where the browser can.\n *\n * The typeface is referenced, never downloaded: the widget issues no font\n * request. If the host loads it, `font-family` resolution crosses the shadow\n * root and the widget benefits; otherwise the system fallbacks apply.\n */\n\n:host {\n /* ── Public extension points ────────────────────────────── */\n /* `--sqc-accent` is one too, deliberately left unset here: see `.sqc`. */\n --sqc-width: min(392px, 100vw);\n /* Height of the floating window (`layout=\"floating\"`), never taller than\n the space it opens in; the sidebar always takes the full height. */\n --sqc-height: 640px;\n --sqc-z: 2147483000;\n --sqc-radius: 16px;\n --sqc-font-family:\n 'Plus Jakarta Sans', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica,\n Arial, sans-serif;\n --sqc-font-heading: var(--sqc-font-family);\n\n position: fixed;\n inset: 0;\n /* Fixed over the whole viewport, so a margin the page's layout gives its\n children — a `space-y-*` column — would shorten the sidebar by as much and\n leave a strip under it. A page's rules beat `:host` except against\n `!important`, which is why this one carries it. */\n margin: 0 !important;\n z-index: var(--sqc-z);\n display: block;\n pointer-events: none;\n font-family: var(--sqc-font-family);\n font-size: 14px;\n line-height: 1.5;\n /* Isolates the type from the host page: without it a `font-size: 62.5%` on\n `html` would render the whole widget at 8.75px. */\n -webkit-font-smoothing: antialiased;\n text-align: left;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n.sqc {\n /* Raw design system scale (light): Tailwind's slate. */\n --sqc-neutral-50: #f8fafc;\n --sqc-neutral-100: #f1f5f9;\n --sqc-neutral-200: #e2e8f0;\n --sqc-neutral-300: #cbd5e1;\n --sqc-neutral-400: #94a3b8;\n --sqc-neutral-500: #64748b;\n --sqc-neutral-600: #475569;\n --sqc-neutral-900: #0f172a;\n --sqc-error-50: #fff1f2;\n --sqc-error-100: #ffe4e6;\n --sqc-error-600: #e11d48;\n\n /* Accent: the page's when it set one, black otherwise. */\n --sqc-accent-default: #000000;\n --sqc-accent-color: var(--sqc-accent, var(--sqc-accent-default));\n /* Text on the accent. White on the default black; the `@supports` below works\n it out for any other accent. */\n --sqc-on-accent: #ffffff;\n /* Hover of a filled button: the DS's black → slate-800, as a mix so that it\n holds for an accent the page chose. */\n --sqc-accent-hover: color-mix(in oklab, var(--sqc-accent-color) 84%, var(--sqc-on-accent));\n /* Accent used as a text colour (icons beside a title): the page's accent when\n it set one, the text colour otherwise. */\n --sqc-accent-fg: var(--sqc-accent, var(--sqc-text));\n\n /* Roles. */\n --sqc-bg: #ffffff; /* bg-white */\n --sqc-surface: var(--sqc-neutral-50); /* hover:bg-slate-50 */\n --sqc-selected: var(--sqc-neutral-100); /* active item: bg-slate-100 */\n --sqc-border: var(--sqc-neutral-200);\n --sqc-border-strong: var(--sqc-neutral-300); /* inputs, hovered outlines */\n --sqc-text: var(--sqc-neutral-900);\n --sqc-text-muted: var(--sqc-neutral-500);\n --sqc-link: #2563eb; /* blue-600 */\n --sqc-bubble-user: var(--sqc-accent-color);\n --sqc-bubble-user-text: var(--sqc-on-accent);\n --sqc-code-bg: var(--sqc-neutral-100);\n --sqc-disabled: var(--sqc-neutral-300); /* bg-slate-300 text-white */\n --sqc-shadow:\n 0 10px 15px -3px rgb(15 23 42 / 10%), 0 4px 6px -4px rgb(15 23 42 / 10%); /* shadow-lg */\n /* Bottom-only shadow (no halo around): the history menu, which spans the\n whole sidebar width rather than floating as a card. */\n --sqc-shadow-bottom: 0 6px 8px -6px rgb(15 23 42 / 18%);\n /* Neutral focus, never coloured: a ring for what is pressed, the DS's\n `focus:border-slate-900 focus:ring-slate-900/10` for what is typed into. */\n --sqc-focus: 0 0 0 2px var(--sqc-bg), 0 0 0 4px rgb(15 23 42 / 30%);\n --sqc-focus-input: 0 0 0 3px rgb(15 23 42 / 10%);\n --sqc-danger: var(--sqc-error-600);\n\n position: absolute;\n inset: 0;\n color: var(--sqc-text);\n}\n\n.sqc[data-theme='dark'] {\n --sqc-neutral-50: #172033;\n --sqc-neutral-100: #1e293b;\n --sqc-neutral-200: #334155;\n --sqc-neutral-300: #475569;\n --sqc-neutral-400: #64748b;\n --sqc-neutral-500: #94a3b8;\n --sqc-neutral-600: #cbd5e1;\n --sqc-neutral-900: #f8fafc;\n --sqc-error-50: #2a0a12;\n --sqc-error-100: #4c0519;\n --sqc-error-600: #fb7185;\n\n --sqc-accent-default: #ffffff;\n --sqc-on-accent: #0f172a;\n\n --sqc-bg: #0f172a; /* slate-900, the app's dark card */\n --sqc-link: #60a5fa;\n --sqc-code-bg: #020617;\n --sqc-shadow: 0 10px 24px -4px rgb(0 0 0 / 55%);\n --sqc-shadow-bottom: 0 6px 8px -6px rgb(0 0 0 / 55%);\n --sqc-focus: 0 0 0 2px var(--sqc-bg), 0 0 0 4px rgb(248 250 252 / 35%);\n --sqc-focus-input: 0 0 0 3px rgb(248 250 252 / 12%);\n}\n\n/* Text on an accent the page chose: white on a dark one, slate-900 on a light\n one, decided by its lightness. Where relative colours are not supported, the\n theme's default above stands. */\n@supports (color: oklch(from red l c h)) {\n .sqc {\n --sqc-on-accent: oklch(from var(--sqc-accent-color) clamp(0.208, (0.62 - l) * 1000, 1) 0 0);\n }\n}\n\n.sqc *,\n.sqc *::before,\n.sqc *::after {\n box-sizing: border-box;\n}\n\n/* ── Bouton flottant ──────────────────────────────────────── */\n\n.sqc-launcher {\n position: absolute;\n bottom: 24px;\n right: 24px;\n width: 56px;\n height: 56px;\n padding: 0;\n border: none;\n border-radius: 50%;\n background: var(--sqc-accent-color);\n color: var(--sqc-on-accent);\n cursor: pointer;\n pointer-events: auto;\n display: grid;\n place-items: center;\n box-shadow: var(--sqc-shadow);\n transition:\n transform 0.18s ease,\n opacity 0.18s ease,\n background 0.18s ease,\n box-shadow 0.18s ease;\n}\n\n.sqc[data-position='bottom-left'] .sqc-launcher {\n right: auto;\n left: 24px;\n}\n\n.sqc-launcher:hover {\n transform: scale(1.06);\n background: var(--sqc-accent-hover);\n}\n\n.sqc-launcher:focus-visible {\n outline: none;\n box-shadow: var(--sqc-focus);\n}\n\n/* Panel open: the button fades out, closing happens through the header. */\n.sqc[data-open='true'] .sqc-launcher {\n opacity: 0;\n transform: scale(0.5);\n pointer-events: none;\n}\n\n.sqc-launcher__icon svg {\n width: 26px;\n height: 26px;\n display: block;\n}\n\n/* Icon provided by the host (`slot=\"launcher-icon\"`): same frame as the default\n one. `::slotted()` can only target the projected node itself, never its\n descendants — a host wrapping its icon therefore has to size it on its own\n side, hence the centring here rather than a plain `display: block`. */\n.sqc-slot-icon::slotted(*) {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 26px;\n height: 26px;\n}\n\n.sqc-launcher__badge {\n position: absolute;\n top: 6px;\n right: 6px;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: var(--sqc-error-600);\n border: 2px solid var(--sqc-bg);\n}\n\n/* ── Sidebar ──────────────────────────────────────────────── */\n\n.sqc-panel {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n width: var(--sqc-width);\n display: flex;\n flex-direction: column;\n background: var(--sqc-bg);\n border-left: 1px solid var(--sqc-border);\n box-shadow: var(--sqc-shadow);\n pointer-events: auto;\n transform: translateX(100%);\n /* `visibility` is delayed so it only hides at the end of the slide, and\n applied immediately on opening. */\n visibility: hidden;\n transition:\n transform 0.26s cubic-bezier(0.22, 1, 0.36, 1),\n visibility 0s linear 0.26s;\n}\n\n/* Under the header, which spans the panel: the rail and the conversation side by\n side. A wrapper even without the rail, so the rail appearing does not remount\n what is beside it. */\n.sqc-panel__body {\n display: flex;\n flex: 1;\n min-height: 0;\n}\n\n.sqc-panel__main {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-width: 0;\n min-height: 0;\n}\n\n/* ── Agent rail ───────────────────────────────────────────── */\n\n/* With several agents, a column of their faces down the left of the\n conversation — the way a chat app lists its workspaces. Tinted with the\n accent so it reads as a choice to make, not as a margin. */\n.sqc-rail {\n display: flex;\n flex-direction: column;\n flex-shrink: 0;\n align-items: stretch;\n gap: 6px;\n width: 72px;\n padding: 12px 0;\n /* Not scrollable: a scroll container clips on both axes, and would cut off\n the names shown beside the faces. An application lists a handful of\n agents, not a column's worth. */\n overflow: visible;\n border-right: 1px solid var(--sqc-border);\n background: color-mix(in oklab, var(--sqc-accent-color) 7%, var(--sqc-bg));\n}\n\n.sqc-rail__item {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 4px;\n padding: 4px 0;\n border: 0;\n background: none;\n color: var(--sqc-text-muted);\n font: inherit;\n cursor: pointer;\n}\n\n.sqc-rail__label {\n max-width: 64px;\n overflow: hidden;\n font-size: 10.5px;\n font-weight: 500;\n line-height: 1.2;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n.sqc-rail__item:hover,\n.sqc-rail__item[aria-pressed='true'] {\n color: var(--sqc-text);\n}\n\n.sqc-rail__item[aria-pressed='true'] .sqc-rail__label {\n font-weight: 600;\n}\n\n.sqc-rail__item .sqc-avatar {\n transition: box-shadow 0.15s ease;\n}\n\n.sqc-rail__item[aria-pressed='true'] .sqc-avatar {\n box-shadow: 0 0 0 2px var(--sqc-bg), 0 0 0 4px var(--sqc-accent-color);\n}\n\n/* The pill on the edge that says who is being talked to. */\n.sqc-rail__item::before {\n content: '';\n position: absolute;\n top: 24px;\n left: 0;\n width: 4px;\n height: 0;\n border-radius: 0 4px 4px 0;\n background: var(--sqc-text);\n transform: translateY(-50%);\n transition: height 0.15s ease;\n}\n\n.sqc-rail__item:hover::before {\n height: 12px;\n}\n\n.sqc-rail__item[aria-pressed='true']::before {\n height: 32px;\n}\n\n.sqc-rail__item:focus-visible {\n outline: 2px solid var(--sqc-accent-color);\n outline-offset: -2px;\n border-radius: 8px;\n}\n\n.sqc-rail__item:disabled {\n cursor: not-allowed;\n opacity: 0.5;\n}\n\n/* The agent's name, beside its face. */\n.sqc-rail__item[data-tip]::after {\n content: attr(data-tip);\n position: absolute;\n left: calc(100% + 6px);\n top: 24px;\n z-index: 2;\n padding: 4px 8px;\n border-radius: 6px;\n background: var(--sqc-text);\n color: var(--sqc-bg);\n font-size: 12px;\n font-weight: 500;\n white-space: nowrap;\n pointer-events: none;\n opacity: 0;\n transform: translateY(-50%);\n transition: opacity 0.12s ease;\n}\n\n.sqc-rail__item[data-tip]:hover::after,\n.sqc-rail__item[data-tip]:focus-visible::after {\n opacity: 1;\n}\n\n.sqc[data-open='true'] .sqc-panel {\n transform: translateX(0);\n visibility: visible;\n transition:\n transform 0.26s cubic-bezier(0.22, 1, 0.36, 1),\n visibility 0s;\n}\n\n/* ── Floating window ──────────────────────────────────────── */\n\n/* `layout=\"floating\"`: the same panel, lifted off the edge into a rounded\n window that grows out of the launcher's corner. */\n.sqc[data-layout='floating'] .sqc-panel {\n top: auto;\n bottom: 24px;\n right: 24px;\n /* Percentages of the host, which covers the viewport: on a page they are\n the viewport's, in a transformed frame (a preview) the frame's. */\n max-width: calc(100% - 48px);\n height: var(--sqc-height);\n max-height: calc(100% - 48px);\n border: 1px solid var(--sqc-border);\n border-radius: var(--sqc-radius);\n overflow: hidden;\n opacity: 0;\n transform: translateY(16px) scale(0.96);\n transform-origin: bottom right;\n transition:\n transform 0.22s cubic-bezier(0.22, 1, 0.36, 1),\n opacity 0.22s ease,\n visibility 0s linear 0.22s;\n}\n\n.sqc[data-layout='floating'][data-position='bottom-left'] .sqc-panel {\n right: auto;\n left: 24px;\n transform-origin: bottom left;\n}\n\n.sqc[data-layout='floating'][data-open='true'] .sqc-panel {\n opacity: 1;\n transform: none;\n transition:\n transform 0.22s cubic-bezier(0.22, 1, 0.36, 1),\n opacity 0.22s ease,\n visibility 0s;\n}\n\n/* ── Header ───────────────────────────────────────────────── */\n\n/* DS card header: white, bottom rule, bold slate-900 title — no coloured band. */\n.sqc-header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 13px 12px 13px 16px;\n background: var(--sqc-bg);\n color: var(--sqc-text);\n border-bottom: 1px solid var(--sqc-border);\n flex-shrink: 0;\n}\n\n.sqc-header__icon {\n display: grid;\n place-items: center;\n flex-shrink: 0;\n color: var(--sqc-accent-fg);\n}\n\n.sqc-header__icon svg {\n width: 17px;\n height: 17px;\n display: block;\n}\n\n.sqc-header__titles {\n flex: 1;\n min-width: 0;\n}\n\n.sqc-header__heading,\n.sqc-header__sub {\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.sqc-header__heading {\n font-family: var(--sqc-font-heading);\n font-size: 15px;\n font-weight: 700;\n letter-spacing: -0.2px;\n}\n\n.sqc-header__sub {\n font-size: 12px;\n color: var(--sqc-text-muted);\n}\n\n.sqc-icon-btn {\n width: 26px;\n height: 26px;\n border: none;\n border-radius: 8px;\n background: none;\n color: var(--sqc-text-muted);\n cursor: pointer;\n display: grid;\n place-items: center;\n flex-shrink: 0;\n transition: background 0.15s ease;\n}\n\n.sqc-icon-btn:hover {\n background: var(--sqc-surface);\n color: var(--sqc-text);\n}\n\n.sqc-icon-btn:focus-visible {\n outline: none;\n box-shadow: var(--sqc-focus);\n}\n\n.sqc-icon-btn svg {\n width: 16px;\n height: 16px;\n}\n\n/* Tooltip of the header icons, in place of the native `title`: that one takes a\n second to appear, is drawn with the system font and theme — outside the shadow\n root, hence out of the panel's reach — and never shows on keyboard focus. The\n label is still carried by `aria-label`: the `::after` is decorative, and an\n assistive technology does not read the same text twice. */\n.sqc-icon-btn[data-tip] {\n position: relative;\n}\n\n.sqc-icon-btn[data-tip]::after {\n content: attr(data-tip);\n position: absolute;\n top: calc(100% + 6px);\n /* Anchored to the right of the button: the three icons sit against the right\n edge of the panel, and a centred bubble would overflow it. */\n right: 0;\n z-index: 6;\n padding: 4px 8px;\n border-radius: 8px;\n /* Inverts the panel colours: dark on light, light on dark, with no extra\n variable to expose. */\n background: var(--sqc-text);\n color: var(--sqc-bg);\n font-family: var(--sqc-font-family);\n font-size: 11px;\n font-weight: 500;\n line-height: 1.3;\n white-space: nowrap;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.12s ease 0.15s;\n}\n\n.sqc-icon-btn[data-tip]:hover::after,\n.sqc-icon-btn[data-tip]:focus-visible::after {\n opacity: 1;\n}\n\n/* ── Conversation history ─────────────────────────────────── */\n\n/* Full sidebar width, not a floating card: only a bottom shadow\n (`--sqc-shadow-bottom`) separates it from what sits below, with no border\n and no shadow all around. */\n.sqc-history-pop {\n position: absolute;\n left: 0;\n right: 0;\n top: 54px;\n z-index: 5;\n}\n\n.sqc-history {\n display: flex;\n flex-direction: column;\n max-height: 320px;\n overflow-y: auto;\n background: var(--sqc-bg);\n box-shadow: var(--sqc-shadow-bottom);\n}\n\n.sqc-history__empty {\n margin: 0;\n padding: 14px 16px;\n font-size: 12px;\n color: var(--sqc-text-muted);\n text-align: center;\n}\n\n.sqc-history__item {\n display: flex;\n flex-direction: column;\n gap: 2px;\n width: 100%;\n padding: 10px 16px;\n border: none;\n border-bottom: 1px solid var(--sqc-border);\n background: none;\n color: var(--sqc-text);\n text-align: left;\n cursor: pointer;\n transition: background 0.15s ease;\n}\n\n.sqc-history__item:last-child {\n border-bottom: none;\n}\n\n.sqc-history__item:hover {\n background: var(--sqc-surface);\n}\n\n.sqc-history__item:focus-visible {\n outline: none;\n box-shadow: var(--sqc-focus);\n}\n\n.sqc-history__item[aria-current='true'] {\n background: var(--sqc-selected);\n}\n\n.sqc-history__item[aria-current='true'] .sqc-history__title {\n color: var(--sqc-text);\n font-weight: 600;\n}\n\n.sqc-history__title {\n font-size: 13px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.sqc-history__date {\n font-size: 11px;\n color: var(--sqc-text-muted);\n}\n\n/* ── Bandeau de contexte ──────────────────────────────────── */\n\n/* A single reminder line, as a neutral slate-100 box. */\n.sqc-context {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n margin: 12px 16px 4px;\n padding: 8px 11px;\n background: var(--sqc-selected);\n border: 1px solid var(--sqc-border);\n border-radius: 12px;\n font-size: 12px;\n color: var(--sqc-text);\n flex-shrink: 0;\n}\n\n.sqc-chip {\n display: inline-flex;\n align-items: baseline;\n gap: 4px;\n max-width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.sqc-chip b {\n font-weight: 600;\n}\n\n/* Separator between two context chips, with no dedicated DOM node. */\n.sqc-chip:not(:last-child)::after {\n content: '·';\n margin-left: 4px;\n opacity: 0.5;\n}\n\n/* ── Fil de conversation ──────────────────────────────────── */\n\n.sqc-messages {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n overscroll-behavior: contain;\n padding: 12px 16px;\n display: flex;\n flex-direction: column;\n gap: 13px;\n background: var(--sqc-bg);\n scrollbar-width: thin;\n scrollbar-color: var(--sqc-neutral-300) transparent;\n}\n\n.sqc-messages::-webkit-scrollbar {\n width: 6px;\n}\n\n.sqc-messages::-webkit-scrollbar-thumb {\n background: var(--sqc-neutral-300);\n border-radius: 99px;\n}\n\n.sqc-msg {\n display: flex;\n flex-direction: column;\n max-width: 93%;\n font-size: 13.5px;\n}\n\n/* The agent's answer is not a bubble: it is signed by an \"Assistant\" line and\n set flat on the panel background, in the body typeface. */\n.sqc-msg--assistant {\n align-self: stretch;\n}\n\n.sqc-msg--user {\n align-self: flex-end;\n}\n\n.sqc-msg__who {\n display: flex;\n align-items: center;\n gap: 6px;\n margin-bottom: 4px;\n font-size: 11px;\n font-weight: 500;\n color: var(--sqc-text-muted);\n}\n\n.sqc-msg__who svg {\n width: 12px;\n height: 12px;\n flex-shrink: 0;\n color: var(--sqc-accent-fg);\n}\n\n/* An agent's face: its picture, or its initial on its colour (the accent when it\n has none), as a rounded square. The size and the radius are set inline — the\n transcript, the picker and the rail draw it at three sizes. */\n.sqc-avatar {\n display: inline-flex;\n flex-shrink: 0;\n align-items: center;\n justify-content: center;\n overflow: hidden;\n background: var(--sqc-accent-color);\n color: var(--sqc-on-accent);\n font-weight: 600;\n line-height: 1;\n user-select: none;\n}\n\n.sqc-avatar img {\n width: 100%;\n height: 100%;\n object-fit: cover;\n}\n\n/* The note under an answer whose message addressed a name nobody answers to. Set\n quietly: the answer above it is what was asked for, and this only says who else\n could have been asked. */\n.sqc-msg__unaddressed {\n margin: 8px 0 0;\n font-size: 11.5px;\n line-height: 1.5;\n color: var(--sqc-text-muted);\n}\n\n.sqc-msg__unaddressed code {\n margin-right: 4px;\n padding: 1px 4px;\n border-radius: 4px;\n background: var(--sqc-code-bg);\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 11px;\n color: var(--sqc-text);\n}\n\n.sqc-msg--user .sqc-msg__bubble {\n padding: 9px 13px;\n background: var(--sqc-bubble-user);\n color: var(--sqc-bubble-user-text);\n border-radius: var(--sqc-radius) var(--sqc-radius) 4px var(--sqc-radius);\n}\n\n.sqc-msg--error .sqc-msg__bubble {\n padding: 11px;\n background: var(--sqc-error-50);\n color: var(--sqc-error-600);\n border: 1px solid var(--sqc-error-100);\n border-radius: 12px;\n}\n\n.sqc-msg__body {\n overflow-wrap: anywhere;\n}\n\n.sqc-msg--assistant .sqc-msg__body {\n font-size: 14px;\n line-height: 1.6;\n}\n\n.sqc-msg__body > *:first-child {\n margin-top: 0;\n}\n\n.sqc-msg__body > *:last-child {\n margin-bottom: 0;\n}\n\n.sqc-msg__body p {\n margin: 0 0 8px;\n white-space: pre-wrap;\n}\n\n.sqc-msg__body ul,\n.sqc-msg__body ol {\n margin: 0 0 8px;\n padding-left: 20px;\n}\n\n.sqc-msg__body li {\n margin-bottom: 3px;\n}\n\n.sqc-msg__body code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 0.85em;\n padding: 1px 4px;\n border-radius: 4px;\n background: var(--sqc-code-bg);\n}\n\n.sqc-msg--user .sqc-msg__body code {\n background: rgb(255 255 255 / 22%);\n}\n\n.sqc-msg__body pre {\n margin: 0 0 8px;\n padding: 9px 11px;\n border-radius: 8px;\n background: var(--sqc-code-bg);\n overflow-x: auto;\n}\n\n.sqc-msg__body pre code {\n padding: 0;\n background: none;\n}\n\n.sqc-msg__body a {\n color: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n/* DS text link: blue-600, underlined on hover. Only in answers: on the accent of\n a bubble, blue would not read. */\n.sqc-msg--assistant .sqc-msg__body a {\n color: var(--sqc-link);\n text-decoration: none;\n}\n\n.sqc-msg--assistant .sqc-msg__body a:hover {\n text-decoration: underline;\n}\n\n/* Headings: ranked by weight and slightly by size — in a 13.5-14px thread, a\n typographic h1 would be grotesque. */\n.sqc-msg__body h3,\n.sqc-msg__body h4,\n.sqc-msg__body h5,\n.sqc-msg__body h6 {\n margin: 12px 0 6px;\n font-family: var(--sqc-font-heading);\n font-weight: 700;\n line-height: 1.3;\n letter-spacing: -0.2px;\n}\n\n.sqc-msg__body h3 {\n font-size: 1.05em;\n}\n\n.sqc-msg__body h4 {\n font-size: 1em;\n}\n\n.sqc-msg__body h5,\n.sqc-msg__body h6 {\n font-size: 0.94em;\n}\n\n.sqc-msg__body ul ul,\n.sqc-msg__body ul ol,\n.sqc-msg__body ol ul,\n.sqc-msg__body ol ol {\n margin: 3px 0 0;\n}\n\n.sqc-msg__body blockquote {\n margin: 0 0 8px;\n padding: 2px 0 2px 10px;\n border-left: 2px solid var(--sqc-border-strong);\n color: var(--sqc-text-muted);\n white-space: pre-wrap;\n}\n\n.sqc-msg--user .sqc-msg__body blockquote {\n border-left-color: rgb(255 255 255 / 45%);\n color: inherit;\n opacity: 0.85;\n}\n\n.sqc-msg__body hr {\n margin: 10px 0;\n border: 0;\n border-top: 1px solid var(--sqc-border);\n}\n\n.sqc-msg--user .sqc-msg__body hr {\n border-top-color: rgb(255 255 255 / 30%);\n}\n\n.sqc-msg__body del {\n opacity: 0.7;\n}\n\n/* A choice the agent is waiting on: its questions, then the single validation\n answering them all (`Selection.tsx`). */\n.sqc-selection {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: 2px 0;\n}\n\n.sqc-selection__question {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.sqc-selection__ask {\n margin: 0;\n font-family: var(--sqc-font-family);\n font-size: 13px;\n font-weight: 600;\n color: var(--sqc-text);\n}\n\n.sqc-selection__actions {\n display: flex;\n}\n\n.sqc-selection__validate {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex: 1 1 auto;\n height: 32px;\n padding: 0 12px;\n font-family: var(--sqc-font-family);\n font-size: 13px;\n font-weight: 600;\n color: var(--sqc-on-accent);\n background: var(--sqc-accent-color);\n border: 1px solid transparent;\n border-radius: 12px;\n cursor: pointer;\n transition:\n filter 0.12s ease,\n background 0.12s ease;\n}\n\n.sqc-selection__validate:hover:not(:disabled) {\n background: var(--sqc-accent-hover);\n}\n\n.sqc-selection__validate:focus-visible {\n outline: none;\n box-shadow: var(--sqc-focus);\n}\n\n/* Nothing ticked, or answer already sent: the DS's disabled action. */\n.sqc-selection__validate:disabled {\n cursor: not-allowed;\n color: #ffffff;\n background: var(--sqc-disabled);\n}\n\n.sqc-selection__hint {\n margin: 0;\n font-family: var(--sqc-font-family);\n font-size: 11.5px;\n color: var(--sqc-text-muted);\n}\n\n.sqc-msg__time {\n display: block;\n margin-top: 3px;\n font-size: 10px;\n color: var(--sqc-text-muted);\n font-variant-numeric: tabular-nums;\n}\n\n.sqc-msg--user .sqc-msg__time {\n color: rgb(255 255 255 / 70%);\n text-align: right;\n}\n\n/* Curseur de frappe pendant le streaming. */\n.sqc-caret {\n display: inline-block;\n width: 2px;\n height: 1em;\n margin-left: 2px;\n vertical-align: text-bottom;\n background: currentColor;\n animation: sqc-blink 1s step-end infinite;\n}\n\n@keyframes sqc-blink {\n 0%,\n 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0;\n }\n}\n\n/* Trois points avant le premier token — DS `.typing`. */\n.sqc-typing {\n display: inline-flex;\n gap: 3px;\n padding: 2px 0;\n}\n\n.sqc-typing i {\n width: 5px;\n height: 5px;\n border-radius: 50%;\n background: var(--sqc-neutral-400);\n animation: sqc-pulse 1.2s infinite;\n}\n\n.sqc-typing i:nth-child(2) {\n animation-delay: 0.2s;\n}\n\n.sqc-typing i:nth-child(3) {\n animation-delay: 0.4s;\n}\n\n/* The dots, and beside them what the agent is busy with until its first word. */\n.sqc-waiting {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n}\n\n.sqc-activity {\n font-size: 12px;\n color: var(--sqc-text-muted);\n}\n\n@keyframes sqc-pulse {\n 0%,\n 60%,\n 100% {\n opacity: 0.25;\n }\n 30% {\n opacity: 1;\n }\n}\n\n/* ── Suggestions ──────────────────────────────────────────── */\n\n/* A full-width stack rather than floating pills: in a 392px panel every other\n pill used to be cut. */\n.sqc-suggestions {\n display: flex;\n flex-direction: column;\n gap: 7px;\n}\n\n.sqc-suggestion {\n display: flex;\n align-items: center;\n gap: 8px;\n width: 100%;\n padding: 8px 11px;\n border: 1px solid var(--sqc-border);\n border-radius: 12px;\n background: var(--sqc-bg);\n color: var(--sqc-text);\n font-family: var(--sqc-font-family);\n font-size: 12.5px;\n cursor: pointer;\n text-align: left;\n transition:\n background 0.15s ease,\n border-color 0.15s ease;\n}\n\n.sqc-suggestion::before {\n content: '';\n flex: 0 0 auto;\n width: 5px;\n height: 5px;\n border-radius: 50%;\n background: var(--sqc-accent-fg);\n}\n\n.sqc-suggestion:hover {\n background: var(--sqc-surface);\n border-color: var(--sqc-border-strong);\n}\n\n.sqc-suggestion:focus-visible {\n outline: none;\n box-shadow: var(--sqc-focus);\n}\n\n/* ── Zone de saisie ───────────────────────────────────────── */\n\n.sqc-composer {\n display: flex;\n align-items: flex-end;\n /* Wraps so the chips of attached files sit on a row of their own above the\n field, rather than squeezing it. */\n flex-wrap: wrap;\n gap: 8px;\n padding: 12px 14px;\n border-top: 1px solid var(--sqc-border);\n background: var(--sqc-bg);\n flex-shrink: 0;\n}\n\n/* A file being dragged over the composer, which is a drop target like the\n paperclip is a button. */\n.sqc-composer--dropping {\n outline: 2px dashed var(--sqc-accent-color);\n outline-offset: -4px;\n}\n\n/* The files a question is being written with, and the ones it was sent with:\n the same chips in the composer and under a bubble. */\n.sqc-attachments {\n flex-basis: 100%;\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n}\n\n.sqc-attachments--sent {\n margin-top: 8px;\n}\n\n.sqc-chip {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n max-width: 100%;\n padding: 3px 4px 3px 10px;\n border: 1px solid var(--sqc-border);\n border-radius: 999px;\n background: var(--sqc-selected);\n color: var(--sqc-text);\n font-size: 12px;\n}\n\n.sqc-chip--waiting {\n opacity: 0.6;\n padding-right: 10px;\n}\n\n.sqc-chip__name {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n max-width: 180px;\n}\n\n.sqc-chip__remove {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 18px;\n height: 18px;\n padding: 0;\n border: 0;\n border-radius: 999px;\n background: transparent;\n color: var(--sqc-text-muted);\n font-size: 14px;\n line-height: 1;\n cursor: pointer;\n}\n\n.sqc-chip__remove:hover {\n background: var(--sqc-selected);\n color: var(--sqc-text);\n}\n\n.sqc-attachments__error {\n flex-basis: 100%;\n margin: 0;\n color: var(--sqc-error-600);\n font-size: 12px;\n}\n\n/* An attached picture, drawn under the message it was sent with. Bounded so a\n photograph does not push the conversation off the panel. */\n.sqc-attachment__image {\n display: block;\n max-width: 100%;\n max-height: 180px;\n border-radius: 12px;\n}\n\n/* A chart an agent drew takes the width of the answer. */\n.sqc-attachment__chart {\n flex-basis: 100%;\n min-width: 0;\n}\n\n/* The real input is never shown: the paperclip is the control. */\n.sqc-file-input {\n display: none;\n}\n\n.sqc-btn--attach {\n background: transparent;\n color: var(--sqc-text-muted);\n}\n\n.sqc-btn--attach:hover {\n background: var(--sqc-selected);\n color: var(--sqc-text);\n}\n\n.sqc-composer__field {\n position: relative;\n flex: 1;\n min-width: 0;\n}\n\n.sqc-composer__input {\n display: block;\n width: 100%;\n min-height: 38px;\n max-height: 132px;\n padding: 9px 12px;\n border: 1px solid var(--sqc-border-strong);\n border-radius: 12px;\n background: var(--sqc-bg);\n color: var(--sqc-text);\n font-family: var(--sqc-font-family);\n font-size: 13.5px;\n line-height: 1.4;\n resize: none;\n /* No scrollbar by default (a single line): `Composer.tsx` switches to `auto`\n once `scrollHeight` goes past `max-height`. */\n overflow-y: hidden;\n outline: none;\n transition:\n border-color 0.15s ease,\n box-shadow 0.15s ease;\n}\n\n.sqc-composer__input::placeholder {\n color: var(--sqc-neutral-400);\n}\n\n.sqc-composer__input:focus {\n border-color: var(--sqc-text);\n box-shadow: var(--sqc-focus-input);\n}\n\n/* The handle picker `@` opens over the field. Anchored to the field rather than\n the panel: it has to sit on top of the message list, and the composer is the\n only positioned ancestor that follows the textarea as it grows. */\n.sqc-mentions {\n position: absolute;\n left: 0;\n right: 0;\n bottom: calc(100% + 6px);\n z-index: 2;\n max-height: 184px;\n overflow-y: auto;\n margin: 0;\n padding: 4px;\n list-style: none;\n border: 1px solid var(--sqc-border);\n border-radius: 12px;\n background: var(--sqc-bg);\n box-shadow: var(--sqc-shadow);\n scrollbar-width: thin;\n}\n\n.sqc-mention {\n display: flex;\n align-items: baseline;\n gap: 6px;\n padding: 6px 8px;\n border-radius: 8px;\n cursor: pointer;\n font-size: 12.5px;\n color: var(--sqc-text);\n}\n\n.sqc-mention--active {\n background: var(--sqc-neutral-100);\n}\n\n.sqc-mention__icon {\n flex-shrink: 0;\n}\n\n.sqc-mention__handle {\n font-weight: 600;\n}\n\n.sqc-mention__name {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--sqc-text-muted);\n}\n\n.sqc-composer__count {\n position: absolute;\n right: 8px;\n bottom: 4px;\n font-size: 10px;\n color: var(--sqc-text-muted);\n pointer-events: none;\n font-variant-numeric: tabular-nums;\n}\n\n.sqc-btn {\n width: 38px;\n height: 38px;\n border: none;\n border-radius: 12px;\n cursor: pointer;\n display: grid;\n place-items: center;\n flex-shrink: 0;\n transition:\n background 0.15s ease,\n opacity 0.15s ease;\n}\n\n.sqc-btn svg {\n width: 17px;\n height: 17px;\n}\n\n.sqc-btn--send {\n background: var(--sqc-accent-color);\n color: var(--sqc-on-accent);\n}\n\n.sqc-btn--send:hover:not(:disabled) {\n background: var(--sqc-accent-hover);\n}\n\n/* The DS's disabled action: slate-300, white glyph. */\n.sqc-btn--send:disabled {\n background: var(--sqc-disabled);\n color: #ffffff;\n cursor: not-allowed;\n}\n\n.sqc-btn--stop {\n background: var(--sqc-bg);\n color: var(--sqc-text);\n border: 1px solid var(--sqc-border);\n}\n\n.sqc-btn--stop:hover {\n border-color: var(--sqc-border-strong);\n background: var(--sqc-surface);\n}\n\n.sqc-btn:focus-visible {\n outline: none;\n box-shadow: var(--sqc-focus);\n}\n\n/* Permanent reminder that nothing is written without confirmation —\n which is exactly the agent contract (`pending_action`, then \"yes\"). */\n.sqc-hint {\n flex-shrink: 0;\n margin: 0;\n /* Safety margin for the iOS / Android home bar. */\n padding: 0 16px max(9px, env(safe-area-inset-bottom));\n font-size: 10.5px;\n line-height: 1.35;\n color: var(--sqc-text-muted);\n text-align: center;\n}\n\n/* Shown when the organization's plan carries our name. */\n.sqc-powered {\n flex-shrink: 0;\n margin: 0;\n padding: 0 16px max(9px, env(safe-area-inset-bottom));\n font-size: 10.5px;\n line-height: 1.35;\n text-align: center;\n}\n\n.sqc-powered a {\n color: var(--sqc-text-muted);\n text-decoration: none;\n}\n\n.sqc-powered a:hover {\n text-decoration: underline;\n}\n\n/* ── Adaptations ──────────────────────────────────────────── */\n\n@media (max-width: 520px) {\n .sqc {\n --sqc-width: 100vw;\n }\n\n .sqc-panel {\n border-left: none;\n }\n\n .sqc-launcher {\n bottom: 16px;\n right: 16px;\n }\n\n .sqc[data-position='bottom-left'] .sqc-launcher {\n left: 16px;\n }\n\n /* No room for a window on a phone: the floating panel fills the screen. */\n .sqc[data-layout='floating'] .sqc-panel,\n .sqc[data-layout='floating'][data-position='bottom-left'] .sqc-panel {\n inset: 0;\n max-width: none;\n height: auto;\n max-height: none;\n border: none;\n border-radius: 0;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .sqc-launcher,\n .sqc-panel,\n .sqc-btn,\n .sqc-suggestion,\n .sqc-choice,\n .sqc-confirm__btn,\n .sqc-icon-btn {\n transition: none;\n }\n\n .sqc-icon-btn[data-tip]::after,\n .sqc-rail__item::before,\n .sqc-rail__item[data-tip]::after,\n .sqc-rail__item .sqc-avatar {\n transition: none;\n }\n\n .sqc-typing i,\n .sqc-caret {\n animation: none;\n }\n}\n\n/* Once an agent handed the conversation to a human: nothing more is streamed,\n and this is what says a reply is still coming. */\n.sqc-with-human {\n margin: 8px 0 0;\n padding: 8px 12px;\n border: 1px solid var(--sqc-border);\n border-radius: 12px;\n background: var(--sqc-selected);\n color: var(--sqc-neutral-600);\n font-size: 13px;\n}\n","/**\n * Custom element wrapper: `<squadico-chatbot>`.\n *\n * The class is built **lazily** by `defineChatbot()` rather than at module\n * level: `class X extends HTMLElement` would throw a `ReferenceError` on a plain\n * server-side import (Next.js or Nuxt SSR, Node tests).\n */\nimport { render } from 'preact'\nimport { ChatbotWidget, type ChatbotControls } from './components/ChatbotWidget'\nimport styles from './styles.css?inline'\nimport type {\n ChatbotContext,\n ChatbotEvent,\n ChatbotOptions,\n HostUser,\n SubjectTokenSource,\n} from './types'\n\nexport const TAG_NAME = 'squadico-chatbot'\n\nconst ATTRIBUTES = [\n 'embed-key',\n 'context',\n 'user',\n 'agent',\n 'heading',\n 'subheading',\n 'assistant-name',\n 'placeholder',\n 'greeting',\n 'suggestions',\n 'width',\n 'accent',\n 'theme',\n 'position',\n 'layout',\n 'open',\n 'persist-open',\n 'show-context',\n 'locale',\n] as const\n\n/** A single `CSSStyleSheet` shared by every instance. */\nlet sheet: CSSStyleSheet | null | undefined\n\nfunction sharedSheet(): CSSStyleSheet | null {\n if (sheet !== undefined) return sheet\n try {\n const created = new CSSStyleSheet()\n created.replaceSync(styles)\n sheet = created\n } catch {\n // Safari < 16.4: no constructable stylesheets, fall back to <style>.\n sheet = null\n }\n return sheet\n}\n\nfunction warn(message: string, detail?: unknown): void {\n if (typeof console !== 'undefined') console.warn(`[${TAG_NAME}] ${message}`, detail ?? '')\n}\n\n/**\n * The host user, as an attribute.\n *\n * Accepts the JSON object a page can write in markup (`user='{\"id\":\"42\"}'`) and\n * refuses anything without an id: a claim with nothing to claim is not one, and\n * sending it would open an anonymous conversation while the page believed it had\n * named somebody.\n */\nfunction parseUser(raw: string | null): HostUser | undefined {\n if (!raw || !raw.trim()) return undefined\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n const source = parsed as { id?: unknown; name?: unknown; digest?: unknown }\n if (typeof source.id === 'string' && source.id) {\n return {\n id: source.id,\n name: typeof source.name === 'string' && source.name ? source.name : undefined,\n // Carried through rather than validated: what a digest has to *be* is\n // the API's rule, and a page that mistyped one meets a refusal about\n // its claim instead of a console warning about its markup.\n digest:\n typeof source.digest === 'string' && source.digest ? source.digest : undefined,\n }\n }\n }\n warn('the \"user\" attribute needs an object with an id', raw)\n } catch (error) {\n warn('the \"user\" attribute is not valid JSON', error)\n }\n return undefined\n}\n\nfunction parseContext(raw: string | null): ChatbotContext | undefined {\n if (!raw || !raw.trim()) return undefined\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as ChatbotContext\n }\n warn('the `context` attribute must be a JSON object', raw)\n } catch (error) {\n warn('the `context` attribute is not valid JSON', error)\n }\n return undefined\n}\n\n/** Accepts `[\"a\",\"b\"]` or `a|b` — the second form avoids escaping quotes in a\n * Vue or Angular template. */\nfunction parseSuggestions(raw: string | null): string[] | undefined {\n if (!raw || !raw.trim()) return undefined\n if (raw.trim().startsWith('[')) {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (Array.isArray(parsed)) return parsed.map(String)\n } catch (error) {\n warn('the `suggestions` attribute is not valid JSON', error)\n return undefined\n }\n }\n return raw\n .split('|')\n .map((item) => item.trim())\n .filter(Boolean)\n}\n\n/** A boolean attribute is true by mere presence; `=\"false\"` negates it. */\nfunction parseBool(raw: string | null): boolean | undefined {\n if (raw === null) return undefined\n return raw !== 'false' && raw !== '0'\n}\n\nfunction parseTheme(raw: string | null): ChatbotOptions['theme'] {\n return raw === 'dark' || raw === 'light' || raw === 'auto' ? raw : undefined\n}\n\nfunction parsePosition(raw: string | null): ChatbotOptions['position'] {\n return raw === 'bottom-left' || raw === 'bottom-right' ? raw : undefined\n}\n\nfunction parseLayout(raw: string | null): ChatbotOptions['layout'] {\n return raw === 'floating' || raw === 'sidebar' ? raw : undefined\n}\n\n/**\n * Properties a host may write before the element is defined. The script often\n * loads after the page has rendered, and a framework writing `chatbot.context`\n * through a ref on its first effect does so on a bare `HTMLElement`: the value\n * becomes a property of the instance, which would shadow the accessor once the\n * element is upgraded — the widget would keep that first value and never hear\n * about the next ones. `open` is not here: it is an order, not a setting, and\n * there is nothing to open before the widget has mounted.\n */\nconst UPGRADED_PROPERTIES = ['context', 'embedKey', 'user', 'scope', 'getSubjectToken', 'agent'] as const\n\nfunction createElementClass(): CustomElementConstructor {\n return class SquadicoChatbot extends HTMLElement {\n static readonly observedAttributes = ATTRIBUTES\n\n #mount: HTMLDivElement\n #controls: ChatbotControls | null = null\n #scheduled = false\n #connected = false\n #sessionId = ''\n\n /* Values set as properties (objects/functions), which have no attribute\n equivalent. They take precedence over the attributes. */\n #context?: ChatbotContext\n #user?: HostUser\n #scope?: string\n #getSubjectToken?: SubjectTokenSource\n #agent?: string\n #embedKey?: string\n\n constructor() {\n super()\n const shadow = this.attachShadow({ mode: 'open' })\n const adoptable = sharedSheet()\n if (adoptable) {\n shadow.adoptedStyleSheets = [adoptable]\n } else {\n const style = document.createElement('style')\n style.textContent = styles\n shadow.append(style)\n }\n this.#mount = document.createElement('div')\n shadow.append(this.#mount)\n\n // Hands every value written before the upgrade to its setter, so the\n // accessor is the one answering from now on.\n for (const name of UPGRADED_PROPERTIES) {\n if (!Object.hasOwn(this, name)) continue\n const value = (this as Record<string, unknown>)[name]\n delete (this as Record<string, unknown>)[name]\n ;(this as Record<string, unknown>)[name] = value\n }\n }\n\n connectedCallback(): void {\n this.#connected = true\n this.#render()\n }\n\n disconnectedCallback(): void {\n this.#connected = false\n render(null, this.#mount)\n this.#controls = null\n }\n\n attributeChangedCallback(name: string, previous: string | null, next: string | null): void {\n if (previous === next) return\n\n // `open` is imperative, not declarative: the render does not read the\n // attribute back, the controls carry the state once the widget is mounted.\n if (name === 'open' && this.#controls) {\n if (parseBool(next)) this.#controls.open()\n else this.#controls.close()\n return\n }\n this.#schedule()\n }\n\n /* ── Properties ────────────────────────────────────────── */\n\n get context(): ChatbotContext | undefined {\n return this.#context ?? parseContext(this.getAttribute('context'))\n }\n\n set context(value: ChatbotContext | undefined) {\n this.#context = value\n this.#schedule()\n }\n\n get embedKey(): string | undefined {\n return this.#embedKey ?? this.getAttribute('embed-key') ?? undefined\n }\n\n set embedKey(value: string | undefined) {\n this.#embedKey = value\n this.#schedule()\n }\n\n /** Who the host application has signed in. Settable as a property, and as a\n * ``user`` attribute holding JSON for a page that only writes markup. */\n /** Opaque partition of conversations, set from script (an organization id). */\n get scope(): string | undefined {\n return this.#scope\n }\n\n set scope(value: string | undefined) {\n this.#scope = value\n this.#schedule()\n }\n\n get user(): HostUser | undefined {\n return this.#user ?? parseUser(this.getAttribute('user'))\n }\n\n set user(value: HostUser | undefined) {\n this.#user = value\n this.#schedule()\n }\n\n /** Hands over the token the site holds for its signed-in user, before each\n * message. A property only: a function has no attribute form. */\n get getSubjectToken(): SubjectTokenSource | undefined {\n return this.#getSubjectToken\n }\n\n set getSubjectToken(value: SubjectTokenSource | undefined) {\n this.#getSubjectToken = value\n this.#schedule()\n }\n\n /** The handle this page opens on — `agent=\"sales\"` on a pricing page. A name\n * nobody answers to opens on the default agent rather than refusing. */\n get agent(): string | undefined {\n return this.#agent ?? this.getAttribute('agent') ?? undefined\n }\n\n set agent(value: string | undefined) {\n this.#agent = value\n this.#schedule()\n }\n\n get open(): boolean {\n return this.#controls?.isOpen() ?? (parseBool(this.getAttribute('open')) ?? false)\n }\n\n set open(value: boolean) {\n if (value) this.openChat()\n else this.closeChat()\n }\n\n get sessionId(): string {\n return this.#controls?.sessionId() ?? this.#sessionId\n }\n\n /* ── Imperative API ───────────────────────────────────── */\n\n openChat(): void {\n this.#controls?.open()\n }\n\n closeChat(): void {\n this.#controls?.close()\n }\n\n toggleChat(): void {\n this.#controls?.toggle()\n }\n\n reset(): void {\n this.#controls?.reset()\n }\n\n sendMessage(text: string): void {\n if (!this.#controls) {\n warn('sendMessage() called before the component was mounted — ignored')\n return\n }\n this.#controls.send(text)\n }\n\n /* ── Rendering ────────────────────────────────────────── */\n\n /** Batches several mutations in a row (a framework setting five attributes)\n * into a single render. */\n #schedule(): void {\n if (this.#scheduled || !this.#connected) return\n this.#scheduled = true\n queueMicrotask(() => {\n this.#scheduled = false\n if (this.#connected) this.#render()\n })\n }\n\n #emit = (event: ChatbotEvent): void => {\n const { type, ...detail } = event\n this.#sessionId = detail.sessionId\n this.dispatchEvent(\n new CustomEvent(type, {\n detail,\n // Crosses the shadow root to reach the host page's listeners.\n bubbles: true,\n composed: true,\n }),\n )\n }\n\n #bind = (controls: ChatbotControls | null): void => {\n this.#controls = controls\n // The `open` attribute present at mount has already been arbitrated\n // against the remembered panel state (`lib/openState`); this only\n // publishes the initial session.\n if (controls) this.#sessionId = controls.sessionId()\n }\n\n #render(): void {\n const attr = (name: string): string | undefined => this.getAttribute(name) ?? undefined\n\n render(\n <ChatbotWidget\n embedKey={this.embedKey}\n context={this.context}\n user={this.user}\n scope={this.scope}\n getSubjectToken={this.getSubjectToken}\n agent={this.agent}\n heading={attr('heading')}\n subheading={attr('subheading')}\n assistantName={attr('assistant-name')}\n placeholder={attr('placeholder')}\n greeting={attr('greeting')}\n suggestions={parseSuggestions(this.getAttribute('suggestions'))}\n width={attr('width')}\n accent={attr('accent')}\n theme={parseTheme(this.getAttribute('theme'))}\n position={parsePosition(this.getAttribute('position'))}\n layout={parseLayout(this.getAttribute('layout'))}\n defaultOpen={parseBool(this.getAttribute('open')) ?? false}\n persistOpen={parseBool(this.getAttribute('persist-open')) ?? true}\n showContext={parseBool(this.getAttribute('show-context')) ?? true}\n locale={attr('locale')}\n onEvent={this.#emit}\n bind={this.#bind}\n />,\n this.#mount,\n )\n }\n }\n}\n\nlet Constructor: CustomElementConstructor | undefined\n\n/**\n * Registers `<squadico-chatbot>`. Idempotent, and a no-op server-side.\n *\n * @param tag alternative tag name, when `squadico-chatbot` is already taken by\n * another version of the widget on the page.\n */\nexport function defineChatbot(tag: string = TAG_NAME): void {\n if (typeof window === 'undefined' || typeof HTMLElement === 'undefined') return\n Constructor ??= createElementClass()\n if (!window.customElements.get(tag)) {\n window.customElements.define(tag, Constructor)\n }\n}\n","/**\n * Default entry point of `@squadico/chatbot`.\n *\n * Importing it registers `<squadico-chatbot>` in the browser (a deliberate side\n * effect, declared through `sideEffects` in `package.json`) and does nothing\n * server-side, which makes it safe to import from a Next.js or Nuxt component.\n *\n * import '@squadico/chatbot'\n * <squadico-chatbot embed-key=\"sq_pub_…\" />\n */\nexport { defineChatbot, TAG_NAME } from './element'\nexport { DEFAULT_LANGUAGE, SUPPORTED_LANGUAGES, type LanguageCode } from './lib/i18n'\nexport { API_URL, ChatHttpError, MAX_MESSAGE_LENGTH } from './lib/client'\nexport type {\n AgentHandle,\n ApprovalDecision,\n ChatActivity,\n ChatbotContext,\n ChatbotEvent,\n ChatbotEventMap,\n ChatbotEventName,\n ChatbotLayout,\n ChatbotOptions,\n ChatbotTheme,\n ChatMessage,\n ChatRole,\n ContextObject,\n ContextValue,\n HostUser,\n LauncherPosition,\n PendingApproval,\n SquadicoChatbotElement,\n SubjectTokenSource,\n} from './types'\n\nimport { defineChatbot } from './element'\n\ndefineChatbot()\n"],"mappings":"yCAoBA,IAAM,EAAgB,IAAI,IAAY,CAAC,WAAW,CAAC,EAQnD,SAAgB,EAAc,EAA2C,CACvE,GAAI,OAAO,GAAU,SACnB,OAAO,EAAM,OAAS,EAAI,CAAE,GAAI,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