@osvi-ai/chat 0.0.0-stage → 0.1.1

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -3
  3. package/dist/core.js +10 -0
  4. package/dist/core.js.map +1 -0
  5. package/dist/index-HWHyM4-l.js +1331 -0
  6. package/dist/index-HWHyM4-l.js.map +1 -0
  7. package/dist/types/core/client.d.ts +67 -0
  8. package/dist/types/core/connection.d.ts +78 -0
  9. package/dist/types/core/errors.d.ts +14 -0
  10. package/dist/types/core/http.d.ts +38 -0
  11. package/dist/types/core/index.d.ts +7 -0
  12. package/dist/types/core/interactions.d.ts +50 -0
  13. package/dist/types/core/protocol/envelope.d.ts +2 -0
  14. package/dist/types/core/protocol/readers.d.ts +14 -0
  15. package/dist/types/core/protocol/types.d.ts +118 -0
  16. package/dist/types/core/protocol/validators.d.ts +10 -0
  17. package/dist/types/core/state.d.ts +23 -0
  18. package/dist/types/core/storage.d.ts +10 -0
  19. package/dist/types/core/version.d.ts +1 -0
  20. package/dist/types/ui/define.d.ts +1 -0
  21. package/dist/types/ui/icons.d.ts +9 -0
  22. package/dist/types/ui/index.d.ts +9 -0
  23. package/dist/types/ui/osvi-chat.d.ts +70 -0
  24. package/dist/types/ui/panel/attrs.d.ts +6 -0
  25. package/dist/types/ui/panel/composer.d.ts +10 -0
  26. package/dist/types/ui/panel/linkify.d.ts +7 -0
  27. package/dist/types/ui/panel/transcript.d.ts +4 -0
  28. package/dist/types/ui/strings.d.ts +27 -0
  29. package/dist/types/ui/styles.d.ts +1 -0
  30. package/dist/types/ui/theme.d.ts +22 -0
  31. package/dist/types/ui/tools/base.d.ts +14 -0
  32. package/dist/types/ui/tools/osvi-buttons.d.ts +10 -0
  33. package/dist/types/ui/tools/osvi-carousel.d.ts +16 -0
  34. package/dist/types/ui/tools/osvi-date-picker.d.ts +17 -0
  35. package/dist/types/widget/config.d.ts +23 -0
  36. package/dist/types/widget/index.d.ts +1 -0
  37. package/dist/types/widget/launcher.d.ts +35 -0
  38. package/dist/types/widget/widget.d.ts +13 -0
  39. package/dist/ui.js +109 -0
  40. package/dist/ui.js.map +1 -0
  41. package/dist/ui.mjs +646 -0
  42. package/dist/ui.mjs.map +1 -0
  43. package/dist/widget.js +132 -0
  44. package/dist/widget.js.map +1 -0
  45. package/package.json +60 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ui.mjs","sources":["../src/ui/theme.ts","../src/ui/strings.ts","../src/ui/panel/attrs.ts","../src/ui/panel/linkify.ts","../src/ui/panel/transcript.ts","../src/ui/icons.ts","../src/ui/panel/composer.ts","../src/ui/osvi-chat.ts","../src/ui/define.ts","../src/ui/styles.ts","../src/ui/tools/base.ts","../src/ui/tools/osvi-buttons.ts","../src/ui/tools/osvi-carousel.ts","../src/ui/tools/osvi-date-picker.ts","../src/ui/index.ts"],"sourcesContent":["export interface ChatTheme {\n colors?: Partial<Record<'primary' | 'background' | 'surface' | 'text' | 'userBubble' | 'assistantBubble', string>>;\n radius?: 'none' | 'sm' | 'md' | 'lg' | 'full' | number;\n mode?: 'light' | 'dark';\n}\nexport interface Variants { buttons?: 'chips' | 'list'; carousel?: 'slider' | 'list' }\nconst LIGHT = { primary: '#4f46e5', background: '#ffffff', surface: '#f4f4f5', text: '#18181b', userBubble: '#4f46e5', assistantBubble: '#f4f4f5' };\nconst DARK = { primary: '#6366f1', background: '#0a0a12', surface: '#1c1c27', text: '#f4f4f5', userBubble: '#6366f1', assistantBubble: '#1f1f2b' };\nconst RADII = { none: '0px', sm: '6px', md: '10px', lg: '16px', full: '9999px' };\nconst VAR = { primary: '--osvi-color-primary', background: '--osvi-color-background', surface: '--osvi-color-surface', text: '--osvi-color-text', userBubble: '--osvi-color-user-bubble', assistantBubble: '--osvi-color-assistant-bubble' };\nexport const cssVar = (key: keyof typeof LIGHT): string => `var(${VAR[key]}, ${LIGHT[key]})`;\nexport function themeVariables(theme: ChatTheme | undefined): Record<string, string> {\n const colors = { ...(theme?.mode === 'dark' ? DARK : LIGHT), ...theme?.colors };\n // The user's bubble is brand-coloured unless the customer picks it separately.\n if (!theme?.colors?.userBubble && theme?.colors?.primary) colors.userBubble = theme.colors.primary;\n const out: Record<string, string> = {};\n for (const key of Object.keys(VAR) as (keyof typeof LIGHT)[]) out[VAR[key]] = colors[key];\n const radius = theme?.radius ?? 'md';\n out['--osvi-radius'] = typeof radius === 'number' ? `${radius}px` : RADII[radius];\n return out;\n}\nexport function explicitThemeVariables(theme: ChatTheme | undefined): Record<string, string> {\n if (!theme) return {};\n if (theme.mode) return themeVariables(theme);\n const full = themeVariables(theme), out: Record<string, string> = {};\n for (const key of Object.keys(theme.colors ?? {}) as (keyof typeof LIGHT)[]) out[VAR[key]] = full[VAR[key]]!;\n if (theme.radius !== undefined) out['--osvi-radius'] = full['--osvi-radius']!;\n return out;\n}\nconst applied = new WeakMap<HTMLElement, string[]>();\nexport function applyTheme(host: HTMLElement, theme: ChatTheme | undefined): void {\n for (const key of applied.get(host) ?? []) host.style.removeProperty(key);\n const variables = explicitThemeVariables(theme);\n for (const [key, value] of Object.entries(variables)) host.style.setProperty(key, value);\n applied.set(host, Object.keys(variables));\n}\n","export const DEFAULT_STRINGS = {\nplaceholder: 'Type your message…', send: 'Send', typing: 'Typing…', humanJoined: 'A team member has joined', chooseOption: 'Choose an option to continue.', typeAnswer: 'Type your answer below, then press Send.', sending: 'Sending your response…', pausedForHuman: 'Choices are paused while a team member is connected.', sendFailed: 'Message not sent.', retry: 'Retry', sessionEnded: 'Conversation ended', reconnecting: 'Reconnecting…', offline: 'You are offline. We will reconnect automatically.', unavailable: 'This chat is unavailable.', originBlocked: 'This chat is not enabled for this website.', rateLimited: 'Too many requests. Please try again in a few minutes.', tryAgain: 'Try again', closeChat: 'Close chat', poweredBy: 'Powered by Osvi AI', newChat: 'New chat', emptyState: 'Send a message to start chatting.', defaultTitle: 'Chat',\n};\nexport type ChatStrings = { [K in keyof typeof DEFAULT_STRINGS]: string };\n","import type { ChatTheme } from '../theme';\nconst warned = new Set<string>();\nfunction warnOnce(name: string, message: string) { if (!warned.has(name)) { warned.add(name); console.warn(`[osvi-chat] ${message}`); } }\nexport function oneOf<T extends string>(value: string | null | undefined, allowed: readonly T[]): T | undefined { return value != null && (allowed as readonly string[]).includes(value) ? value as T : undefined; }\nexport function parseRadius(value: string | null | undefined): ChatTheme['radius'] | undefined {\n if (value == null) return undefined;\n return oneOf(value, ['none', 'sm', 'md', 'lg', 'full'] as const) ?? (/^\\d{1,2}(?:px)?$/.test(value) ? Number(value.replace(/px$/, '')) : undefined);\n}\nexport function safeBaseUrl(value: string | null | undefined): string | undefined {\n if (!value) return undefined;\n try { const u = new URL(value); if (!u.username && !u.password && (u.protocol === 'https:' || u.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(u.hostname))) return value.replace(/\\/+$/, ''); } catch { /* ignored */ }\n warnOnce('base-url', 'ignored an invalid base-url (https required, http only for localhost)'); return undefined;\n}\nexport function safeAvatar(value: string | null | undefined): string | undefined {\n if (!value) return undefined;\n if (/^data:image\\/(png|jpeg|gif|webp);base64,[a-z0-9+/]+={0,2}$/i.test(value)) return value;\n try { const u = new URL(value); if (u.protocol === 'https:' && !u.username && !u.password) return value; } catch { /* ignored */ }\n return undefined;\n}\nexport function parseJsonAttr(name: string, value: string | null | undefined): Record<string, unknown> | undefined {\n if (!value) return undefined;\n try { const parsed: unknown = JSON.parse(value); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as Record<string, unknown>; } catch { /* warn below */ }\n warnOnce(name, `ignored invalid JSON in the ${name} attribute`); return undefined;\n}\n","export type LinkPart = { text: string } | { href: string; text: string };\nconst URL_RE = /https?:\\/\\/[^\\s<>\"']+/g;\nconst count = (s: string, ch: string) => s.split(ch).length - 1;\nfunction trimUrl(url: string): string {\n for (;;) { const c = url[url.length - 1];\n if (c && '.,!?;:'.includes(c) || c === ')' && count(url, ')') > count(url, '(') || c === ']' && count(url, ']') > count(url, '[')) { url = url.slice(0, -1); continue; } return url; }\n}\nexport function linkify(text: string): LinkPart[] {\n const out: LinkPart[] = []; let last = 0;\n for (const m of text.matchAll(URL_RE)) { const url = trimUrl(m[0]), start = m.index!;\n try { const u = new URL(url); if (!['http:', 'https:'].includes(u.protocol)) continue; } catch { continue; }\n if (start > last) out.push({ text: text.slice(last, start) }); out.push({ href: url, text: url }); last = start + url.length; }\n if (last < text.length) out.push({ text: text.slice(last) }); return out.length ? out : [{ text }];\n}\n","import { html, nothing } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport type { ChatState } from '../../core';\nimport type { ChatStrings } from '../strings';\nimport type { Variants } from '../theme';\nimport { linkify } from './linkify';\nexport function renderTranscript(state: ChatState, strings: ChatStrings, variants: Variants, baseUrl: string, retry: (id: string) => void) {\n return html`${state.items.length ? repeat(state.items, item => item.id, item => {\n if (item.kind === 'divider') return html`<p class=\"divider\">${strings.sessionEnded}</p>`;\n if (item.kind === 'message') return html`<article class=${`bubble ${item.role}`}>${item.role === 'human' ? html`<small class=\"team\">Team</small>` : nothing}<p>${linkify(item.content).map(p => 'href' in p ? html`<a href=${p.href} target=\"_blank\" rel=\"noopener noreferrer\">${p.text}</a>` : p.text)}</p>${item.role === 'user' && item.status === 'failed' ? html`<span class=\"failed\"><span>${strings.sendFailed}</span><button type=\"button\" @click=${() => retry(item.id)}>${strings.retry}</button></span>` : nothing}</article>`;\n const i = item.interaction, live = i.interaction_id === state.activeInteraction?.interaction_id && i.interaction_status === 'pending';\n const disabled = !live || state.interactionPending || state.mode === 'human';\n switch (i.tool_type) {\n case 'ui_buttons': return html`<osvi-buttons data-live=${live ? 'true' : 'false'} .interaction=${i} .disabled=${disabled} .variant=${variants.buttons ?? 'chips'} base-url=${baseUrl}></osvi-buttons>`;\n case 'ui_carousel': return html`<osvi-carousel data-live=${live ? 'true' : 'false'} .interaction=${i} .disabled=${disabled} .variant=${variants.carousel ?? 'slider'} base-url=${baseUrl}></osvi-carousel>`;\n case 'ui_date_picker': return html`<osvi-date-picker data-live=${live ? 'true' : 'false'} .interaction=${i} .disabled=${disabled} base-url=${baseUrl}></osvi-date-picker>`;\n default: return html`<p>${i.content}</p>`;\n }\n }) : html`<p class=\"empty\">${strings.emptyState}</p>`}${state.awaitingReply ? html`<div class=\"typing\" role=\"img\" aria-label=${strings.typing}><i></i><i></i><i></i></div>` : nothing}`;\n}\n","import { svg } from 'lit';\n\n// Inline icons (no network, no font). Each SVG is decorative; buttons carry their own text label.\nconst stroke = (d: unknown, cls = '') => svg`<svg class=${cls} viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">${d}</svg>`;\nexport const chatIcon = stroke(svg`<path d=\"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z\"/><path d=\"M8.5 8.5h7M8.5 11.5h4\"/>`);\nexport const newChatIcon = stroke(svg`<path d=\"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z\"/><path d=\"M12 6.5v6M9 9.5h6\"/>`);\nexport const closeIcon = stroke(svg`<path d=\"M6 6l12 12M18 6L6 18\"/>`);\nexport const launcherChatIcon = stroke(svg`<path d=\"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z\"/><path d=\"M8.5 8.5h7M8.5 11.5h4\"/>`, 'chat');\nexport const launcherCloseIcon = stroke(svg`<path d=\"M6 6l12 12M18 6L6 18\"/>`, 'close');\nexport const sendIcon = stroke(svg`<path d=\"M12 19V5M5.5 11.5L12 5l6.5 6.5\"/>`);\nexport const leftIcon = stroke(svg`<path d=\"M15 6l-6 6 6 6\"/>`);\nexport const rightIcon = stroke(svg`<path d=\"M9 6l6 6-6 6\"/>`);\n\n// Osvi AI mark. Ids are scoped by the shadow root each copy renders into.\nexport const osviLogo = svg`<svg viewBox=\"0 0 134 134\" aria-hidden=\"true\" focusable=\"false\"><defs><linearGradient id=\"osvi-g\" x1=\"-36.28\" y1=\"32.2\" x2=\"161.98\" y2=\"93.64\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".304\" stop-color=\"#155DFC\"/><stop offset=\".822\" stop-color=\"#353333\"/></linearGradient><mask id=\"osvi-m\" style=\"mask-type:alpha\" maskUnits=\"userSpaceOnUse\" x=\"-7\" y=\"-6\" width=\"149\" height=\"150\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" fill=\"#0F0F0F\" d=\"M141.385 114.008L141.622 108.411V29.4704L141.385 23.8743C139.964 7.44314 126.224 -5.41602 109.523 -5.41602H25.3094C8.60869 -5.41602 -5.13083 7.44314 -6.55216 23.8743L-6.78906 29.4704V108.411L-6.55216 114.008C-5.13083 130.439 8.60869 143.298 25.3094 143.298H109.523C126.224 143.298 139.964 130.439 141.385 114.008ZM25.3094 102.339C9.55625 102.339 65.7059 83.8874 53.6176 66.6191C42.3654 50.5452 93.7703 32.6852 109.523 32.6852C125.277 32.6852 73.161 54.1172 81.4521 80.9071C86.1899 96.2156 40.944 102.339 25.3094 102.339Z\"/></mask></defs><g mask=\"url(#osvi-m)\"><ellipse cx=\"66.88\" cy=\"66.79\" rx=\"67.22\" ry=\"66.81\" fill=\"url(#osvi-g)\"/></g></svg>`;\n","import { html } from 'lit';\nimport { live } from 'lit/directives/live.js';\nimport type { ChatStrings } from '../strings';\nimport { sendIcon } from '../icons';\nexport interface ComposerOptions { strings: ChatStrings; draft: string; placeholder: string; disabled: boolean; input: (event: Event) => void; send: () => void }\nexport function renderComposer(o: ComposerOptions) {\n return html`<div class=\"composer\"><textarea rows=\"1\" aria-label=\"Message\" placeholder=${o.placeholder} .value=${live(o.draft)} ?disabled=${o.disabled} @input=${(e: Event) => { const ta = e.target as HTMLTextAreaElement; ta.style.height = 'auto'; ta.style.height = `${Math.min(ta.scrollHeight, 120)}px`; o.input(e); }} @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !o.disabled) { e.preventDefault(); o.send(); } }}></textarea><button type=\"button\" class=\"send\" title=${o.strings.send} aria-label=${o.strings.send} ?disabled=${o.disabled || !o.draft.trim()} @click=${o.send}>${sendIcon}<span class=\"sr\">${o.strings.send}</span></button></div>`;\n}\n","import { LitElement, css, html, nothing } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { createChatClient, type ChatClient, type ChatState, type InteractionResponse } from '../core';\nimport { applyTheme, type ChatTheme, type Variants } from './theme';\nimport { DEFAULT_STRINGS, type ChatStrings } from './strings';\nimport { oneOf, parseJsonAttr, parseRadius, safeAvatar, safeBaseUrl } from './panel/attrs';\nimport { renderTranscript } from './panel/transcript';\nimport { renderComposer } from './panel/composer';\nimport { closeIcon, newChatIcon, osviLogo } from './icons';\nconst emptyState = (): ChatState => ({ status: 'idle', mode: 'ai', awaitingReply: false, items: [], activeInteraction: null, interactionPending: false, agent: null, error: null });\nconst bool = { fromAttribute: (v: string | null) => v !== 'false' };\nexport class OsviChat extends LitElement {\n static clientFactory = createChatClient;\n static properties = { themeAttribute: { attribute: 'theme' }, stringsAttribute: { attribute: 'strings' } };\n static styles = css`\n :host { --p:var(--osvi-color-primary,#4f46e5); --bg:var(--osvi-color-background,#fff); --surface:var(--osvi-color-surface,#f4f4f5); --text:var(--osvi-color-text,#18181b);\n --ub:var(--osvi-color-user-bubble,var(--p)); --ab:var(--osvi-color-assistant-bubble,var(--surface)); --r:var(--osvi-radius,14px);\n --sub:color-mix(in srgb,var(--text) 58%,var(--bg)); --line:color-mix(in srgb,var(--text) 11%,var(--bg));\n display:flex; flex-direction:column; height:100%; min-height:260px; color:var(--text); background:var(--bg); font-family:inherit; font-size:14px; line-height:1.5; border-radius:var(--r); overflow:hidden; }\n * { box-sizing:border-box; } h2,p { margin:0; }\n button,textarea { font:inherit; color:inherit; } button { cursor:pointer; } button:disabled { cursor:default; opacity:.45; }\n button:focus-visible,textarea:focus-visible,a:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:2px; }\n .sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; }\n header { display:flex; align-items:center; gap:12px; padding:14px 12px 14px 16px; border-bottom:1px solid var(--line); }\n .avatar { width:38px; height:38px; border-radius:50%; flex:none; object-fit:cover; display:grid; place-items:center; background:var(--p); color:#fff; font-weight:700; font-size:15px; }\n .heading { flex:1; min-width:0; } h2 { font-size:15px; line-height:1.3; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }\n .heading p,.heading small { display:block; font-size:12.5px; color:var(--sub); }\n .heading small { color:var(--p); font-weight:600; }\n .icon { width:34px; height:34px; border:0; border-radius:10px; background:transparent; color:var(--sub); display:grid; place-items:center; flex:none; }\n .icon:hover:not(:disabled) { background:var(--surface); color:var(--text); } .icon svg { width:18px; height:18px; }\n .transcript { flex:1; overflow:auto; padding:18px 16px; min-height:0; display:flex; flex-direction:column; gap:10px; }\n .empty { margin:auto; color:var(--sub); text-align:center; }\n .bubble { width:fit-content; max-width:84%; padding:10px 14px; border-radius:var(--r); border-bottom-left-radius:6px; background:var(--ab); overflow-wrap:anywhere; white-space:pre-wrap; }\n .bubble.user { align-self:flex-end; color:#fff; background:var(--ub); border-bottom-left-radius:var(--r); border-bottom-right-radius:6px; }\n .bubble a { color:inherit; } .team { display:block; font-size:11px; font-weight:600; color:var(--p); margin-bottom:2px; }\n .failed { display:flex; align-items:center; gap:8px; font-size:12px; margin-top:6px; } .failed button { border:0; background:rgb(255 255 255/.2); border-radius:8px; padding:2px 8px; }\n .divider { display:flex; align-items:center; gap:10px; color:var(--sub); font-size:12px; } .divider::before,.divider::after { content:\"\"; flex:1; height:1px; background:var(--line); }\n .typing { display:inline-flex; gap:4px; padding:12px 14px; background:var(--ab); border-radius:var(--r); border-bottom-left-radius:6px; width:fit-content; }\n .typing i { width:6px; height:6px; border-radius:50%; background:var(--sub); animation:osvi-dot 1.2s infinite; } .typing i:nth-child(2) { animation-delay:.15s; } .typing i:nth-child(3) { animation-delay:.3s; }\n @keyframes osvi-dot { 0%,60%,100% { opacity:.35; transform:none; } 30% { opacity:1; transform:translateY(-3px); } }\n osvi-buttons,osvi-carousel,osvi-date-picker { display:block; max-width:100%; }\n .status { padding:0 16px; font-size:12.5px; color:var(--sub); display:flex; gap:8px; align-items:center; } .status:empty { display:none; }\n .status button { border:1px solid var(--line); background:var(--bg); border-radius:8px; padding:3px 10px; }\n .composer { margin:10px 12px; display:flex; align-items:flex-end; gap:8px; border:1px solid var(--line); border-radius:18px; padding:6px 6px 6px 14px; background:var(--surface); }\n .composer:focus-within { border-color:var(--p); box-shadow:0 0 0 3px color-mix(in srgb,var(--p) 18%,transparent); }\n textarea { flex:1; min-width:0; border:0; outline:0; background:transparent; resize:none; min-height:24px; max-height:120px; padding:6px 0; field-sizing:content; }\n textarea::placeholder { color:var(--sub); } textarea:focus-visible { outline:0; }\n .send { width:36px; height:36px; border:0; border-radius:50%; background:var(--p); color:#fff; display:grid; place-items:center; flex:none; } .send svg { width:17px; height:17px; }\n footer { padding:0 16px 12px; text-align:center; font-size:11.5px; } footer a { color:var(--sub); text-decoration:none; display:inline-flex; align-items:center; gap:6px; }\n footer a:hover { color:var(--text); } footer svg { width:14px; height:14px; flex:none; }\n @media (prefers-reduced-motion:reduce) { .typing i { animation:none; } }\n `;\n @property({ attribute: 'agent-id' }) agentId = '';\n @property({ attribute: 'base-url' }) baseUrl = '';\n @property({ attribute: false }) client: ChatClient | null = null;\n @property({ attribute: false }) theme: ChatTheme = {};\n @property({ attribute: false }) variants: Variants = {};\n @property({ attribute: false }) strings: Partial<ChatStrings> = {};\n @property({ attribute: 'powered-by', converter: bool }) poweredBy = true;\n @property({ attribute: 'new-chat', converter: bool }) newChat = true;\n @property({ attribute: 'new-chat-history' }) newChatHistory: string | undefined; // 'clear' (default) | 'keep'\n @property({ attribute: false }) header: { title?: string; subtitle?: string; avatarUrl?: string } = {};\n @property({ type: Boolean }) closable = false;\n @property({ attribute: 'header-title' }) headerTitle: string | undefined;\n @property({ attribute: 'header-subtitle' }) headerSubtitle: string | undefined;\n @property({ attribute: 'header-avatar' }) headerAvatar: string | undefined;\n @property({ attribute: 'primary-color' }) primaryColor: string | undefined;\n @property() radius: string | undefined;\n @property() mode: string | undefined;\n @property() buttons: string | undefined;\n @property() carousel: string | undefined;\n declare themeAttribute: string | undefined;\n declare stringsAttribute: string | undefined;\n @state() private chatState = emptyState();\n @state() private draft = '';\n @state() private busy = false;\n @state() private typed: { id: string; placeholder?: string; previousDraft: string } | null = null;\n private ownClient: ChatClient | null = null;\n private boundClient: ChatClient | null = null;\n private ownKey = '';\n private unsubscribe: (() => void) | undefined;\n private generation = 0;\n private followBottom = true;\n private focusedInteraction: string | null = null;\n connectedCallback() { super.connectedCallback(); this.syncClient(); }\n disconnectedCallback() { super.disconnectedCallback(); this.releaseClient(); }\n private releaseClient() {\n ++this.generation; this.unsubscribe?.(); this.unsubscribe = undefined;\n this.boundClient = null; const own = this.ownClient; this.ownClient = null; this.ownKey = '';\n own?.destroy(); this.busy = false; this.typed = null; this.focusedInteraction = null; this.requestUpdate();\n }\n private syncClient() {\n if (!this.isConnected) return;\n if (!this.client && !this.agentId && !this.boundClient) return;\n const key = JSON.stringify([this.agentId, safeBaseUrl(this.baseUrl)]);\n if (this.client ? this.boundClient === this.client && !this.ownClient : this.ownClient && key === this.ownKey) return;\n this.releaseClient(); this.chatState = emptyState();\n if (!this.client && !this.agentId) return;\n const own = !this.client;\n const client = this.client ?? OsviChat.clientFactory({ agentId: this.agentId, baseUrl: safeBaseUrl(this.baseUrl) });\n this.boundClient = client;\n if (own) { this.ownClient = client; this.ownKey = key; }\n const generation = this.generation;\n this.chatState = client.getState(); this.requestUpdate();\n this.unsubscribe = client.subscribe(state => {\n if (this.generation !== generation || this.boundClient !== client) return;\n this.chatState = state; this.requestUpdate();\n if (this.typed && (state.mode === 'human' || state.activeInteraction?.interaction_id !== this.typed.id || state.activeInteraction.interaction_status !== 'pending')) this.restoreDraft();\n });\n if (own) void this.run(() => client.start());\n }\n protected willUpdate() { this.syncClient(); applyTheme(this, this.mergedTheme()); }\n private mergedTheme(): ChatTheme {\n const attr = parseJsonAttr('theme', this.themeAttribute);\n const colors: NonNullable<ChatTheme['colors']> = {};\n const rawColors = attr?.colors;\n if (rawColors && typeof rawColors === 'object' && !Array.isArray(rawColors)) {\n for (const key of ['primary', 'background', 'surface', 'text', 'userBubble', 'assistantBubble'] as const) {\n const value = (rawColors as Record<string, unknown>)[key]; if (typeof value === 'string') colors[key] = value;\n }\n }\n if (typeof this.primaryColor === 'string') colors.primary = this.primaryColor;\n const radius = parseRadius(this.radius) ?? (typeof attr?.radius === 'number' && Number.isInteger(attr.radius) && attr.radius >= 0 && attr.radius <= 99 ? attr.radius : typeof attr?.radius === 'string' ? parseRadius(attr.radius) : undefined);\n const mode = oneOf(this.mode, ['light', 'dark'] as const) ?? oneOf(typeof attr?.mode === 'string' ? attr.mode : undefined, ['light', 'dark'] as const);\n return { ...this.theme, colors: { ...this.theme?.colors, ...colors }, ...(radius === undefined ? {} : { radius }), ...(mode === undefined ? {} : { mode }) };\n }\n private get labels(): ChatStrings {\n const out = { ...DEFAULT_STRINGS };\n for (const source of [this.strings, parseJsonAttr('strings', this.stringsAttribute)]) {\n for (const key of Object.keys(DEFAULT_STRINGS) as (keyof ChatStrings)[]) if (typeof source?.[key] === 'string') out[key] = source[key] as string;\n }\n return out;\n }\n private get blocked() {\n const s = this.chatState;\n return !this.boundClient || this.busy || s.status === 'connecting' || s.status === 'closed' && !!s.error && !s.error.retryable || s.mode === 'ai' && (s.interactionPending || s.activeInteraction?.interaction_status === 'pending' && !this.typed);\n }\n private get sessionBusy() { return this.busy || this.chatState.status === 'connecting' || this.chatState.interactionPending || this.chatState.items.some(i => i.kind === 'message' && i.status === 'sending'); }\n private async run(action: () => unknown): Promise<void> {\n if (this.busy || !this.boundClient) return;\n const generation = this.generation; this.busy = true; this.requestUpdate();\n try { await action(); } catch { /* Client state owns errors; prevent unhandled rejections from host callbacks. */ }\n finally { if (this.generation === generation) { this.busy = false; this.requestUpdate(); } }\n }\n private restoreDraft() { if (this.typed) { this.draft = this.typed.previousDraft; this.typed = null; this.requestUpdate(); } }\n private send = () => {\n if (this.blocked || !this.draft.trim() || !this.boundClient) return;\n const client = this.boundClient, value = this.draft.trim(), typed = this.typed;\n this.draft = ''; if (typed) this.restoreDraft(); this.requestUpdate();\n const box = this.renderRoot.querySelector<HTMLTextAreaElement>('textarea'); if (box) box.style.height = '';\n void this.run(() => typed ? client.respond(typed.id, { kind: 'text', value }) : client.send(value));\n };\n private respond = (event: CustomEvent<{ interactionId: string; response: InteractionResponse }>) => {\n const d = event.detail, s = this.chatState;\n if (!d || this.busy || s.mode !== 'ai' || s.interactionPending || s.activeInteraction?.interaction_status !== 'pending' || d.interactionId !== s.activeInteraction.interaction_id) return;\n event.stopPropagation(); const client = this.boundClient; if (client) void this.run(() => client.respond(d.interactionId, d.response));\n };\n private requestInput = (event: CustomEvent<{ interactionId: string; placeholder?: string }>) => {\n const d = event.detail, s = this.chatState;\n if (!d || this.busy || s.mode !== 'ai' || s.interactionPending || s.activeInteraction?.interaction_status !== 'pending' || d.interactionId !== s.activeInteraction.interaction_id) return;\n event.stopPropagation();\n this.typed = { id: d.interactionId, placeholder: typeof d.placeholder === 'string' ? d.placeholder : undefined, previousDraft: this.typed?.previousDraft ?? this.draft };\n this.draft = ''; this.requestUpdate(); void this.updateComplete.then(() => this.renderRoot.querySelector('textarea')?.focus());\n };\n async focusActiveInteraction(): Promise<void> {\n await this.updateComplete;\n if (!this.isConnected || this.chatState.activeInteraction?.interaction_status !== 'pending') return;\n const tool = this.renderRoot.querySelector<LitElement>('[data-live=\"true\"]');\n if (!tool) return; const id = this.chatState.activeInteraction.interaction_id;\n await tool.updateComplete;\n if (!this.isConnected || this.chatState.activeInteraction?.interaction_id !== id) return;\n tool.shadowRoot?.querySelector<HTMLElement>('button:not(:disabled),input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex=\"0\"]')?.focus();\n }\n protected updated() {\n const log = this.renderRoot.querySelector<HTMLElement>('.transcript');\n if (log && this.followBottom) log.scrollTop = log.scrollHeight;\n const id = this.chatState.activeInteraction?.interaction_status === 'pending' ? this.chatState.activeInteraction.interaction_id : null;\n if (id !== this.focusedInteraction) {\n this.focusedInteraction = id;\n if (id && this.isConnected && !this.hidden && document.visibilityState !== 'hidden') void this.focusActiveInteraction();\n }\n }\n private statusText(strings: ChatStrings): string {\n const s = this.chatState;\n if (s.error?.code === 'origin_not_allowed') return strings.originBlocked;\n if (s.error && ['agent_inactive', 'agent_archived', 'agent_not_found'].includes(s.error.code)) return strings.unavailable;\n if (s.error?.code === 'rate_limited') return strings.rateLimited;\n if (s.error?.code === 'token_failed') return s.error.message;\n if (s.status === 'recovering') return strings.reconnecting;\n if (s.status === 'offline') return strings.offline;\n if (s.interactionPending || this.busy && this.typed) return strings.sending;\n if (s.activeInteraction?.interaction_status === 'pending') return s.mode === 'human' ? strings.pausedForHuman : this.typed ? strings.typeAnswer : strings.chooseOption;\n if (s.status === 'closed') return strings.sessionEnded;\n return '';\n }\n render() {\n const strings = this.labels, s = this.chatState, client = this.boundClient;\n const avatar = safeAvatar(this.headerAvatar ?? this.header.avatarUrl);\n const variants: Variants = { ...this.variants, ...(oneOf(this.buttons, ['chips', 'list'] as const) ? { buttons: oneOf(this.buttons, ['chips', 'list'] as const) } : {}), ...(oneOf(this.carousel, ['slider', 'list'] as const) ? { carousel: oneOf(this.carousel, ['slider', 'list'] as const) } : {}) };\n const title = this.headerTitle ?? this.header.title ?? s.agent?.name ?? strings.defaultTitle;\n return html`<header>${avatar ? html`<img class=\"avatar\" src=${avatar} alt=\"\" referrerpolicy=\"no-referrer\">` : html`<span class=\"avatar\" aria-hidden=\"true\">${title.trim().charAt(0).toUpperCase()}</span>`}<div class=\"heading\"><h2>${title}</h2>${this.headerSubtitle ?? this.header.subtitle ? html`<p>${this.headerSubtitle ?? this.header.subtitle}</p>` : nothing}${s.mode === 'human' ? html`<small>${strings.humanJoined}</small>` : nothing}</div>\n ${this.newChat ? html`<button type=\"button\" class=\"icon\" title=${strings.newChat} ?disabled=${!client || this.sessionBusy} @click=${() => client && !this.sessionBusy && void this.run(() => client.newSession({ keepHistory: this.newChatHistory === 'keep' }))}>${newChatIcon}<span class=\"sr\">${strings.newChat}</span></button>` : nothing}\n ${this.closable ? html`<button type=\"button\" class=\"icon\" title=${strings.closeChat} aria-label=${strings.closeChat} @click=${() => this.dispatchEvent(new CustomEvent('osvi-close', { bubbles: true, composed: true }))}>${closeIcon}</button>` : nothing}</header>\n <div class=\"transcript\" role=\"log\" aria-live=\"polite\" aria-label=\"Conversation\" @scroll=${(e: Event) => { const el = e.currentTarget as HTMLElement; this.followBottom = el.scrollHeight - el.scrollTop - el.clientHeight <= 80; }} @osvi-respond=${this.respond} @osvi-request-input=${this.requestInput}>${renderTranscript(s, strings, variants, client?.resolveUrl('') ?? '', id => { if (client) void this.run(() => client.retry(id)); })}</div>\n <div class=\"status\" role=\"status\">${this.statusText(strings)}${s.error?.retryable && (s.status === 'idle' || s.status === 'closed') ? html`<button type=\"button\" ?disabled=${this.busy || !client} @click=${() => client && void this.run(() => client.start())}>${strings.tryAgain}</button>` : nothing}</div>\n ${renderComposer({ strings, draft: this.draft, placeholder: this.typed?.placeholder ?? strings.placeholder, disabled: this.blocked, input: e => { this.draft = (e.target as HTMLTextAreaElement).value; this.requestUpdate(); }, send: this.send })}\n ${this.poweredBy ? html`<footer><a href=\"https://osvi.ai\" target=\"_blank\" rel=\"noopener noreferrer\">${osviLogo}<span>${strings.poweredBy}</span></a></footer>` : nothing}`;\n }\n}\n","export function defineOnce(name: string, ctor: CustomElementConstructor): void {\n if (typeof customElements === 'undefined' || customElements.get(name)) return;\n customElements.define(name, ctor);\n}\n","import { css, unsafeCSS } from 'lit';\nimport { cssVar } from './theme';\nconst v = (k: Parameters<typeof cssVar>[0]) => unsafeCSS(cssVar(k));\nexport const toolStyles = css`\n :host { --p:${v('primary')}; --bg:${v('background')}; --surface:${v('surface')}; --text:${v('text')}; --r:var(--osvi-radius,14px);\n --sub:color-mix(in srgb,var(--text) 58%,var(--bg)); --line:color-mix(in srgb,var(--text) 11%,var(--bg));\n display:block; font:inherit; color:var(--text); }\n * { box-sizing:border-box; }\n p { margin:0 0 6px; } .label { font-weight:600; } .description { color:var(--sub); font-size:13px; }\n .answer { display:inline-block; margin-top:2px; padding:4px 10px; border-radius:999px; background:color-mix(in srgb,var(--p) 12%,var(--bg)); color:var(--p); font-weight:600; font-size:13px; }\n .sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; }\n button { font:inherit; color:inherit; cursor:pointer; }\n button:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:2px; }\n button:disabled { opacity:.45; cursor:default; }\n small { display:block; color:var(--sub); font-size:12px; font-weight:400; }\n .chips { display:flex; flex-wrap:wrap; gap:8px; }\n .chips button { border:1.5px solid color-mix(in srgb,var(--p) 55%,var(--line)); background:var(--bg); color:var(--p); border-radius:999px; padding:7px 14px; font-weight:600; font-size:13px; text-align:center; }\n .chips button:hover:not(:disabled) { background:color-mix(in srgb,var(--p) 10%,var(--bg)); }\n .text { display:grid; gap:1px; min-width:0; }\n .chips small { color:inherit; opacity:.8; }\n .list { display:grid; gap:6px; }\n .list > button { display:flex; justify-content:space-between; align-items:center; gap:10px; width:100%; text-align:left; border:1px solid var(--line); background:var(--bg); border-radius:12px; padding:10px 12px; }\n .list > button:hover:not(:disabled) { border-color:var(--p); }\n .list > button svg { width:16px; height:16px; flex:none; color:var(--sub); }\n .card { background:var(--bg); border:1px solid var(--line); border-radius:var(--r); overflow:hidden; box-shadow:0 6px 18px -10px rgb(16 18 30/.35); }\n .card .body { padding:10px 12px 12px; display:grid; gap:4px; } .card h3 { margin:0; font-size:14px; } .card p { margin:0; color:var(--sub); font-size:12.5px; }\n .image { aspect-ratio:16 / 9; max-width:100%; display:grid; place-items:center; overflow:hidden; background:var(--surface); color:var(--sub); font-size:12px; }\n .image img { width:100%; height:100%; object-fit:cover; display:block; }\n .primary { justify-self:start; margin-top:6px; border:0; border-radius:10px; background:var(--p); color:#fff; font-weight:600; font-size:13px; padding:8px 14px; }\n .list .card { display:grid; grid-template-columns:minmax(0,88px) 1fr; } .list .card .image { aspect-ratio:auto; height:100%; min-height:88px; }\n .list .card:not(:has(.image)) { grid-template-columns:1fr; }\n .navigation { display:flex; align-items:center; justify-content:space-between; gap:8px; margin:10px 0 0; }\n .round { width:32px; height:32px; border-radius:50%; border:1px solid var(--line); background:var(--bg); display:grid; place-items:center; padding:0; flex:none; }\n .round:hover:not(:disabled) { border-color:var(--p); } .round svg { width:15px; height:15px; }\n .dots { display:flex; gap:5px; align-items:center; } .dots i { width:6px; height:6px; border-radius:3px; background:var(--line); transition:width .2s; } .dots i.on { width:16px; background:var(--p); }\n .calendar { border:1px solid var(--line); border-radius:var(--r); padding:10px; background:var(--bg); display:grid; gap:6px; }\n .calendar .navigation { margin:0; font-weight:600; font-size:13px; }\n .days, .weekdays { display:grid; grid-template-columns:repeat(7, minmax(0, 1fr)); gap:2px 0; text-align:center; }\n .weekdays { color:var(--sub); font-size:11px; }\n .days button { border:0; background:transparent; height:30px; border-radius:8px; padding:0; font-size:12.5px; font-variant-numeric:tabular-nums; }\n .days button:hover:not(:disabled) { background:var(--surface); }\n .days button.today { box-shadow:inset 0 0 0 1.5px var(--line); }\n .days button.in { background:color-mix(in srgb,var(--p) 14%,transparent); border-radius:0; }\n .days button[aria-pressed=\"true\"] { background:var(--p); color:#fff; }\n .days button.start:not(.end) { border-radius:8px 0 0 8px; } .days button.end:not(.start) { border-radius:0 8px 8px 0; }\n .hint { color:var(--sub); font-size:12px; margin:0; }\n @media (prefers-reduced-motion:reduce) { .dots i { transition:none; } }\n`;\n","import { LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport type { InteractionMessage, InteractionResponse } from '../../core/protocol/types';\nimport { isInteractionPresentation } from '../../core/protocol/validators';\nimport { applyTheme, type ChatTheme } from '../theme';\nexport abstract class ToolElement extends LitElement {\n @property({ attribute: false }) interaction: InteractionMessage | null = null;\n @property({ type: Boolean }) disabled = false;\n @property({ attribute: false }) theme: ChatTheme | undefined;\n @property({ attribute: 'base-url' }) baseUrl = '';\n protected abstract readonly toolType: string;\n protected get live(): boolean { return !this.disabled && this.interaction?.interaction_status === 'pending'; }\n protected get valid(): boolean {\n const i = this.interaction;\n return !!i && i.tool_type === this.toolType && isInteractionPresentation(i, i.presentation);\n }\n protected respond(response: InteractionResponse): void {\n if (!this.interaction || !this.live || !this.valid) return;\n this.dispatchEvent(new CustomEvent('osvi-respond', { bubbles: true, composed: true, detail: { interactionId: this.interaction.interaction_id, response } }));\n }\n protected updated(changed: Map<PropertyKey, unknown>): void { if (changed.has('theme')) applyTheme(this, this.theme); }\n}\n","import { html, nothing } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport type { ChoicePresentation } from '../../core/protocol/types';\nimport { toolStyles } from '../styles';\nimport { ToolElement } from './base';\nimport { rightIcon } from '../icons';\nexport class OsviButtons extends ToolElement {\n static styles = toolStyles;\n protected readonly toolType = 'ui_buttons';\n @property() variant: 'chips' | 'list' = 'chips';\n render() {\n const i = this.interaction;\n if (!i) return nothing;\n if (!this.valid) return html`<p>${i.content}</p>`;\n const p = i.presentation as ChoicePresentation;\n const chosen = i.response_payload?.kind === 'text' ? i.response_payload.value : p.options.find(o => o.id === (i.response_payload?.kind === 'selection' ? i.response_payload.value : i.selected_option_id))?.label;\n return html`<p class=\"label\">${p.label}</p>${p.description ? html`<p class=\"description\">${p.description}</p>` : nothing}\n ${this.live ? html`<div role=\"group\" aria-label=\"Options\" class=${this.variant} @keydown=${this.onKey}>\n ${p.options.map(o => html`<button type=\"button\" @click=${() => this.pick(o.id, o.allow_input, o.input_placeholder)}><span class=\"text\"><span>${o.label}</span>${o.description ? html`<small>${o.description}</small>` : nothing}</span>${this.variant === 'list' ? rightIcon : nothing}</button>`)}\n </div>` : chosen ? html`<p class=\"answer\">${chosen}</p>` : nothing}`;\n }\n private pick(id: string, allowInput?: true, placeholder?: string) {\n if (!this.live || !this.valid || !this.interaction) return;\n if (this.interaction.schema_version === 2 && allowInput) {\n this.dispatchEvent(new CustomEvent('osvi-request-input', { bubbles: true, composed: true, detail: { interactionId: this.interaction.interaction_id, placeholder } }));\n } else this.respond({ kind: 'selection', value: id });\n }\n private onKey(e: KeyboardEvent) {\n if (!['ArrowDown', 'ArrowUp', 'ArrowRight', 'ArrowLeft'].includes(e.key)) return;\n const list = [...this.renderRoot.querySelectorAll('button')];\n const at = list.indexOf((this.renderRoot as ShadowRoot).activeElement as HTMLButtonElement);\n const step = e.key === 'ArrowDown' || e.key === 'ArrowRight' ? 1 : -1;\n list[(at + step + list.length) % list.length]?.focus(); e.preventDefault();\n }\n}\n","import { html, nothing } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport type { CarouselItem, CarouselPresentation } from '../../core/protocol/types';\nimport { isProxyImageUrl } from '../../core/protocol/validators';\nimport { toolStyles } from '../styles';\nimport { ToolElement } from './base';\nimport { leftIcon, rightIcon } from '../icons';\nexport class OsviCarousel extends ToolElement {\n static styles = toolStyles;\n protected readonly toolType = 'ui_carousel';\n @property() variant: 'slider' | 'list' = 'slider';\n @state() private index = 0;\n @state() private imageFailed = new Set<number>();\n private pointerStart: number | undefined;\n private suppressPointerClick = false;\n protected willUpdate(changed: Map<PropertyKey, unknown>) {\n if (changed.has('interaction')) { this.index = 0; this.imageFailed = new Set(); this.pointerStart = undefined; this.suppressPointerClick = false; }\n }\n render() {\n const i = this.interaction;\n if (!i) return nothing;\n if (!this.valid) return html`<p>${i.content}</p>`;\n const p = i.presentation as CarouselPresentation;\n const chosen = p.items.find(item => item.id === (i.response_payload?.kind === 'selection' ? i.response_payload.value : i.selected_option_id));\n return html`<p class=\"label\">${p.label}</p>${p.description ? html`<p class=\"description\">${p.description}</p>` : nothing}\n ${!this.live ? chosen ? html`<p class=\"answer\">${chosen.title}</p>` : nothing : this.variant === 'list'\n ? html`<div class=\"list\">${p.items.map((item, n) => this.card(item, n))}</div>`\n : html`<div @pointerdown=${(e: PointerEvent) => { this.pointerStart = e.clientX; this.suppressPointerClick = false; }} @pointerup=${(e: PointerEvent) => {\n if (this.pointerStart !== undefined && Math.abs(e.clientX - this.pointerStart) > 40) {\n this.suppressPointerClick = true;\n this.navigate(e.clientX < this.pointerStart ? 1 : -1, p.items.length);\n }\n this.pointerStart = undefined;\n }} @pointercancel=${() => { this.pointerStart = undefined; }}>${this.card(p.items[this.index]!, this.index)}</div>\n <div class=\"navigation\"><button type=\"button\" class=\"round\" aria-label=\"Previous card\" ?disabled=${this.index === 0} @click=${() => this.navigate(-1, p.items.length)}>${leftIcon}</button>\n <span class=\"dots\" aria-hidden=\"true\">${p.items.map((_, n) => html`<i class=${n === this.index ? 'on' : ''}></i>`)}</span><span class=\"sr\" aria-live=\"polite\">${this.index + 1} of ${p.items.length}</span>\n <button type=\"button\" class=\"round\" aria-label=\"Next card\" ?disabled=${this.index === p.items.length - 1} @click=${() => this.navigate(1, p.items.length)}>${rightIcon}</button></div>`}`;\n }\n private navigate(delta: number, length: number) { this.index = Math.max(0, Math.min(length - 1, this.index + delta)); }\n private select(event: MouseEvent, id: string) {\n // Keyboard activation has detail 0; a swipe's synthesized pointer click must not select.\n if (this.suppressPointerClick && event.detail !== 0) {\n this.suppressPointerClick = false;\n event.preventDefault();\n event.stopPropagation();\n return;\n }\n this.respond({ kind: 'selection', value: id });\n }\n private card(item: CarouselItem, index: number) {\n const image = item.image;\n return html`<article class=\"card\">${image && isProxyImageUrl(image.url) ? html`<div class=\"image\">${this.imageFailed.has(index)\n ? html`<span role=\"img\" aria-label=\"Image unavailable\">Image unavailable</span>`\n : html`<img src=${this.baseUrl.replace(/\\/$/, '') + image.url} alt=${image.alt} referrerpolicy=\"no-referrer\" loading=\"lazy\" @error=${() => { this.imageFailed = new Set([...this.imageFailed, index]); }}>`}</div>` : nothing}\n <div class=\"body\"><h3>${item.title}</h3>${item.description ? html`<p>${item.description}</p>` : nothing}\n <button type=\"button\" class=\"primary\" @click=${(e: MouseEvent) => this.select(e, item.id)}>${item.action_label ?? 'Select'}</button></div></article>`;\n }\n}\n","import { html, nothing } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport type { DatePickerPresentation } from '../../core/protocol/types';\nimport { isCalendarDate } from '../../core/protocol/validators';\nimport { toolStyles } from '../styles';\nimport { ToolElement } from './base';\nimport { leftIcon, rightIcon } from '../icons';\nconst toIso = (d: Date) => `${String(d.getFullYear()).padStart(4, '0')}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;\nconst today = () => toIso(new Date());\nconst parseDate = (iso: string) => { const d = new Date(0); d.setHours(0, 0, 0, 0); d.setFullYear(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10))); return d; };\nconst monthOf = (iso: string) => iso.slice(0, 7);\nexport class OsviDatePicker extends ToolElement {\n static styles = toolStyles;\n protected readonly toolType = 'ui_date_picker';\n @property() variant = 'grid';\n @state() private month = monthOf(today());\n @state() private start = '';\n @state() private end = '';\n private earliest(p: DatePickerPresentation) { return p.min_date && p.min_date > today() ? p.min_date : today(); }\n protected willUpdate(changed: Map<PropertyKey, unknown>) {\n if (changed.has('interaction')) {\n this.start = ''; this.end = '';\n if (this.valid) this.month = monthOf(this.earliest(this.interaction!.presentation as DatePickerPresentation));\n }\n }\n render() {\n const i = this.interaction;\n if (!i) return nothing;\n if (!this.valid) return html`<p>${i.content}</p>`;\n const p = i.presentation as DatePickerPresentation;\n const response = i.response_payload;\n const chosen = response?.kind === 'date_range' ? `${response.value.start_date} – ${response.value.end_date}` : response?.kind === 'date' || response?.kind === 'text' ? response.value : i.selected_option_id;\n if (!this.live) return html`<p class=\"label\">${p.label}</p>${p.description ? html`<p class=\"description\">${p.description}</p>` : nothing}${chosen ? html`<p class=\"answer\">${chosen}</p>` : nothing}`;\n const first = parseDate(`${this.month}-01`);\n const last = new Date(first); last.setMonth(last.getMonth() + 1, 0);\n const earliest = this.earliest(p);\n const days = Array.from({ length: last.getDate() }, (_, n) => `${this.month}-${String(n + 1).padStart(2, '0')}`);\n const hint = p.selection_mode === 'range' ? !this.start ? 'Choose check-in, then check-out.' : !this.end ? `Check-in: ${this.start}. Choose check-out.` : `${this.start} – ${this.end}` : this.start;\n const now = today();\n return html`<p class=\"label\">${p.label}</p>${p.description ? html`<p class=\"description\">${p.description}</p>` : nothing}\n <div class=\"calendar\"><div class=\"navigation\"><button type=\"button\" class=\"round\" aria-label=\"Previous month\" ?disabled=${this.month <= monthOf(earliest)} @click=${() => this.moveMonth(-1, p)}>${leftIcon}</button>\n <span aria-live=\"polite\">${first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</span>\n <button type=\"button\" class=\"round\" aria-label=\"Next month\" ?disabled=${!!p.max_date && this.month >= monthOf(p.max_date)} @click=${() => this.moveMonth(1, p)}>${rightIcon}</button></div>\n <div class=\"weekdays\" aria-hidden=\"true\">${['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map(day => html`<span>${day}</span>`)}</div>\n <div class=\"days\" role=\"group\" aria-label=\"Choose date\" @keydown=${this.onKey}>\n ${Array.from({ length: first.getDay() }, () => html`<span></span>`)}\n ${days.map((day, n) => html`<button type=\"button\" class=${[day === now ? 'today' : '', day === this.start ? 'start' : '', day === this.end ? 'end' : '', this.start && this.end && day > this.start && day < this.end ? 'in' : ''].filter(Boolean).join(' ')} aria-label=${day} aria-pressed=${day === this.start || day === this.end} ?disabled=${day < earliest || !!p.max_date && day > p.max_date} @click=${() => this.pick(day, p)}>${n + 1}</button>`)}\n </div><p class=\"hint\" aria-live=\"polite\">${hint}</p>\n <button type=\"button\" class=\"primary\" ?disabled=${!this.start || p.selection_mode === 'range' && (!this.end || this.start >= this.end)} @click=${() => this.confirm(p)}>${p.confirm_label ?? 'Confirm date'}</button></div>`;\n }\n private moveMonth(delta: number, p: DatePickerPresentation) {\n const date = parseDate(`${this.month}-01`); date.setMonth(date.getMonth() + delta);\n const next = monthOf(toIso(date));\n if (next >= monthOf(this.earliest(p)) && (!p.max_date || next <= monthOf(p.max_date))) this.month = next;\n }\n private pick(day: string, p: DatePickerPresentation) {\n if (!this.live || !this.valid || !isCalendarDate(day) || day < this.earliest(p) || p.max_date && day > p.max_date) return;\n if (p.selection_mode === 'single' || !this.start || this.end || day <= this.start) { this.start = day; this.end = ''; }\n else this.end = day;\n }\n private confirm(p: DatePickerPresentation) {\n if (!isCalendarDate(this.start) || this.start < this.earliest(p) || p.max_date && this.start > p.max_date) return;\n if (p.selection_mode === 'single') this.respond({ kind: 'date', value: this.start });\n else if (isCalendarDate(this.end) && this.start < this.end && (!p.max_date || this.end <= p.max_date)) this.respond({ kind: 'date_range', value: { start_date: this.start, end_date: this.end } });\n }\n private onKey(e: KeyboardEvent) {\n const steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };\n const step = steps[e.key]; if (step === undefined) return;\n const buttons = [...this.renderRoot.querySelectorAll<HTMLButtonElement>('.days button')];\n const at = buttons.indexOf((this.renderRoot as ShadowRoot).activeElement as HTMLButtonElement);\n if (at < 0) return;\n let next = at + step;\n while (next >= 0 && next < buttons.length && buttons[next]?.disabled) next += step > 0 ? 1 : -1;\n buttons[next]?.focus(); e.preventDefault();\n }\n}\n","import { OsviChat } from './osvi-chat';\nimport { defineOnce } from './define';\nimport { OsviButtons } from './tools/osvi-buttons';\nimport { OsviCarousel } from './tools/osvi-carousel';\nimport { OsviDatePicker } from './tools/osvi-date-picker';\ndefineOnce('osvi-chat', OsviChat);\ndefineOnce('osvi-buttons', OsviButtons);\ndefineOnce('osvi-carousel', OsviCarousel);\ndefineOnce('osvi-date-picker', OsviDatePicker);\nexport { OsviButtons, OsviCarousel, OsviDatePicker };\nexport { defineOnce } from './define';\nexport { themeVariables, explicitThemeVariables, applyTheme, cssVar, type ChatTheme, type Variants } from './theme';\n\nexport { OsviChat };\nexport { DEFAULT_STRINGS, type ChatStrings } from './strings';\n"],"names":["LIGHT","DARK","RADII","VAR","cssVar","key","themeVariables","theme","colors","out","radius","explicitThemeVariables","full","applied","applyTheme","host","variables","value","DEFAULT_STRINGS","warned","warnOnce","name","message","oneOf","allowed","parseRadius","safeBaseUrl","u","safeAvatar","parseJsonAttr","parsed","URL_RE","count","s","ch","trimUrl","url","c","linkify","text","last","m","start","renderTranscript","state","strings","variants","baseUrl","retry","html","repeat","item","nothing","p","i","live","disabled","stroke","d","cls","svg","newChatIcon","closeIcon","sendIcon","leftIcon","rightIcon","osviLogo","renderComposer","o","e","ta","emptyState","bool","v","_OsviChat","_a","LitElement","client","typed","box","event","own","generation","attr","rawColors","mode","source","action","tool","id","log","avatar","title","el","createChatClient","css","__decorateClass","property","OsviChat","defineOnce","ctor","k","unsafeCSS","toolStyles","ToolElement","isInteractionPresentation","response","changed","_OsviButtons","chosen","allowInput","placeholder","list","at","step","OsviButtons","_OsviCarousel","_","delta","length","index","image","isProxyImageUrl","OsviCarousel","toIso","today","parseDate","iso","monthOf","_OsviDatePicker","first","earliest","days","n","hint","now","day","date","next","isCalendarDate","buttons","OsviDatePicker"],"mappings":";;;;;AAMA,MAAMA,IAAQ,EAAE,SAAS,WAAW,YAAY,WAAW,SAAS,WAAW,MAAM,WAAW,YAAY,WAAW,iBAAiB,UAAA,GAClIC,KAAO,EAAE,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A;AAAA,EAC5B;AACF;AA/DE4D,EAAO,SAAS1B;AADX,IAAMsC,IAANZ;AAGOjC,EAAA;AAAA,EAAXC,EAAA;AAAS,GAHC4C,EAGC,WAAA,SAAA;AACK7C,EAAA;AAAA,EAAhBpD,EAAA;AAAM,GAJIiG,EAIM,WAAA,OAAA;AACA7C,EAAA;AAAA,EAAhBpD,EAAA;AAAM,GALIiG,EAKM,WAAA,OAAA;AACA7C,EAAA;AAAA,EAAhBpD,EAAA;AAAM,GANIiG,EAMM,WAAA,KAAA;ACZnB1C,EAAW,aAAaD,EAAQ;AAChCC,EAAW,gBAAgBgB,CAAW;AACtChB,EAAW,iBAAiBwB,CAAY;AACxCxB,EAAW,oBAAoB0C,CAAc;"}
package/dist/widget.js ADDED
@@ -0,0 +1,132 @@
1
+ (function(){"use strict";var j;const Ct=globalThis,Vt=Ct.ShadowRoot&&(Ct.ShadyCSS===void 0||Ct.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Wt=Symbol(),ve=new WeakMap;let _e=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Wt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(Vt&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=ve.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&ve.set(e,t))}return t}toString(){return this.cssText}};const we=s=>new _e(typeof s=="string"?s:s+"",void 0,Wt),Gt=(s,...t)=>{const e=s.length===1?s[0]:t.reduce((i,n,r)=>i+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+s[r+1],s[0]);return new _e(e,s,Wt)},Si=(s,t)=>{if(Vt)s.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),n=Ct.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},$e=Vt?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return we(e)})(s):s;const{is:Ai,defineProperty:Ci,getOwnPropertyDescriptor:Ii,getOwnPropertyNames:Ei,getOwnPropertySymbols:Ti,getPrototypeOf:Pi}=Object,H=globalThis,xe=H.trustedTypes,Oi=xe?xe.emptyScript:"",Ri=H.reactiveElementPolyfillSupport,ht=(s,t)=>s,It={toAttribute(s,t){switch(t){case Boolean:s=s?Oi:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s)}return s},fromAttribute(s,t){let e=s;switch(t){case Boolean:e=s!==null;break;case Number:e=s===null?null:Number(s);break;case Object:case Array:try{e=JSON.parse(s)}catch{e=null}}return e}},Kt=(s,t)=>!Ai(s,t),ke={attribute:!0,type:String,converter:It,reflect:!1,useDefault:!1,hasChanged:Kt};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),H.litPropertyMetadata??(H.litPropertyMetadata=new WeakMap);let rt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=ke){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(t,i,e);n!==void 0&&Ci(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){const{get:n,set:r}=Ii(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:n,set(o){const a=n?.call(this);r?.call(this,o),this.requestUpdate(t,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ke}static _$Ei(){if(this.hasOwnProperty(ht("elementProperties")))return;const t=Pi(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ht("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ht("properties"))){const e=this.properties,i=[...Ei(e),...Ti(e)];for(const n of i)this.createProperty(n,e[n])}const t=this[Symbol.metadata];if(t!==null){const e=litPropertyMetadata.get(t);if(e!==void 0)for(const[i,n]of e)this.elementProperties.set(i,n)}this._$Eh=new Map;for(const[e,i]of this.elementProperties){const n=this._$Eu(e,i);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const n of i)e.unshift($e(n))}else t!==void 0&&e.push($e(t));return e}static _$Eu(t,e){const i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Si(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$ET(t,e){const i=this.constructor.elementProperties.get(t),n=this.constructor._$Eu(t,i);if(n!==void 0&&i.reflect===!0){const r=(i.converter?.toAttribute!==void 0?i.converter:It).toAttribute(e,i.type);this._$Em=t,r==null?this.removeAttribute(n):this.setAttribute(n,r),this._$Em=null}}_$AK(t,e){const i=this.constructor,n=i._$Eh.get(t);if(n!==void 0&&this._$Em!==n){const r=i.getPropertyOptions(n),o=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:It;this._$Em=n;const a=o.fromAttribute(e,r.type);this[n]=a??this._$Ej?.get(n)??a,this._$Em=null}}requestUpdate(t,e,i,n=!1,r){if(t!==void 0){const o=this.constructor;if(n===!1&&(r=this[t]),i??(i=o.getPropertyOptions(t)),!((i.hasChanged??Kt)(r,e)||i.useDefault&&i.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,i))))return;this.C(t,e,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:i,reflect:n,wrapped:r},o){i&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),r!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),n===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,r]of this._$Ep)this[n]=r;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[n,r]of i){const{wrapped:o}=r,a=this[n];o!==!0||this._$AL.has(n)||a===void 0||this.C(n,void 0,r,a)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(i=>i.hostUpdate?.()),this.update(e)):this._$EM()}catch(i){throw t=!1,this._$EM(),i}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach(e=>this._$ET(e,this[e]))),this._$EM()}updated(t){}firstUpdated(t){}};rt.elementStyles=[],rt.shadowRootOptions={mode:"open"},rt[ht("elementProperties")]=new Map,rt[ht("finalized")]=new Map,Ri?.({ReactiveElement:rt}),(H.reactiveElementVersions??(H.reactiveElementVersions=[])).push("2.1.2");const ut=globalThis,Se=s=>s,Et=ut.trustedTypes,Ae=Et?Et.createPolicy("lit-html",{createHTML:s=>s}):void 0,Ce="$lit$",z=`lit$${Math.random().toFixed(9).slice(2)}$`,Ie="?"+z,Mi=`<${Ie}>`,Y=document,pt=()=>Y.createComment(""),ft=s=>s===null||typeof s!="object"&&typeof s!="function",Yt=Array.isArray,Ui=s=>Yt(s)||typeof s?.[Symbol.iterator]=="function",Jt=`[
2
+ \f\r]`,gt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ee=/-->/g,Te=/>/g,J=RegExp(`>|${Jt}(?:([^\\s"'>=/]+)(${Jt}*=${Jt}*(?:[^
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Pe=/'/g,Oe=/"/g,Re=/^(?:script|style|textarea|title)$/i,Me=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),p=Me(1),R=Me(2),E=Symbol.for("lit-noChange"),m=Symbol.for("lit-nothing"),Ue=new WeakMap,X=Y.createTreeWalker(Y,129);function Ne(s,t){if(!Yt(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ae!==void 0?Ae.createHTML(t):t}const Ni=(s,t)=>{const e=s.length-1,i=[];let n,r=t===2?"<svg>":t===3?"<math>":"",o=gt;for(let a=0;a<e;a++){const c=s[a];let l,f,d=-1,h=0;for(;h<c.length&&(o.lastIndex=h,f=o.exec(c),f!==null);)h=o.lastIndex,o===gt?f[1]==="!--"?o=Ee:f[1]!==void 0?o=Te:f[2]!==void 0?(Re.test(f[2])&&(n=RegExp("</"+f[2],"g")),o=J):f[3]!==void 0&&(o=J):o===J?f[0]===">"?(o=n??gt,d=-1):f[1]===void 0?d=-2:(d=o.lastIndex-f[2].length,l=f[1],o=f[3]===void 0?J:f[3]==='"'?Oe:Pe):o===Oe||o===Pe?o=J:o===Ee||o===Te?o=gt:(o=J,n=void 0);const u=o===J&&s[a+1].startsWith("/>")?" ":"";r+=o===gt?c+Mi:d>=0?(i.push(l),c.slice(0,d)+Ce+c.slice(d)+z+u):c+z+(d===-2?a:u)}return[Ne(s,r+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};class mt{constructor({strings:t,_$litType$:e},i){let n;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[l,f]=Ni(t,e);if(this.el=mt.createElement(l,i),X.currentNode=this.el.content,e===2||e===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(n=X.nextNode())!==null&&c.length<a;){if(n.nodeType===1){if(n.hasAttributes())for(const d of n.getAttributeNames())if(d.endsWith(Ce)){const h=f[o++],u=n.getAttribute(d).split(z),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:u,ctor:g[1]==="."?Bi:g[1]==="?"?Li:g[1]==="@"?ji:Tt}),n.removeAttribute(d)}else d.startsWith(z)&&(c.push({type:6,index:r}),n.removeAttribute(d));if(Re.test(n.tagName)){const d=n.textContent.split(z),h=d.length-1;if(h>0){n.textContent=Et?Et.emptyScript:"";for(let u=0;u<h;u++)n.append(d[u],pt()),X.nextNode(),c.push({type:2,index:++r});n.append(d[h],pt())}}}else if(n.nodeType===8)if(n.data===Ie)c.push({type:2,index:r});else{let d=-1;for(;(d=n.data.indexOf(z,d+1))!==-1;)c.push({type:7,index:r}),d+=z.length-1}r++}}static createElement(t,e){const i=Y.createElement("template");return i.innerHTML=t,i}}function ot(s,t,e=s,i){if(t===E)return t;let n=i!==void 0?e._$Co?.[i]:e._$Cl;const r=ft(t)?void 0:t._$litDirective$;return n?.constructor!==r&&(n?._$AO?.(!1),r===void 0?n=void 0:(n=new r(s),n._$AT(s,e,i)),i!==void 0?(e._$Co??(e._$Co=[]))[i]=n:e._$Cl=n),n!==void 0&&(t=ot(s,n._$AS(s,t.values),n,i)),t}class Di{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:e},parts:i}=this._$AD,n=(t?.creationScope??Y).importNode(e,!0);X.currentNode=n;let r=X.nextNode(),o=0,a=0,c=i[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new at(r,r.nextSibling,this,t):c.type===1?l=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(l=new Hi(r,this,t)),this._$AV.push(l),c=i[++a]}o!==c?.index&&(r=X.nextNode(),o++)}return X.currentNode=Y,n}p(t){let e=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}}class at{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,i,n){this.type=2,this._$AH=m,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=ot(this,t,e),ft(t)?t===m||t==null||t===""?(this._$AH!==m&&this._$AR(),this._$AH=m):t!==this._$AH&&t!==E&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ui(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==m&&ft(this._$AH)?this._$AA.nextSibling.data=t:this.T(Y.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:i}=t,n=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=mt.createElement(Ne(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(e);else{const r=new Di(n,this),o=r.u(this.options);r.p(e),this.T(o),this._$AH=r}}_$AC(t){let e=Ue.get(t.strings);return e===void 0&&Ue.set(t.strings,e=new mt(t)),e}k(t){Yt(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,n=0;for(const r of t)n===e.length?e.push(i=new at(this.O(pt()),this.O(pt()),this,this.options)):i=e[n],i._$AI(r),n++;n<e.length&&(this._$AR(i&&i._$AB.nextSibling,n),e.length=n)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){const i=Se(t).nextSibling;Se(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}class Tt{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,n,r){this.type=1,this._$AH=m,this._$AN=void 0,this.element=t,this.name=e,this._$AM=n,this.options=r,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=m}_$AI(t,e=this,i,n){const r=this.strings;let o=!1;if(r===void 0)t=ot(this,t,e,0),o=!ft(t)||t!==this._$AH&&t!==E,o&&(this._$AH=t);else{const a=t;let c,l;for(t=r[0],c=0;c<r.length-1;c++)l=ot(this,a[i+c],e,c),l===E&&(l=this._$AH[c]),o||(o=!ft(l)||l!==this._$AH[c]),l===m?t=m:t!==m&&(t+=(l??"")+r[c+1]),this._$AH[c]=l}o&&!n&&this.j(t)}j(t){t===m?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class Bi extends Tt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===m?void 0:t}}class Li extends Tt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==m)}}class ji extends Tt{constructor(t,e,i,n,r){super(t,e,i,n,r),this.type=5}_$AI(t,e=this){if((t=ot(this,t,e,0)??m)===E)return;const i=this._$AH,n=t===m&&i!==m||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,r=t!==m&&(i===m||n);n&&this.element.removeEventListener(this.name,this,i),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}}class Hi{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){ot(this,t)}}const zi={I:at},Fi=ut.litHtmlPolyfillSupport;Fi?.(mt,at),(ut.litHtmlVersions??(ut.litHtmlVersions=[])).push("3.3.3");const qi=(s,t,e)=>{const i=e?.renderBefore??t;let n=i._$litPart$;if(n===void 0){const r=e?.renderBefore??null;i._$litPart$=n=new at(t.insertBefore(pt(),r),r,void 0,e??{})}return n._$AI(s),n};const bt=globalThis;let Z=class extends rt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=qi(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return E}};Z._$litElement$=!0,Z.finalized=!0,bt.litElementHydrateSupport?.({LitElement:Z});const Vi=bt.litElementPolyfillSupport;Vi?.({LitElement:Z}),(bt.litElementVersions??(bt.litElementVersions=[])).push("4.2.2");const Wi={attribute:!0,type:String,converter:It,reflect:!1,hasChanged:Kt},Gi=(s=Wi,t,e)=>{const{kind:i,metadata:n}=e;let r=globalThis.litPropertyMetadata.get(n);if(r===void 0&&globalThis.litPropertyMetadata.set(n,r=new Map),i==="setter"&&((s=Object.create(s)).wrapped=!0),r.set(e.name,s),i==="accessor"){const{name:o}=e;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(o,c,s,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,s,a),a}}}if(i==="setter"){const{name:o}=e;return function(a){const c=this[o];t.call(this,a),this.requestUpdate(o,c,s,!0,a)}}throw Error("Unsupported decorator location: "+i)};function b(s){return(t,e)=>typeof e=="object"?Gi(s,t,e):((i,n,r)=>{const o=n.hasOwnProperty(r);return n.constructor.createProperty(r,i),o?Object.getOwnPropertyDescriptor(n,r):void 0})(s,t,e)}function N(s){return b({...s,state:!0,attribute:!1})}const Ki="0.1.1",Yi=new Set(["origin_not_allowed","agent_inactive","agent_archived","agent_not_found","session_not_found","session_closed","invalid_customer_id","invalid_token","session_unavailable","stream_unavailable","token_failed","rate_limited","network","interaction_not_pending","interaction_suspended","invalid_interaction","unknown"]),Ji=new Set(["rate_limited","network","session_unavailable","stream_unavailable","token_failed"]);function k(s,t){const e=s&&Yi.has(s)?s:"unknown";return{code:e,message:t||e,retryable:Ji.has(e)}}class A extends Error{constructor(t,e){super(t.message),this.error=t,this.status=e,this.name="ChatRequestError"}}const Xi=3e5;function De(s,t=Date.now()){return typeof s!="number"||!Number.isFinite(s)?t+Xi:s<1e12?s*1e3:s}class Be{constructor(t,e=(...i)=>globalThis.fetch.bind(globalThis)(...i)){this.fetchImpl=e,this.base=t.replace(/\/+$/,"")}resolveUrl(t){return`${this.base}${t}`}bootstrap(t,e,i){const n=`?customer_id=${encodeURIComponent(e)}`;return this.request(`/public/chat/agents/${encodeURIComponent(t)}/bootstrap${n}`,{signal:i})}createSession(t,e){return this.request(`/public/chat/agents/${encodeURIComponent(t)}/session`,{method:"POST",body:JSON.stringify({customer_id:e})})}async mintPublicToken(t){const e=await this.request(`/public/chat/session/${encodeURIComponent(t)}/ws_token`,{method:"POST",body:"{}"});if(!e?.token||!e?.ws_url)throw new A(k("stream_unavailable"),200);return{token:e.token,wsUrl:e.ws_url,expiresAt:De(e.expires_at)}}snapshot(t,e){return this.request(`/public/chat/session/${encodeURIComponent(t)}/snapshot`,{headers:{Authorization:`Bearer ${e}`}})}async request(t,e={}){let i;try{const r=this.fetchImpl,o={...e.headers};e.body!==void 0&&(o["Content-Type"]="application/json"),i=await r(this.resolveUrl(t),{...e,credentials:"omit",headers:o})}catch(r){throw r?.name==="AbortError"?r:new A(k("network","Network error"),0)}let n=null;try{n=await i.json()}catch{n=null}if(!i.ok||n?.success===!1){const r=k(typeof n?.error=="string"?n.error:void 0,typeof n?.message=="string"?n.message:void 0);if(typeof n?.origin=="string"&&(r.origin=n.origin),i.status===429){r.code="rate_limited",r.retryable=!0;const o=Number(i.headers.get("Retry-After")),a=Number(n?.retry_after),c=Number.isFinite(o)&&o>0?o:a;Number.isFinite(c)&&c>0&&(r.retryAfterSeconds=c)}throw new A(r,i.status)}return n?.data??n}}const Xt=[{tool_type:"ui_buttons",schema_version:1},{tool_type:"ui_buttons",schema_version:2},{tool_type:"ui_carousel",schema_version:1},{tool_type:"ui_date_picker",schema_version:1}],Zi=65536,Qi=2e3,ts=8192,Le=2048,Zt=/^[A-Za-z0-9_-]{1,64}$/,D=s=>!!s&&typeof s=="object"&&!Array.isArray(s),F=(s,t)=>Object.keys(s).every(e=>t.includes(e)),es=s=>[...s].length,je=s=>new TextEncoder().encode(s).length,is=s=>[...s].some(t=>{const e=t.codePointAt(0)??0;return e===127||e<32&&e!==9&&e!==10&&e!==13}),ss=s=>[...s].some(t=>{const e=t.codePointAt(0)??0;return e<=32||e===127}),S=(s,t,e=!1)=>typeof s=="string"&&es(s)<=t&&!is(s)&&(!e||s.trim().length>0),Qt=s=>Array.isArray(s)?s.map(Qt):D(s)?Object.fromEntries(Object.keys(s).sort().map(t=>[t,Qt(s[t])])):s,te=s=>{try{return je(JSON.stringify(Qt(s)))<=Zi}catch{return!1}};function He(s){return typeof s=="string"&&/^\/public\/chat\/images\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/(?:0|[1-9][0-9]*)$/i.test(s)}function ns(s){if(typeof s!="string"||s.length===0||s.length>Le||ss(s))return!1;try{const t=new URL(s),e=t.hostname.toLowerCase();return t.protocol!=="https:"||t.username||t.password||t.hash||t.port||!e||e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".internal")||e.startsWith("[")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)?!1:t.toString().length<=Le}catch{return!1}}function Pt(s,t){if(!D(s)||!F(s,["label","description","options"])||!S(s.label,160,!0)||"description"in s&&s.description!==void 0&&!S(s.description,240)||!Array.isArray(s.options)||s.options.length===0||t!==void 0)return!1;const e=new Set;let i=0;for(const n of s.options){if(!D(n)||!F(n,["id","label","description","allow_input","input_placeholder"])||typeof n.id!="string"||!Zt.test(n.id)||e.has(n.id)||!S(n.label,80,!0)||"description"in n&&n.description!==void 0&&!S(n.description,240))return!1;const r=n.allow_input===!0;if("allow_input"in n&&!r||"input_placeholder"in n&&(!r||!S(n.input_placeholder,160,!0))||(r&&(i+=1),i>1))return!1;e.add(n.id)}return te(s)}function ze(s,t){return Pt(s,t)&&s.options.every(e=>!Object.prototype.hasOwnProperty.call(e,"allow_input")&&!Object.prototype.hasOwnProperty.call(e,"input_placeholder"))}function Fe(s,t,e=!1){if(!D(s)||!F(s,["label","description","items"])||!S(s.label,160,!0)||"description"in s&&s.description!==void 0&&!S(s.description,240)||!Array.isArray(s.items)||s.items.length===0||t!==void 0)return!1;const i=new Set;for(const n of s.items){if(!D(n)||!F(n,["id","title","description","image","action_label"])||typeof n.id!="string"||!Zt.test(n.id)||i.has(n.id)||!S(n.title,120,!0)||"description"in n&&n.description!==void 0&&!S(n.description,500)||"action_label"in n&&n.action_label!==void 0&&!S(n.action_label,80,!0)||"image"in n&&n.image!==void 0&&(!D(n.image)||!F(n.image,["url","alt"])||!(ns(n.image.url)||e&&He(n.image.url))||!S(n.image.alt,240,!0)))return!1;i.add(n.id)}return te(s)}function q(s){if(typeof s!="string"||!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(s))return!1;const t=Number(s.slice(0,4)),e=Number(s.slice(5,7)),i=Number(s.slice(8,10));if(t<1||t>9999||e<1||e>12||i<1)return!1;const r=[31,t%4===0&&(t%100!==0||t%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return i<=r[e-1]}function ee(s){return!D(s)||!F(s,["label","description","min_date","max_date","confirm_label","selection_mode"])||!S(s.label,160,!0)||!["single","range"].includes(String(s.selection_mode))||"description"in s&&s.description!==void 0&&!S(s.description,240)||"confirm_label"in s&&s.confirm_label!==void 0&&!S(s.confirm_label,80,!0)||"min_date"in s&&s.min_date!==void 0&&!q(s.min_date)||"max_date"in s&&s.max_date!==void 0&&!q(s.max_date)||typeof s.min_date=="string"&&typeof s.max_date=="string"&&s.min_date>s.max_date?!1:te(s)}function rs(s,t){return s.tool_type==="ui_buttons"&&s.schema_version===1?ze(t):s.tool_type==="ui_buttons"&&s.schema_version===2?Pt(t):s.tool_type==="ui_carousel"&&s.schema_version===1?Fe(t,void 0,!0):s.tool_type==="ui_date_picker"&&s.schema_version===1?ee(t):!1}function qe(s,t){return!D(t)||!F(t,["kind","value"])||Object.keys(t).length!==2?!1:t.kind==="date_range"?s.tool_type==="ui_date_picker"&&s.schema_version===1&&D(t.value)&&F(t.value,["start_date","end_date"])&&Object.keys(t.value).length===2&&q(t.value.start_date)&&q(t.value.end_date)&&t.value.start_date<t.value.end_date:typeof t.value!="string"?!1:t.kind==="selection"?(s.tool_type==="ui_buttons"||s.tool_type==="ui_carousel")&&Zt.test(t.value):t.kind==="text"?s.tool_type==="ui_buttons"&&s.schema_version===2&&t.value===t.value.trim()&&S(t.value,Qi,!0)&&je(t.value)<=ts:t.kind==="date"?s.tool_type==="ui_date_picker"&&s.schema_version===1&&q(t.value):!1}const ie=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),os=new Set(["preparing","pending","accepted","resumed","cancelled","expired"]);function ct(s){if(!ie(s)||s.type!=="interaction"||typeof s.id!="string"||!s.id||s.role!=="assistant"||typeof s.content!="string"||typeof s.interaction_id!="string"||!s.interaction_id||typeof s.tool_type!="string"||!Number.isSafeInteger(s.schema_version)||Number(s.schema_version)<1||!Number.isSafeInteger(s.interaction_revision)||Number(s.interaction_revision)<1||!os.has(String(s.interaction_status))||!ie(s.presentation))return null;const t={tool_type:s.tool_type,schema_version:Number(s.schema_version)},e=s.response_payload;return e!=null&&!qe(t,e)?null:{id:s.id,type:"interaction",role:"assistant",content:s.content,interaction_id:s.interaction_id,tool_type:s.tool_type,schema_version:Number(s.schema_version),presentation:s.presentation,interaction_status:s.interaction_status,interaction_revision:Number(s.interaction_revision),...typeof s.created_at=="string"?{created_at:s.created_at}:{},...typeof s.selected_option_id=="string"?{selected_option_id:s.selected_option_id}:{},...e!==void 0?{response_payload:e}:{}}}function B(s){if(!ie(s)||typeof s.id!="string"&&typeof s.id!="number"||typeof s.content!="string"||!["assistant","user","operator","system"].includes(String(s.role)))return null;const t=ct({...s,id:String(s.id)});return{id:String(s.id),content:s.content,type:s.type==="interaction"?"interaction":"message",ts:typeof s.created_at=="string"?s.created_at:typeof s.ts=="string"?s.ts:new Date().toISOString(),...t??{},role:s.role}}function T(s){return typeof s=="string"&&/^\d+$/.test(s)?s.replace(/^0+(?=\d)/,""):null}function P(s,t){return s.length===t.length?s===t?0:s>t?1:-1:s.length>t.length?1:-1}function se(s,t){const e=[...s];for(const i of t){const n=e.findIndex(r=>r.id===i.id||i.interaction_id&&r.interaction_id===i.interaction_id);if(n<0)e.push(i);else{const r=e[n],o=c=>c.interaction_status==="preparing"?0:c.interaction_status==="pending"?1:c.interaction_status==="accepted"?2:3;!(i.interaction_revision===r.interaction_revision&&o(i)<o(r))&&(!i.interaction_revision||!r.interaction_revision||i.interaction_revision>=r.interaction_revision)&&(e[n]={...r,...i})}}return e}const as=new Set(["user","ai","assistant","operator","support","system"]);function ne(s){if(!s||typeof s!="object")return null;const t=s,e=typeof t.id=="number"?String(t.id):t.id;if(typeof e!="string"||e===""||typeof t.content!="string"||typeof t.role!="string"||!as.has(t.role))return null;const i={id:e,role:t.role,content:t.content};return typeof t.created_at=="string"&&(i.created_at=t.created_at),(t.type==="interaction"||t.type==="message")&&(i.type=t.type),i}const yt=s=>["pending","accepted"].includes(s.interaction_status);class cs{constructor(t){this.host=t,this._active=null,this._cursor="0",this._pending=!1,this._error=null,this.operations=new Map,this.operation=null,this.generation=0,this.refreshInFlight=!1,this.recoveryCursor=null}get active(){return this._active}get cursor(){return this._cursor}get pending(){return this._pending}get error(){return this._error}setActive(t){this._active=t,this.host.onChange()}setCursor(t){this._cursor=t,this.host.onChange()}setSelectionPending(t){this._pending=t,this.host.onChange()}setInteractionError(t){this._error=t,this.host.onChange()}setRows(t){this.host.updateItems(e=>{let i=e.length;for(;i>0&&e[i-1].kind!=="divider";)i-=1;const n=e.slice(i);return[...e.slice(0,i),...ds(t(ls(n)),n)]})}reset(){this.generation+=1,this.refreshInFlight=!1,this.recoveryCursor=null,this.setActive(null),this._cursor="0",this.setCursor("0"),this.operations.clear(),this.operation=null,this.setSelectionPending(!1),this.setInteractionError(null)}reject(t,e){this.operations.delete(t.interactionId),this.operations.size===0&&(this.recoveryCursor=null),this.operation===t&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(e);const i=this._active,n=i?.interaction_id===t.interactionId&&i.interaction_revision<=t.original.interaction_revision;n&&this.setActive(t.original),this.setRows(r=>r.filter(o=>o.id!==t.messageId).map(o=>n&&o.interaction_id===t.interactionId?B(t.original):o))}mergeProjection(t,e){const i=B(e),n=t&&this.operations.get(t.interaction_id);n&&i?.role==="user"&&(this.operations.delete(n.interactionId),this.operations.size===0&&(this.recoveryCursor=null),this.operation===n&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(null));const r=[t&&B(t),i?.role==="user"?i:null].filter(o=>o!==null);this.setRows(o=>{const a=n&&i?.role==="user"&&o.some(c=>c.id===n.messageId)?o.flatMap(c=>c.id===n.messageId?[i]:c.id===i.id?[]:[c]):o;return se(a,r)})}refreshMissingOutcome(t){if(this.operations.size===0){this.recoveryCursor=null;return}if((this.recoveryCursor===null||P(t,this.recoveryCursor)>0)&&(this.recoveryCursor=t),this.refreshInFlight)return;const e=this.recoveryCursor,i=[...this.operations.values()],n=a=>this.operations.get(a.interactionId)===a,r=this.generation,o=this.host.sessionId();this.refreshInFlight=!0,this.setSelectionPending(!0),this.host.refreshSnapshot().then(a=>{if(!a)throw new Error("Snapshot unavailable");if(r!==this.generation||o!==this.host.sessionId()||a.session!==null&&a.session.id!==o||!i.some(n))return;const c=T(a.interaction_cursor);if(c===null||P(c,this.recoveryCursor??e)<0||P(c,this._cursor)<0)return;const l=a.active_interaction===null?null:ct(a.active_interaction);if(a.active_interaction!==null&&(!l||!yt(l)))return;const f=a.messages.map(B).filter(g=>g!==null),d=B(a.interaction_response_message);l&&f.push(B(l)),d?.role==="user"&&f.push(d);const h=i.filter(g=>n(g)&&(l?.interaction_id!==g.interactionId||l.interaction_status==="accepted"&&d?.role==="user")),u=new Set(h.map(g=>g.messageId));this.setRows(g=>se(g.filter(x=>!u.has(x.id)),f).sort((x,G)=>Date.parse(x.ts)-Date.parse(G.ts)||0)),h.forEach(g=>this.operations.delete(g.interactionId)),this.operation&&h.includes(this.operation)&&(this.operation=null),this._cursor=c,this.recoveryCursor=null,this.setCursor(c),this.setActive(l),this.setSelectionPending(this.operation!==null),this.setInteractionError(null)}).catch(()=>{r===this.generation&&i.some(n)&&this.setInteractionError({code:"network",message:"Reconnecting to confirm your selection…"})}).finally(()=>{if(r===this.generation){if(this.refreshInFlight=!1,this.operations.size===0){this.recoveryCursor=null;return}const a=this.recoveryCursor;a!==null&&P(a,e)>0&&this.refreshMissingOutcome(a)}})}hasMissingOutcome(t){return[...this.operations.values()].some(e=>!t||e.interactionId!==t.interaction_id)}applySnapshot(t){const e=T(t.interaction_cursor);if(e===null||!Object.prototype.hasOwnProperty.call(t,"active_interaction"))return;const i=P(e,this._cursor);if(i<0)return;const n=t.active_interaction===null?null:ct(t.active_interaction);if(!(t.active_interaction!==null&&(!n||!yt(n)))){if(i>0&&this.hasMissingOutcome(n)){this.refreshMissingOutcome(e);return}i===0&&(this.operation||n&&this.operations.has(n.interaction_id)||n===null&&this._active)||(this._cursor=e,this.setCursor(e),this.setActive(n),this.mergeProjection(n,t.interaction_response_message),(!n||this.operation?.interactionId!==n.interaction_id)&&(this.operation=null,this.setSelectionPending(!1)))}}applyEvent(t){if(!["interaction_published","interaction_updated","interaction_closed"].includes(t.type))return!1;if(t.session_id&&t.session_id!==this.host.sessionId())return!0;const e=T(t.payload.interaction_cursor),i=ct(t.payload);return!i||i.interaction_status==="preparing"||e===null||P(e,this._cursor)<=0?!0:this.hasMissingOutcome(i)||!yt(i)&&this.operations.has(i.interaction_id)&&!B(t.payload.interaction_response_message)?(this.refreshMissingOutcome(e),!0):(this._cursor=e,this.setCursor(e),this.mergeProjection(i,t.payload.interaction_response_message),yt(i)?this.setActive(i):this._active?.interaction_id===i.interaction_id&&this.setActive(null),this.operation&&(this.operation.interactionId!==i.interaction_id||!yt(i))&&(this.operation=null,this.setSelectionPending(!1)),!0)}handleWriteResult(t){const e=t,i=[...this.operations.values()].find(n=>n.messageId===e.message_id);if(!i)return!1;if(e.error||["refused","failed","error","busy"].includes(String(e.state))){const n=["interaction_not_pending","interaction_suspended","invalid_interaction","network"].includes(String(e.error))?e.error:"invalid_interaction";this.reject(i,{code:n,message:String(e.error||e.reason||"The selection was not accepted. Please try again.")})}else i.acknowledged=!0,this.operation===i&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(null);return!0}respond(t,e){const i=this._active;if(!this.host.sessionId()||this.host.humanConnected()||this.operation||!i||i.interaction_id!==t||i.interaction_status!=="pending"||!Xt.some(l=>l.tool_type===i.tool_type&&l.schema_version===i.schema_version)||!qe(i,e))return!1;const n=i.tool_type==="ui_buttons"&&i.schema_version===1;let r=null;if(n&&e.kind==="selection"&&ze(i.presentation))r=i.presentation.options.find(l=>l.id===e.value)?.label??null;else if(!n&&e.kind==="text"&&i.tool_type==="ui_buttons"&&Pt(i.presentation))r=e.value;else if(!n&&e.kind==="selection"&&i.tool_type==="ui_buttons"&&Pt(i.presentation))r=i.presentation.options.find(l=>l.id===e.value)?.label??null;else if(e.kind==="selection"&&i.tool_type==="ui_carousel"&&Fe(i.presentation,void 0,!0))r=i.presentation.items.find(l=>l.id===e.value)?.title??null;else if(e.kind==="date"&&i.tool_type==="ui_date_picker"&&i.schema_version===1&&ee(i.presentation)&&i.presentation.selection_mode==="single")(!i.presentation.min_date||e.value>=i.presentation.min_date)&&(!i.presentation.max_date||e.value<=i.presentation.max_date)&&(r=e.value);else if(e.kind==="date_range"&&i.tool_type==="ui_date_picker"&&i.schema_version===1&&ee(i.presentation)&&i.presentation.selection_mode==="range"){const{start_date:l,end_date:f}=e.value;(!i.presentation.min_date||l>=i.presentation.min_date)&&(!i.presentation.max_date||f<=i.presentation.max_date)&&(r=`${l} to ${f}`)}if(!r)return!1;const o=this.host.newId(),a={interactionId:t,messageId:o,original:i,acknowledged:!1,sent:!1,frame:{type:"interaction_response",interaction_id:t,...n?{option_id:e.value}:{response:e},message_id:o,idempotency_key:this.host.newId(),supported_interactions:Xt}};this.operations.set(t,a),this.operation=a,this.setSelectionPending(!0),this.setInteractionError(null);const c={...i,interaction_status:"accepted",...n?{selected_option_id:e.value}:{response_payload:e}};return this.setActive(c),this.setRows(l=>se(l,[B(c),{id:o,type:"message",role:"user",content:r,ts:new Date().toISOString(),local:!0}])),a.sent=this.host.sendFrame(a.frame),!0}onConnectionOpen(){const t=this.operation;t&&!t.acknowledged&&!this.host.humanConnected()&&(t.sent=this.host.sendFrame(t.frame))}}function ls(s){const t=[];for(const e of s)e.kind==="interaction"?t.push(B(e.interaction)):e.kind==="message"&&t.push({id:e.serverId??e.id,type:"message",role:e.role==="human"?"operator":e.role,content:e.content,ts:e.createdAt});return t}function ds(s,t){const e=new Map;for(const n of t)n.kind==="message"&&(e.set(n.id,n),n.serverId&&e.set(n.serverId,n));const i=[];for(const n of s){if(n.type==="interaction"&&n.interaction_id){const o=ct(n);o&&i.push({kind:"interaction",id:n.interaction_id,interaction:o});continue}if(n.role==="system")continue;const r=e.get(n.id);if(r){i.push(r.content===n.content?r:{...r,content:n.content});continue}if(n.local){i.push({kind:"message",id:n.id,role:"user",content:n.content,createdAt:n.ts,status:"sending"});continue}i.push({kind:"message",id:`srv:${n.id}`,serverId:n.id,role:n.role==="operator"?"human":n.role,content:n.content,createdAt:n.ts,status:"sent"})}return i}function hs(s){let t=s;if(typeof s=="string")try{t=JSON.parse(s)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const e=t;if(typeof e.type!="string")return null;const i=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{};return{...e,type:e.type,payload:i}}const us=25e3,ps=6e4,fs=3e4,Ve=6e4,vt=[1e3,2e3,4e3,8e3,16e3,3e4],re=1e4,gs=4e3,ms=2,We=new Set(["invalid_token","session_not_found","session_closed","origin_not_allowed","agent_archived","agent_not_found"]);function Ge(){return{isVisible:()=>typeof document>"u"||document.visibilityState!=="hidden",onVisible:s=>{const t=()=>{document.visibilityState!=="hidden"&&s()};return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))},onOnline:s=>typeof window>"u"?()=>{}:(window.addEventListener("online",s),()=>window.removeEventListener("online",s))}}function _t(s){s&&(s.onopen=null,s.onmessage=null,s.onclose=null,s.onerror=null)}class bs{constructor(t){this.opts=t,this.socket=null,this.next=null,this.stopped=!1,this.started=!1,this.everOpened=!1,this.failures=0,this.authCloses=0,this.epoch=0,this.rotating=!1,this.pingSupported=!0,this.lastInbound=0,this.lastPingSentAt=0,this.expiresAt=0,this.timers=new Set,this.pingTimer=null,this.waitingForPage=new Set,this.page=t.page??Ge(),this.WS=t.WebSocketImpl??WebSocket,this.random=t.random??Math.random}get isOpen(){return!this.stopped&&this.socket?.readyState===1}start(){this.started||this.stopped||(this.started=!0,this.opts.onStatus("connecting"),this.connect())}send(t){return this.isOpen?(this.socket.send(JSON.stringify(t)),!0):!1}stop(){this.stopped=!0,this.epoch+=1,this.clearTimers(),this.stopPings(),this.waitingForPage.forEach(t=>t()),this.waitingForPage.clear(),this.abandon(this.next),this.next=null,this.abandon(this.socket),this.socket=null}abandon(t){_t(t);try{t?.close(1e3,"client-stop")}catch{}}recoveringStatus(){return this.everOpened?"recovering":"connecting"}urlFor(t){const e=t.wsUrl.includes("?")?"&":"?";return`${t.wsUrl}${e}token=${encodeURIComponent(t.token)}&sdk=${encodeURIComponent(this.opts.sdkVersion)}`}async connect(){if(this.stopped)return;const t=this.epoch;let e;try{e=await this.opts.mint()}catch(i){if(this.stopped||t!==this.epoch)return;this.handleMintFailure(i);return}if(!(this.stopped||t!==this.epoch))try{this.openSocket(e,!1)}catch(i){this.handleMintFailure(i)}}openSocket(t,e){const i=new this.WS(this.urlFor(t));e?this.next=i:(this.socket=i,this.expiresAt=t.expiresAt),i.onopen=()=>{this.stopped||(e?this.next===i&&this.swapIn(i,t.expiresAt):this.socket===i&&this.handleOpen())},i.onmessage=n=>{this.socket===i&&this.handleMessage(n.data)},i.onclose=n=>{if(!this.stopped){if(this.next===i){_t(i),this.next=null,this.later(re,()=>this.whenVisible(()=>{this.rotate()}));return}this.socket===i&&this.handleClose(n.code,n.reason)}}}handleOpen(){const t=this.everOpened;this.everOpened=!0,this.failures=0,this.authCloses=0,this.pingSupported=!0,this.lastInbound=Date.now(),this.opts.onStatus("open"),!this.stopped&&(this.startPings(),this.scheduleRotation(),!this.stopped&&(this.opts.onOpen(),t&&!this.stopped&&this.opts.onReconnected()))}swapIn(t,e){const i=this.socket;this.next=null,this.socket=t,this.expiresAt=e,this.failures=0,this.authCloses=0,this.pingSupported=!0,_t(i);try{i?.close(gs,"token-refresh")}catch{}this.clearTimers(),this.lastInbound=Date.now(),this.startPings(),this.scheduleRotation(),this.opts.onOpen(),this.stopped||this.opts.onReconnected()}handleMessage(t){if(this.stopped)return;this.lastInbound=Date.now();const e=hs(t);if(e){if(e.type==="ws_write_result"&&e.payload.error==="invalid_input_type"&&!e.payload.message_id){this.pingSupported=!1,this.stopPings();return}this.opts.onFrame(e)}}handleClose(t,e){if(!this.stopped){if(this.epoch+=1,_t(this.socket),this.socket=null,this.abandon(this.next),this.next=null,this.rotating=!1,this.stopPings(),this.clearTimers(),this.clearPageListeners(),t===4401){if(this.authCloses+=1,this.authCloses>ms){this.opts.onError(k("invalid_token")),this.scheduleBackoff();return}this.opts.onStatus(this.recoveringStatus()),this.whenVisible(()=>this.reconnectNow());return}if(t===1008&&e==="agent_inactive"){this.opts.onError(k("agent_inactive")),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(Ve,()=>this.reconnectNow());return}if(t===1008){this.terminate(e||"policy");return}this.scheduleBackoff()}}handleMintFailure(t){const e=t instanceof A?t.error:k("network");if(e.code==="agent_inactive"){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(Ve,()=>this.reconnectNow());return}if(We.has(e.code)){this.terminate(e.code);return}if(e.code==="rate_limited"&&e.retryAfterSeconds){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(e.retryAfterSeconds*1e3,()=>this.reconnectNow());return}this.scheduleBackoff()}reconnectNow(){this.stopped||(this.opts.onStatus(this.recoveringStatus()),this.connect())}scheduleBackoff(){if(this.stopped)return;const t=Math.min(this.failures,vt.length-1);if(this.failures+=1,this.failures>vt.length){this.opts.onStatus("offline"),this.retryWhenReachable();return}this.opts.onStatus(this.recoveringStatus());const e=Math.round(vt[t]*(.8+.4*this.random()));this.later(e,()=>{this.connect()})}retryWhenReachable(){if(this.stopped)return;let t=!1;const e=()=>{clearTimeout(o),this.timers.delete(o),n(),r(),this.waitingForPage.delete(e)},i=()=>{t||this.stopped||(t=!0,e(),this.reconnectNow())},n=this.page.onVisible(i),r=this.page.onOnline(i),o=setTimeout(()=>{this.stopped||i()},vt[vt.length-1]);this.timers.add(o),this.waitingForPage.add(e)}whenVisible(t){if(this.stopped)return;if(this.page.isVisible()){t();return}let e=!1;const i=this.page.onVisible(()=>{e||this.stopped||!this.page.isVisible()||(e=!0,i(),this.waitingForPage.delete(i),t())});this.waitingForPage.add(i)}startPings(){this.stopPings(),this.lastPingSentAt=0,this.pingTimer=setInterval(()=>{if(this.stopped||!this.isOpen||!this.pingSupported)return;const t=Date.now(),e=this.lastPingSentAt>this.lastInbound;if(this.page.isVisible()&&e&&t-this.lastInbound>=ps){this.declareDead();return}this.send({type:"ping"})&&(this.lastPingSentAt=t)},us)}declareDead(){const t=this.socket;if(t){_t(t);try{t.close(4001,"silent")}catch{}this.handleClose(4001,"silent")}}stopPings(){this.pingTimer!==null&&clearInterval(this.pingTimer),this.pingTimer=null}scheduleRotation(){const t=Math.max(5e3,this.expiresAt-Date.now()-fs);this.later(t,()=>this.whenVisible(()=>{this.rotate()}))}async rotate(){if(this.stopped||this.rotating||!this.isOpen||this.next)return;this.rotating=!0;const t=this.epoch;let e;try{e=await this.opts.mint()}catch(i){if(this.stopped||t!==this.epoch)return;this.rotating=!1;const n=i instanceof A?i.error:k("network");if(We.has(n.code)){this.terminate(n.code);return}const r=n.retryAfterSeconds?n.retryAfterSeconds*1e3:re;this.later(r,()=>this.whenVisible(()=>{this.rotate()}));return}if(!(this.stopped||t!==this.epoch)){this.rotating=!1;try{this.openSocket(e,!0)}catch{this.later(re,()=>this.whenVisible(()=>{this.rotate()}))}}}terminate(t){this.stop(),this.opts.onClosed(t)}later(t,e){if(this.stopped)return;const i=setTimeout(()=>{this.timers.delete(i),this.stopped||e()},t);this.timers.add(i)}clearPageListeners(){this.waitingForPage.forEach(t=>t()),this.waitingForPage.clear()}clearTimers(){this.timers.forEach(clearTimeout),this.timers.clear()}}const oe="osvi.chat.visitor",ys=/^web:[0-9a-f]{32}$/;function ae(){const s=new Map;return{get:t=>s.get(t)??null,set:(t,e)=>{s.set(t,e)},remove:t=>{s.delete(t)}}}function Ke(){const s=ae();let t=!1;const e=(i,n)=>{if(t)return n();try{return i()}catch{return t=!0,n()}};return{get:i=>e(()=>window.localStorage.getItem(i),()=>s.get(i)),set:(i,n)=>e(()=>window.localStorage.setItem(i,n),()=>s.set(i,n)),remove:i=>e(()=>window.localStorage.removeItem(i),()=>s.remove(i))}}const Ye=s=>`web:${Array.from(s,t=>t.toString(16).padStart(2,"0")).join("")}`;let ce=null;function lt(s,t){const e=s.get(oe);if(e&&ys.test(e))return e;e!==null&&s.remove(oe);let i;try{i=globalThis.crypto?.getRandomValues?.(new Uint8Array(16))}catch{}if(i){const n=Ye(i);return s.set(oe,n),n}if(!ce){const n=new Uint8Array(16);for(let r=0;r<n.length;r+=1)n[r]=Math.floor(Math.random()*256);ce=Ye(n)}return ce}function Ot(s){return`osvi.chat.session.${s}`}const Je="https://api.osvi.ai",vs=12e4,_s=15e3,Xe=[1e3,2e3,4e3,8e3,16e3],ws=2048,$s=new Set(["session_closed","session_dormant","new_session"]);function Rt(){const s=globalThis.crypto;if(s?.randomUUID)return s.randomUUID();if(s?.getRandomValues){const t=s.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}const Ze=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Qe={user:"user",ai:"assistant",assistant:"assistant",operator:"human",support:"human"};class xs{constructor(t){this.opts=t,this.state=Ze(),this.listeners=new Set,this.conn=null,this.sessionId=null,this.latestToken=null,this.chain=Promise.resolve(),this.startP=null,this.ensureP=null,this.pending=new Map,this.openGen=0,this.sessionGeneration=0,this.seen=[],this.seenSet=new Set,this.timers=new Set,this.awaitingTimer=null,this.destroyed=!1,this.wantNewServerSession=!1,this.switchTo=null,this.http=new Be(t.baseUrl??Je,t.fetch),this.store=t.store??Ke(),this.page=t.page??Ge(),this.interactions=new cs({sessionId:()=>this.sessionId,humanConnected:()=>this.state.mode==="human",sendFrame:e=>this.conn?.send(e)??!1,updateItems:e=>this.patch({items:e(this.state.items)}),refreshSnapshot:()=>this.fetchSnapshot(),onChange:()=>this.patch({}),newId:Rt})}get serverMode(){return this.opts.auth?.mode==="server"}serialize(t){const e=this.chain.then(t);return this.chain=e.catch(()=>{}),e}start(){return this.destroyed?Promise.resolve():(this.startP||(this.startP=this.serialize(()=>this.doStart()).finally(()=>{this.startP=null})),this.startP)}async doStart(){if(!(this.destroyed||this.sessionId&&this.conn)){if(this.serverMode){await this.openServerSession();return}try{const t=await this.http.bootstrap(this.opts.agentId,lt(this.store));if(this.destroyed)return;this.patch({agent:{agentId:this.opts.agentId,name:t.agent?.name??""}}),t.session?.id&&t.session.status==="active"?this.adopt(t.session.id,t,this.pending.size?"append":"replace"):this.store.remove(Ot(this.opts.agentId))}catch(t){this.fail(t,!1)}}}async send(t){if(this.destroyed)return{ok:!1,reason:"destroyed"};const e=t.trim();if(!e)return{ok:!1,reason:"empty"};if(this.state.mode==="ai"&&(this.interactions.pending||this.interactions.active?.interaction_status==="pending"))return{ok:!1,reason:"awaiting_interaction"};const i=Rt(),n=Rt(),r={kind:"message",id:i,role:"user",content:e,createdAt:new Date().toISOString(),status:"sending",idempotencyKey:n};return this.patch({items:[...this.state.items,r]}),this.pending.set(i,{frame:this.frameFor(r),attempts:0,gen:-1,ackTimer:null}),await this.ensureSession()?(this.transmit(i),{ok:!0,messageId:i}):(this.dropPending(i),this.setMessage(i,{status:"failed"}),{ok:!1,reason:"unavailable"})}async respond(t,e){return this.destroyed?!1:this.interactions.respond(t,e)}async retry(t){const e=this.state.items.find(i=>i.kind==="message"&&i.id===t);return!e||e.status!=="failed"||!e.idempotencyKey||this.destroyed?!1:(this.dropPending(t),this.pending.set(t,{frame:this.frameFor(e),attempts:0,gen:-1,ackTimer:null}),this.setMessage(t,{status:"sending"}),await this.ensureSession()?(this.transmit(t),!0):(this.dropPending(t),this.setMessage(t,{status:"failed"}),!1))}newSession(t={}){return this.destroyed?Promise.resolve(!1):!this.sessionId&&this.ensureP?this.ensureP.then(e=>e!==null):this.serialize(async()=>{if(this.destroyed)return!1;if(this.sessionId&&this.endSession("new_session"),t.keepHistory===!1&&this.patch({items:[]}),this.serverMode)return this.wantNewServerSession=!0,await this.openServerSession()!==null;try{const e=await this.http.createSession(this.opts.agentId,lt(this.store));return this.destroyed?!1:(this.adopt(e.id,null,"keep"),!0)}catch(e){return this.fail(e,!1),!1}})}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getState(){return this.state}resolveUrl(t){return this.http.resolveUrl(t)}destroy(){this.destroyed||(this.destroyed=!0,this.sessionGeneration+=1,this.conn?.stop(),this.conn=null,this.timers.forEach(clearTimeout),this.timers.clear(),this.pending.forEach(t=>{t.ackTimer&&clearTimeout(t.ackTimer)}),this.pending.clear(),this.awaitingTimer&&clearTimeout(this.awaitingTimer),this.interactions.reset(),this.sessionId=null,this.latestToken=null,this.switchTo=null,this.state=Ze(),this.listeners.clear())}ensureSession(){return this.ensureP?this.ensureP:(this.ensureP=this.serialize(async()=>this.destroyed?null:this.sessionId?this.sessionId:this.serverMode?this.openServerSession():this.openAnonymousSession()).finally(()=>{this.ensureP=null}),this.ensureP)}async openAnonymousSession(){try{const t=lt(this.store),e=await this.http.bootstrap(this.opts.agentId,t);if(this.destroyed)return null;if(this.patch({agent:{agentId:this.opts.agentId,name:e.agent?.name??""}}),e.session?.id&&e.session.status==="active")return this.adopt(e.session.id,e,"append"),this.sessionId;const i=await this.http.createSession(this.opts.agentId,t);return this.destroyed?null:(this.adopt(i.id,null,"keep"),this.sessionId)}catch(t){return this.fail(t,!1),null}}async openServerSession(t){const e=this.sessionGeneration;try{let i=t?this.accept(t):await this.serverToken(e);this.assertCurrent(e),this.latestToken=i.token;let n;try{n=await this.http.snapshot(i.sessionId,i.token)}catch(r){if(this.assertCurrent(e),!(r instanceof A)||r.error.code!=="invalid_token")throw r;i=await this.serverToken(e),this.assertCurrent(e),this.latestToken=i.token,n=await this.http.snapshot(i.sessionId,i.token)}return this.assertCurrent(e),this.adopt(i.sessionId,n,this.state.items.length?"append":"replace",i),this.sessionId}catch(i){return this.isCurrent(e)&&this.fail(i,!0),null}}async serverToken(t=this.sessionGeneration){if(this.assertCurrent(t),this.opts.auth?.mode!=="server")throw new Error("not server mode");let e;const i=this.wantNewServerSession;this.wantNewServerSession=!1;try{e=await(i?this.opts.auth.getToken({newSession:!0}):this.opts.auth.getToken())}catch{throw new A(k("token_failed","getToken failed"),0)}this.assertCurrent(t);try{return this.accept(e)}catch(n){throw this.isCurrent(t)&&this.fail(n,!1),n}}accept(t){return this.checkWsUrl(t.wsUrl),{...t,expiresAt:De(t.expiresAt)}}checkWsUrl(t){let e=null;try{e=new URL(t)}catch{}const i=e?.hostname==="localhost"||e?.hostname==="127.0.0.1";if(e&&(e.protocol==="wss:"||e.protocol==="ws:"&&i))return;const n=k("token_failed","The chat stream URL must use wss://");throw new A(n,0)}isCurrent(t,e){return!this.destroyed&&this.sessionGeneration===t&&(e===void 0||this.sessionId===e)}assertCurrent(t,e){if(!this.isCurrent(t,e))throw new A(k("session_closed"),0)}adopt(t,e,i,n,r=!0){if(this.sessionId===t&&this.conn)return;this.conn?.stop(),this.conn=null,this.sessionId=t;const o=++this.sessionGeneration;this.serverMode||this.store.set(Ot(this.opts.agentId),t),e&&this.applySnapshot(e,i);let a=n??null;const c=this.serverMode?null:lt(this.store);let l=!0,f=!1;const d=async()=>{if(this.assertCurrent(o,t),a){const g=a;return a=null,this.latestToken=g.token,g}if(this.serverMode){const g=await this.serverToken(o);if(this.assertCurrent(o,t),g.sessionId!==t)throw this.switchTo=g,new A(k("session_closed"),0);return this.latestToken=g.token,g}const h=l;l=!1;let u;try{u=await this.http.mintPublicToken(t)}catch(g){throw f=h&&r&&this.isCurrent(o,t)&&g instanceof A&&g.status===404&&g.error.code==="session_not_found"&&[...this.pending.values()].every(x=>x.gen===-1),g}this.assertCurrent(o,t);try{this.checkWsUrl(u.wsUrl)}catch(g){throw this.fail(g,!1),g}return this.latestToken=u.token,u};this.conn=new bs({mint:d,sdkVersion:Ki,page:this.page,random:this.opts.random,WebSocketImpl:this.opts.WebSocketImpl,onFrame:h=>this.onFrame(h),onStatus:h=>this.patch({status:h,...h==="open"?{error:null}:{}}),onOpen:()=>this.onOpen(),onReconnected:()=>{this.recover()},onError:h=>this.patch({error:h}),onClosed:h=>{if(!this.isCurrent(o,t))return;if(f&&c&&h==="session_not_found"){f=!1,this.serialize(()=>this.replaceBeforeFirstWrite(o,t,c));return}const u=this.switchTo;this.switchTo=null,this.endSession(h),u&&this.serialize(()=>this.openServerSession(u))}}),this.conn.start()}async replaceBeforeFirstWrite(t,e,i){if(this.isCurrent(t,e))try{const n=await this.http.bootstrap(this.opts.agentId,i);if(!this.isCurrent(t,e))return;const r=n?.session,o=r,a=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n?.agent?.agent_uuid!==this.opts.agentId||!Array.isArray(n.messages)||!r||typeof r.id!="string"||!a.test(r.id)||r.id===e||r.status!=="active"||r.mode!=="ai"&&r.mode!=="support"||o&&"customer_id"in o&&o.customer_id!==i||o&&"agent_uuid"in o&&o.agent_uuid!==this.opts.agentId||[...this.pending.values()].some(c=>c.gen!==-1)){this.endSession("session_not_found");return}this.adopt(r.id,n,"append",void 0,!1)}catch{this.isCurrent(t,e)&&this.endSession("session_not_found")}}onOpen(){this.openGen+=1,this.seen=[],this.seenSet.clear();for(const t of[...this.pending.keys()])this.write(t);this.interactions.onConnectionOpen()}async recover(){const t=this.sessionId,e=this.sessionGeneration,i=await this.fetchSnapshot();i&&t&&this.isCurrent(e,t)&&this.applySnapshot(i,"reconcile")}async fetchSnapshot(){if(this.destroyed)return null;const t=this.sessionId,e=this.sessionGeneration;if(!t)return null;try{try{const i=await this.http.snapshot(t,this.latestToken??await this.mintFresh(t));return this.isCurrent(e,t)?i:null}catch(i){if(this.assertCurrent(e,t),!(i instanceof A)||i.error.code!=="invalid_token")throw i;const n=await this.http.snapshot(t,await this.mintFresh(t));return this.isCurrent(e,t)?n:null}}catch(i){if(i instanceof A&&i.error.code==="session_not_found"){if(!this.isCurrent(e,t))return null;this.endSession("session_closed"),this.serverMode||this.readoptAfterReplacement()}return null}}async mintFresh(t){const e=this.sessionGeneration;if(this.assertCurrent(e,t),this.serverMode){const n=await this.serverToken(e);return this.assertCurrent(e,t),this.latestToken=n.token,n.token}const i=await this.http.mintPublicToken(t);return this.assertCurrent(e,t),this.checkWsUrl(i.wsUrl),this.latestToken=i.token,i.token}async readoptAfterReplacement(){try{const t=await this.http.bootstrap(this.opts.agentId,lt(this.store));!this.destroyed&&!this.sessionId&&t.session?.id&&t.session.status==="active"&&this.adopt(t.session.id,t,"append")}catch{}}endSession(t){if(this.destroyed)return;this.sessionGeneration+=1,this.conn?.stop(),this.conn=null,this.sessionId=null,this.latestToken=null,this.serverMode||this.store.remove(Ot(this.opts.agentId)),this.interactions.reset(),this.pending.forEach(r=>{r.ackTimer&&clearTimeout(r.ackTimer)}),this.pending.clear();const e=this.state.items.map(r=>r.kind==="message"&&r.status==="sending"?{...r,status:"failed"}:r),i=e[e.length-1],n={kind:"divider",id:Rt(),reason:"session_ended"};this.setAwaiting(!1),this.patch({status:"closed",mode:"ai",items:e.length&&i?.kind!=="divider"?[...e,n]:e,...$s.has(t)?{}:{error:k(t)}})}onFrame(t){if(this.destroyed)return;if(t.event_id!==void 0){const i=String(t.event_id);if(this.seenSet.has(i))return;this.seenSet.add(i),this.seen.push(i),this.seen.length>ws&&this.seenSet.delete(this.seen.shift())}const e=t.payload;switch(t.type){case"ws_write_result":this.interactions.handleWriteResult(e)||this.onWriteResult(e);return;case"message_received":{if(e.type==="interaction")return;const i=ne(e);if(!i)return;i.role==="user"?this.onUserEcho(i.id,i.content,i.created_at,typeof e.message_id=="string"?e.message_id:void 0):this.appendRemote(i.id,i.role,i.content,i.created_at);return}case"operator_message":{const i=ne({...e,role:"operator"});i&&this.appendRemote(i.id,"operator",i.content,i.created_at);return}case"mode_changed":e.to==="support"?this.setMode("human"):e.to==="ai"&&this.setMode("ai");return;case"takeover_started":this.setMode("human");return;case"takeover_ended":this.setMode("ai");return;case"interaction_published":case"interaction_updated":case"interaction_closed":this.interactions.applyEvent(t)&&t.type==="interaction_published"&&this.setAwaiting(!1),this.patch({});return;case"turn_result":(e.state==="failed"||e.state==="error")&&(this.setAwaiting(!1),this.patch({error:{code:"unknown",message:"The assistant could not reply",retryable:!0}}));return;case"session_closed":case"session_dormant":this.endSession(t.type);return;default:return}}onWriteResult(t){const e=t.message_id;if(!e)return;const i=this.pending.get(e);if(i){if(i.ackTimer&&(clearTimeout(i.ackTimer),i.ackTimer=null),t.state==="accepted"||t.state==="merged"||t.state==="done"){this.pending.delete(e),this.setMessage(e,{status:"sent"}),this.setAwaiting(!0);return}if(t.state==="busy"&&i.attempts<Xe.length){const n=Xe[i.attempts];i.attempts+=1,this.later(n,()=>{this.pending.get(e)===i&&(i.gen=-1,this.transmit(e))});return}this.pending.delete(e),this.setMessage(e,{status:"failed"}),this.patch({error:k(t.error,t.error)})}}onUserEcho(t,e,i,n){const r=this.state.items;if(r.some(a=>a.kind==="message"&&a.serverId===t))return;const o=n?r.findIndex(a=>a.kind==="message"&&a.role==="user"&&a.id===n):r.findIndex(a=>a.kind==="message"&&a.role==="user"&&!a.serverId&&a.status!=="failed"&&a.content===e);if(o>=0){const a=r.slice(),c=a[o];a[o]={...c,serverId:t,status:"sent"},this.dropPending(c.id),this.patch({items:a});return}this.appendRemote(t,"user",e,i)}appendRemote(t,e,i,n){const r=Qe[e];if(!r||this.state.items.some(a=>a.kind==="message"&&a.serverId===t))return;const o={kind:"message",id:`srv:${t}`,serverId:t,role:r,content:i,createdAt:n??new Date().toISOString(),status:"sent"};this.patch({items:[...this.state.items,o]}),r!=="user"&&this.setAwaiting(!1)}applySnapshot(t,e){if(this.destroyed)return;const i=[],n=new Map;for(const c of t.messages??[]){const l=ct(c);if(l){i.push({kind:"interaction",id:l.interaction_id,interaction:l});continue}const f=ne(c),d=f?Qe[f.role]:void 0;if(f&&d){i.push({kind:"message",id:`srv:${f.id}`,serverId:f.id,role:d,content:f.content,createdAt:f.created_at??new Date().toISOString(),status:"sent"});const h=c.message_id;typeof h=="string"&&n.set(f.id,h)}}let r=this.state.items;if(e==="replace")r=i;else if(e==="append"){let c=r.length;for(;c>0;){const l=r[c-1];if(l.kind==="message"&&l.role==="user"&&l.status==="sending"&&!l.serverId)c-=1;else break}r=[...r.slice(0,c),...i,...r.slice(c)]}else if(e==="reconcile"){const c=new Set(r.flatMap(l=>l.kind==="message"?[l.serverId]:l.kind==="interaction"?[l.id]:[]));for(const l of i){const f=l.kind==="message"?l.serverId:l.id;if(l.kind==="message"&&l.role==="user"&&!c.has(f)){const d=n.get(l.serverId),h=r.findIndex(u=>u.kind==="message"&&u.role==="user"&&!u.serverId&&(d?u.id===d:u.content===l.content));if(h>=0){const u=r[h];r=r.slice(),r[h]={...u,serverId:l.serverId,status:"sent"},this.dropPending(u.id),c.add(f);continue}}c.has(f)||(r=[...r,l],c.add(f))}}const o=t.session;this.patch({items:r,...o?{mode:o.mode==="support"?"human":"ai"}:{}}),this.interactions.applySnapshot(t);const a=r.filter(c=>c.kind!=="divider").at(-1);a&&!(a.kind==="message"&&a.role==="user")&&this.setAwaiting(!1),this.patch({})}frameFor(t){return{type:"message",content:t.content,message_id:t.id,idempotency_key:t.idempotencyKey,supported_interactions:Xt}}transmit(t){this.write(t)}write(t){const e=this.pending.get(t);!e||!this.conn?.isOpen||e.gen===this.openGen||this.conn.send(e.frame)&&(e.gen=this.openGen,e.ackTimer&&clearTimeout(e.ackTimer),e.ackTimer=setTimeout(()=>{this.onAckTimeout(t)},_s))}async onAckTimeout(t){const e=this.pending.get(t);if(!e||this.destroyed||(e.ackTimer=null,!this.conn?.isOpen))return;const i=this.openGen;await this.recover(),!(this.destroyed||this.pending.get(t)!==e||!this.conn?.isOpen||i!==this.openGen)&&(this.dropPending(t),this.setMessage(t,{status:"failed"}),this.patch({error:k("network","The message could not be confirmed")}))}dropPending(t){const e=this.pending.get(t);e?.ackTimer&&clearTimeout(e.ackTimer),this.pending.delete(t)}setMode(t){this.setAwaiting(!1),this.patch({mode:t})}setAwaiting(t){this.awaitingTimer&&(clearTimeout(this.awaitingTimer),this.awaitingTimer=null),t&&(this.awaitingTimer=setTimeout(()=>{this.awaitingTimer=null,this.patch({awaitingReply:!1})},vs)),this.state.awaitingReply!==t&&this.patch({awaitingReply:t})}setMessage(t,e){this.patch({items:this.state.items.map(i=>i.kind==="message"&&i.id===t?{...i,...e}:i)})}fail(t,e){const i=t instanceof A?t.error:k("network","Network error");this.patch({error:i,...e||!i.retryable?{status:"closed"}:{}})}later(t,e){const i=setTimeout(()=>{this.timers.delete(i),this.destroyed||e()},t);this.timers.add(i)}patch(t){if(this.destroyed)return;const e={...this.state,...t,activeInteraction:this.interactions.active,interactionPending:this.interactions.pending};Object.keys(e).some(n=>e[n]!==this.state[n])&&(this.state=e,this.listeners.forEach(n=>n(e)))}}function ti(s){return new xs(s)}const ei={primary:"#4f46e5",background:"#ffffff",surface:"#f4f4f5",text:"#18181b",userBubble:"#4f46e5",assistantBubble:"#f4f4f5"},ks={primary:"#6366f1",background:"#0a0a12",surface:"#1c1c27",text:"#f4f4f5",userBubble:"#6366f1",assistantBubble:"#1f1f2b"},Ss={none:"0px",sm:"6px",md:"10px",lg:"16px",full:"9999px"},wt={primary:"--osvi-color-primary",background:"--osvi-color-background",surface:"--osvi-color-surface",text:"--osvi-color-text",userBubble:"--osvi-color-user-bubble",assistantBubble:"--osvi-color-assistant-bubble"},As=s=>`var(${wt[s]}, ${ei[s]})`;function ii(s){const t={...s?.mode==="dark"?ks:ei,...s?.colors};!s?.colors?.userBubble&&s?.colors?.primary&&(t.userBubble=s.colors.primary);const e={};for(const n of Object.keys(wt))e[wt[n]]=t[n];const i=s?.radius??"md";return e["--osvi-radius"]=typeof i=="number"?`${i}px`:Ss[i],e}function Cs(s){if(!s)return{};if(s.mode)return ii(s);const t=ii(s),e={};for(const i of Object.keys(s.colors??{}))e[wt[i]]=t[wt[i]];return s.radius!==void 0&&(e["--osvi-radius"]=t["--osvi-radius"]),e}const si=new WeakMap;function le(s,t){for(const i of si.get(s)??[])s.style.removeProperty(i);const e=Cs(t);for(const[i,n]of Object.entries(e))s.style.setProperty(i,n);si.set(s,Object.keys(e))}const ni={placeholder:"Type your message…",send:"Send",typing:"Typing…",humanJoined:"A team member has joined",chooseOption:"Choose an option to continue.",typeAnswer:"Type your answer below, then press Send.",sending:"Sending your response…",pausedForHuman:"Choices are paused while a team member is connected.",sendFailed:"Message not sent.",retry:"Retry",sessionEnded:"Conversation ended",reconnecting:"Reconnecting…",offline:"You are offline. We will reconnect automatically.",unavailable:"This chat is unavailable.",originBlocked:"This chat is not enabled for this website.",rateLimited:"Too many requests. Please try again in a few minutes.",tryAgain:"Try again",closeChat:"Close chat",poweredBy:"Powered by Osvi AI",newChat:"New chat",emptyState:"Send a message to start chatting.",defaultTitle:"Chat"},ri=new Set;function oi(s,t){ri.has(s)||(ri.add(s),console.warn(`[osvi-chat] ${t}`))}function $(s,t){return s!=null&&t.includes(s)?s:void 0}function Mt(s){if(s!=null)return $(s,["none","sm","md","lg","full"])??(/^\d{1,2}(?:px)?$/.test(s)?Number(s.replace(/px$/,"")):void 0)}function Ut(s){if(s){try{const t=new URL(s);if(!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1"].includes(t.hostname)))return s.replace(/\/+$/,"")}catch{}oi("base-url","ignored an invalid base-url (https required, http only for localhost)")}}function de(s){if(s){if(/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/]+={0,2}$/i.test(s))return s;try{const t=new URL(s);if(t.protocol==="https:"&&!t.username&&!t.password)return s}catch{}}}function ai(s,t){if(t){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}oi(s,`ignored invalid JSON in the ${s} attribute`)}}const Q={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4},ci=s=>(...t)=>({_$litDirective$:s,values:t});let li=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const{I:Is}=zi,di=s=>s,Es=s=>s.strings===void 0,hi=()=>document.createComment(""),$t=(s,t,e)=>{const i=s._$AA.parentNode,n=t===void 0?s._$AB:t._$AA;if(e===void 0){const r=i.insertBefore(hi(),n),o=i.insertBefore(hi(),n);e=new Is(r,o,s,s.options)}else{const r=e._$AB.nextSibling,o=e._$AM,a=o!==s;if(a){let c;e._$AQ?.(s),e._$AM=s,e._$AP!==void 0&&(c=s._$AU)!==o._$AU&&e._$AP(c)}if(r!==n||a){let c=e._$AA;for(;c!==r;){const l=di(c).nextSibling;di(i).insertBefore(c,n),c=l}}}return e},tt=(s,t,e=s)=>(s._$AI(t,e),s),Ts={},ui=(s,t=Ts)=>s._$AH=t,Ps=s=>s._$AH,he=s=>{s._$AR(),s._$AA.remove()};const pi=(s,t,e)=>{const i=new Map;for(let n=t;n<=e;n++)i.set(s[n],n);return i},Os=ci(class extends li{constructor(s){if(super(s),s.type!==Q.CHILD)throw Error("repeat() can only be used in text expressions")}dt(s,t,e){let i;e===void 0?e=t:t!==void 0&&(i=t);const n=[],r=[];let o=0;for(const a of s)n[o]=i?i(a,o):o,r[o]=e(a,o),o++;return{values:r,keys:n}}render(s,t,e){return this.dt(s,t,e).values}update(s,[t,e,i]){const n=Ps(s),{values:r,keys:o}=this.dt(t,e,i);if(!Array.isArray(n))return this.ut=o,r;const a=this.ut??(this.ut=[]),c=[];let l,f,d=0,h=n.length-1,u=0,g=r.length-1;for(;d<=h&&u<=g;)if(n[d]===null)d++;else if(n[h]===null)h--;else if(a[d]===o[u])c[u]=tt(n[d],r[u]),d++,u++;else if(a[h]===o[g])c[g]=tt(n[h],r[g]),h--,g--;else if(a[d]===o[g])c[g]=tt(n[d],r[g]),$t(s,c[g+1],n[d]),d++,g--;else if(a[h]===o[u])c[u]=tt(n[h],r[u]),$t(s,n[d],n[h]),h--,u++;else if(l===void 0&&(l=pi(o,u,g),f=pi(a,d,h)),l.has(a[d]))if(l.has(a[h])){const x=f.get(o[u]),G=x!==void 0?n[x]:null;if(G===null){const At=$t(s,n[d]);tt(At,r[u]),c[u]=At}else c[u]=tt(G,r[u]),$t(s,n[d],G),n[x]=null;u++}else he(n[h]),h--;else he(n[d]),d++;for(;u<=g;){const x=$t(s,c[g+1]);tt(x,r[u]),c[u++]=x}for(;d<=h;){const x=n[d++];x!==null&&he(x)}return this.ut=o,ui(s,c),E}}),Rs=/https?:\/\/[^\s<>"']+/g,Nt=(s,t)=>s.split(t).length-1;function Ms(s){for(;;){const t=s[s.length-1];if(t&&".,!?;:".includes(t)||t===")"&&Nt(s,")")>Nt(s,"(")||t==="]"&&Nt(s,"]")>Nt(s,"[")){s=s.slice(0,-1);continue}return s}}function Us(s){const t=[];let e=0;for(const i of s.matchAll(Rs)){const n=Ms(i[0]),r=i.index;try{const o=new URL(n);if(!["http:","https:"].includes(o.protocol))continue}catch{continue}r>e&&t.push({text:s.slice(e,r)}),t.push({href:n,text:n}),e=r+n.length}return e<s.length&&t.push({text:s.slice(e)}),t.length?t:[{text:s}]}function Ns(s,t,e,i,n){return p`${s.items.length?Os(s.items,r=>r.id,r=>{if(r.kind==="divider")return p`<p class="divider">${t.sessionEnded}</p>`;if(r.kind==="message")return p`<article class=${`bubble ${r.role}`}>${r.role==="human"?p`<small class="team">Team</small>`:m}<p>${Us(r.content).map(l=>"href"in l?p`<a href=${l.href} target="_blank" rel="noopener noreferrer">${l.text}</a>`:l.text)}</p>${r.role==="user"&&r.status==="failed"?p`<span class="failed"><span>${t.sendFailed}</span><button type="button" @click=${()=>n(r.id)}>${t.retry}</button></span>`:m}</article>`;const o=r.interaction,a=o.interaction_id===s.activeInteraction?.interaction_id&&o.interaction_status==="pending",c=!a||s.interactionPending||s.mode==="human";switch(o.tool_type){case"ui_buttons":return p`<osvi-buttons data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.buttons??"chips"} base-url=${i}></osvi-buttons>`;case"ui_carousel":return p`<osvi-carousel data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.carousel??"slider"} base-url=${i}></osvi-carousel>`;case"ui_date_picker":return p`<osvi-date-picker data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} base-url=${i}></osvi-date-picker>`;default:return p`<p>${o.content}</p>`}}):p`<p class="empty">${t.emptyState}</p>`}${s.awaitingReply?p`<div class="typing" role="img" aria-label=${t.typing}><i></i><i></i><i></i></div>`:m}`}const Ds=ci(class extends li{constructor(s){if(super(s),s.type!==Q.PROPERTY&&s.type!==Q.ATTRIBUTE&&s.type!==Q.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!Es(s))throw Error("`live` bindings can only contain a single expression")}render(s){return s}update(s,[t]){if(t===E||t===m)return t;const e=s.element,i=s.name;if(s.type===Q.PROPERTY){if(t===e[i])return E}else if(s.type===Q.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(i))return E}else if(s.type===Q.ATTRIBUTE&&e.getAttribute(i)===t+"")return E;return ui(s),t}}),V=(s,t="")=>R`<svg class=${t} viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${s}</svg>`;V(R`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z"/><path d="M8.5 8.5h7M8.5 11.5h4"/>`);const Bs=V(R`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z"/><path d="M12 6.5v6M9 9.5h6"/>`),fi=V(R`<path d="M6 6l12 12M18 6L6 18"/>`),Ls=V(R`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z"/><path d="M8.5 8.5h7M8.5 11.5h4"/>`,"chat"),js=V(R`<path d="M6 6l12 12M18 6L6 18"/>`,"close"),Hs=V(R`<path d="M12 19V5M5.5 11.5L12 5l6.5 6.5"/>`),gi=V(R`<path d="M15 6l-6 6 6 6"/>`),ue=V(R`<path d="M9 6l6 6-6 6"/>`),zs=R`<svg viewBox="0 0 134 134" aria-hidden="true" focusable="false"><defs><linearGradient id="osvi-g" x1="-36.28" y1="32.2" x2="161.98" y2="93.64" gradientUnits="userSpaceOnUse"><stop offset=".304" stop-color="#155DFC"/><stop offset=".822" stop-color="#353333"/></linearGradient><mask id="osvi-m" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="-7" y="-6" width="149" height="150"><path fill-rule="evenodd" clip-rule="evenodd" fill="#0F0F0F" d="M141.385 114.008L141.622 108.411V29.4704L141.385 23.8743C139.964 7.44314 126.224 -5.41602 109.523 -5.41602H25.3094C8.60869 -5.41602 -5.13083 7.44314 -6.55216 23.8743L-6.78906 29.4704V108.411L-6.55216 114.008C-5.13083 130.439 8.60869 143.298 25.3094 143.298H109.523C126.224 143.298 139.964 130.439 141.385 114.008ZM25.3094 102.339C9.55625 102.339 65.7059 83.8874 53.6176 66.6191C42.3654 50.5452 93.7703 32.6852 109.523 32.6852C125.277 32.6852 73.161 54.1172 81.4521 80.9071C86.1899 96.2156 40.944 102.339 25.3094 102.339Z"/></mask></defs><g mask="url(#osvi-m)"><ellipse cx="66.88" cy="66.79" rx="67.22" ry="66.81" fill="url(#osvi-g)"/></g></svg>`;function Fs(s){return p`<div class="composer"><textarea rows="1" aria-label="Message" placeholder=${s.placeholder} .value=${Ds(s.draft)} ?disabled=${s.disabled} @input=${t=>{const e=t.target;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,s.input(t)}} @keydown=${t=>{t.key==="Enter"&&!t.shiftKey&&!t.isComposing&&!s.disabled&&(t.preventDefault(),s.send())}}></textarea><button type="button" class="send" title=${s.strings.send} aria-label=${s.strings.send} ?disabled=${s.disabled||!s.draft.trim()} @click=${s.send}>${Hs}<span class="sr">${s.strings.send}</span></button></div>`}var qs=Object.defineProperty,v=(s,t,e,i)=>{for(var n=void 0,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=o(t,e,n)||n);return n&&qs(t,e,n),n};const mi=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),bi={fromAttribute:s=>s!=="false"},y=(j=class extends Z{constructor(){super(...arguments),this.agentId="",this.baseUrl="",this.client=null,this.theme={},this.variants={},this.strings={},this.poweredBy=!0,this.newChat=!0,this.header={},this.closable=!1,this.chatState=mi(),this.draft="",this.busy=!1,this.typed=null,this.ownClient=null,this.boundClient=null,this.ownKey="",this.generation=0,this.followBottom=!0,this.focusedInteraction=null,this.send=()=>{if(this.blocked||!this.draft.trim()||!this.boundClient)return;const t=this.boundClient,e=this.draft.trim(),i=this.typed;this.draft="",i&&this.restoreDraft(),this.requestUpdate();const n=this.renderRoot.querySelector("textarea");n&&(n.style.height=""),this.run(()=>i?t.respond(i.id,{kind:"text",value:e}):t.send(e))},this.respond=t=>{const e=t.detail,i=this.chatState;if(!e||this.busy||i.mode!=="ai"||i.interactionPending||i.activeInteraction?.interaction_status!=="pending"||e.interactionId!==i.activeInteraction.interaction_id)return;t.stopPropagation();const n=this.boundClient;n&&this.run(()=>n.respond(e.interactionId,e.response))},this.requestInput=t=>{const e=t.detail,i=this.chatState;!e||this.busy||i.mode!=="ai"||i.interactionPending||i.activeInteraction?.interaction_status!=="pending"||e.interactionId!==i.activeInteraction.interaction_id||(t.stopPropagation(),this.typed={id:e.interactionId,placeholder:typeof e.placeholder=="string"?e.placeholder:void 0,previousDraft:this.typed?.previousDraft??this.draft},this.draft="",this.requestUpdate(),this.updateComplete.then(()=>this.renderRoot.querySelector("textarea")?.focus()))}}connectedCallback(){super.connectedCallback(),this.syncClient()}disconnectedCallback(){super.disconnectedCallback(),this.releaseClient()}releaseClient(){++this.generation,this.unsubscribe?.(),this.unsubscribe=void 0,this.boundClient=null;const t=this.ownClient;this.ownClient=null,this.ownKey="",t?.destroy(),this.busy=!1,this.typed=null,this.focusedInteraction=null,this.requestUpdate()}syncClient(){if(!this.isConnected||!this.client&&!this.agentId&&!this.boundClient)return;const t=JSON.stringify([this.agentId,Ut(this.baseUrl)]);if((this.client?this.boundClient===this.client&&!this.ownClient:this.ownClient&&t===this.ownKey)||(this.releaseClient(),this.chatState=mi(),!this.client&&!this.agentId))return;const e=!this.client,i=this.client??j.clientFactory({agentId:this.agentId,baseUrl:Ut(this.baseUrl)});this.boundClient=i,e&&(this.ownClient=i,this.ownKey=t);const n=this.generation;this.chatState=i.getState(),this.requestUpdate(),this.unsubscribe=i.subscribe(r=>{this.generation!==n||this.boundClient!==i||(this.chatState=r,this.requestUpdate(),this.typed&&(r.mode==="human"||r.activeInteraction?.interaction_id!==this.typed.id||r.activeInteraction.interaction_status!=="pending")&&this.restoreDraft())}),e&&this.run(()=>i.start())}willUpdate(){this.syncClient(),le(this,this.mergedTheme())}mergedTheme(){const t=ai("theme",this.themeAttribute),e={},i=t?.colors;if(i&&typeof i=="object"&&!Array.isArray(i))for(const o of["primary","background","surface","text","userBubble","assistantBubble"]){const a=i[o];typeof a=="string"&&(e[o]=a)}typeof this.primaryColor=="string"&&(e.primary=this.primaryColor);const n=Mt(this.radius)??(typeof t?.radius=="number"&&Number.isInteger(t.radius)&&t.radius>=0&&t.radius<=99?t.radius:typeof t?.radius=="string"?Mt(t.radius):void 0),r=$(this.mode,["light","dark"])??$(typeof t?.mode=="string"?t.mode:void 0,["light","dark"]);return{...this.theme,colors:{...this.theme?.colors,...e},...n===void 0?{}:{radius:n},...r===void 0?{}:{mode:r}}}get labels(){const t={...ni};for(const e of[this.strings,ai("strings",this.stringsAttribute)])for(const i of Object.keys(ni))typeof e?.[i]=="string"&&(t[i]=e[i]);return t}get blocked(){const t=this.chatState;return!this.boundClient||this.busy||t.status==="connecting"||t.status==="closed"&&!!t.error&&!t.error.retryable||t.mode==="ai"&&(t.interactionPending||t.activeInteraction?.interaction_status==="pending"&&!this.typed)}get sessionBusy(){return this.busy||this.chatState.status==="connecting"||this.chatState.interactionPending||this.chatState.items.some(t=>t.kind==="message"&&t.status==="sending")}async run(t){if(this.busy||!this.boundClient)return;const e=this.generation;this.busy=!0,this.requestUpdate();try{await t()}catch{}finally{this.generation===e&&(this.busy=!1,this.requestUpdate())}}restoreDraft(){this.typed&&(this.draft=this.typed.previousDraft,this.typed=null,this.requestUpdate())}async focusActiveInteraction(){if(await this.updateComplete,!this.isConnected||this.chatState.activeInteraction?.interaction_status!=="pending")return;const t=this.renderRoot.querySelector('[data-live="true"]');if(!t)return;const e=this.chatState.activeInteraction.interaction_id;await t.updateComplete,!(!this.isConnected||this.chatState.activeInteraction?.interaction_id!==e)&&t.shadowRoot?.querySelector('button:not(:disabled),input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex="0"]')?.focus()}updated(){const t=this.renderRoot.querySelector(".transcript");t&&this.followBottom&&(t.scrollTop=t.scrollHeight);const e=this.chatState.activeInteraction?.interaction_status==="pending"?this.chatState.activeInteraction.interaction_id:null;e!==this.focusedInteraction&&(this.focusedInteraction=e,e&&this.isConnected&&!this.hidden&&document.visibilityState!=="hidden"&&this.focusActiveInteraction())}statusText(t){const e=this.chatState;return e.error?.code==="origin_not_allowed"?t.originBlocked:e.error&&["agent_inactive","agent_archived","agent_not_found"].includes(e.error.code)?t.unavailable:e.error?.code==="rate_limited"?t.rateLimited:e.error?.code==="token_failed"?e.error.message:e.status==="recovering"?t.reconnecting:e.status==="offline"?t.offline:e.interactionPending||this.busy&&this.typed?t.sending:e.activeInteraction?.interaction_status==="pending"?e.mode==="human"?t.pausedForHuman:this.typed?t.typeAnswer:t.chooseOption:e.status==="closed"?t.sessionEnded:""}render(){const t=this.labels,e=this.chatState,i=this.boundClient,n=de(this.headerAvatar??this.header.avatarUrl),r={...this.variants,...$(this.buttons,["chips","list"])?{buttons:$(this.buttons,["chips","list"])}:{},...$(this.carousel,["slider","list"])?{carousel:$(this.carousel,["slider","list"])}:{}},o=this.headerTitle??this.header.title??e.agent?.name??t.defaultTitle;return p`<header>${n?p`<img class="avatar" src=${n} alt="" referrerpolicy="no-referrer">`:p`<span class="avatar" aria-hidden="true">${o.trim().charAt(0).toUpperCase()}</span>`}<div class="heading"><h2>${o}</h2>${this.headerSubtitle??this.header.subtitle?p`<p>${this.headerSubtitle??this.header.subtitle}</p>`:m}${e.mode==="human"?p`<small>${t.humanJoined}</small>`:m}</div>
4
+ ${this.newChat?p`<button type="button" class="icon" title=${t.newChat} ?disabled=${!i||this.sessionBusy} @click=${()=>i&&!this.sessionBusy&&void this.run(()=>i.newSession({keepHistory:this.newChatHistory==="keep"}))}>${Bs}<span class="sr">${t.newChat}</span></button>`:m}
5
+ ${this.closable?p`<button type="button" class="icon" title=${t.closeChat} aria-label=${t.closeChat} @click=${()=>this.dispatchEvent(new CustomEvent("osvi-close",{bubbles:!0,composed:!0}))}>${fi}</button>`:m}</header>
6
+ <div class="transcript" role="log" aria-live="polite" aria-label="Conversation" @scroll=${a=>{const c=a.currentTarget;this.followBottom=c.scrollHeight-c.scrollTop-c.clientHeight<=80}} @osvi-respond=${this.respond} @osvi-request-input=${this.requestInput}>${Ns(e,t,r,i?.resolveUrl("")??"",a=>{i&&this.run(()=>i.retry(a))})}</div>
7
+ <div class="status" role="status">${this.statusText(t)}${e.error?.retryable&&(e.status==="idle"||e.status==="closed")?p`<button type="button" ?disabled=${this.busy||!i} @click=${()=>i&&void this.run(()=>i.start())}>${t.tryAgain}</button>`:m}</div>
8
+ ${Fs({strings:t,draft:this.draft,placeholder:this.typed?.placeholder??t.placeholder,disabled:this.blocked,input:a=>{this.draft=a.target.value,this.requestUpdate()},send:this.send})}
9
+ ${this.poweredBy?p`<footer><a href="https://osvi.ai" target="_blank" rel="noopener noreferrer">${zs}<span>${t.poweredBy}</span></a></footer>`:m}`}},j.clientFactory=ti,j.properties={themeAttribute:{attribute:"theme"},stringsAttribute:{attribute:"strings"}},j.styles=Gt`
10
+ :host { --p:var(--osvi-color-primary,#4f46e5); --bg:var(--osvi-color-background,#fff); --surface:var(--osvi-color-surface,#f4f4f5); --text:var(--osvi-color-text,#18181b);
11
+ --ub:var(--osvi-color-user-bubble,var(--p)); --ab:var(--osvi-color-assistant-bubble,var(--surface)); --r:var(--osvi-radius,14px);
12
+ --sub:color-mix(in srgb,var(--text) 58%,var(--bg)); --line:color-mix(in srgb,var(--text) 11%,var(--bg));
13
+ display:flex; flex-direction:column; height:100%; min-height:260px; color:var(--text); background:var(--bg); font-family:inherit; font-size:14px; line-height:1.5; border-radius:var(--r); overflow:hidden; }
14
+ * { box-sizing:border-box; } h2,p { margin:0; }
15
+ button,textarea { font:inherit; color:inherit; } button { cursor:pointer; } button:disabled { cursor:default; opacity:.45; }
16
+ button:focus-visible,textarea:focus-visible,a:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:2px; }
17
+ .sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; }
18
+ header { display:flex; align-items:center; gap:12px; padding:14px 12px 14px 16px; border-bottom:1px solid var(--line); }
19
+ .avatar { width:38px; height:38px; border-radius:50%; flex:none; object-fit:cover; display:grid; place-items:center; background:var(--p); color:#fff; font-weight:700; font-size:15px; }
20
+ .heading { flex:1; min-width:0; } h2 { font-size:15px; line-height:1.3; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
21
+ .heading p,.heading small { display:block; font-size:12.5px; color:var(--sub); }
22
+ .heading small { color:var(--p); font-weight:600; }
23
+ .icon { width:34px; height:34px; border:0; border-radius:10px; background:transparent; color:var(--sub); display:grid; place-items:center; flex:none; }
24
+ .icon:hover:not(:disabled) { background:var(--surface); color:var(--text); } .icon svg { width:18px; height:18px; }
25
+ .transcript { flex:1; overflow:auto; padding:18px 16px; min-height:0; display:flex; flex-direction:column; gap:10px; }
26
+ .empty { margin:auto; color:var(--sub); text-align:center; }
27
+ .bubble { width:fit-content; max-width:84%; padding:10px 14px; border-radius:var(--r); border-bottom-left-radius:6px; background:var(--ab); overflow-wrap:anywhere; white-space:pre-wrap; }
28
+ .bubble.user { align-self:flex-end; color:#fff; background:var(--ub); border-bottom-left-radius:var(--r); border-bottom-right-radius:6px; }
29
+ .bubble a { color:inherit; } .team { display:block; font-size:11px; font-weight:600; color:var(--p); margin-bottom:2px; }
30
+ .failed { display:flex; align-items:center; gap:8px; font-size:12px; margin-top:6px; } .failed button { border:0; background:rgb(255 255 255/.2); border-radius:8px; padding:2px 8px; }
31
+ .divider { display:flex; align-items:center; gap:10px; color:var(--sub); font-size:12px; } .divider::before,.divider::after { content:""; flex:1; height:1px; background:var(--line); }
32
+ .typing { display:inline-flex; gap:4px; padding:12px 14px; background:var(--ab); border-radius:var(--r); border-bottom-left-radius:6px; width:fit-content; }
33
+ .typing i { width:6px; height:6px; border-radius:50%; background:var(--sub); animation:osvi-dot 1.2s infinite; } .typing i:nth-child(2) { animation-delay:.15s; } .typing i:nth-child(3) { animation-delay:.3s; }
34
+ @keyframes osvi-dot { 0%,60%,100% { opacity:.35; transform:none; } 30% { opacity:1; transform:translateY(-3px); } }
35
+ osvi-buttons,osvi-carousel,osvi-date-picker { display:block; max-width:100%; }
36
+ .status { padding:0 16px; font-size:12.5px; color:var(--sub); display:flex; gap:8px; align-items:center; } .status:empty { display:none; }
37
+ .status button { border:1px solid var(--line); background:var(--bg); border-radius:8px; padding:3px 10px; }
38
+ .composer { margin:10px 12px; display:flex; align-items:flex-end; gap:8px; border:1px solid var(--line); border-radius:18px; padding:6px 6px 6px 14px; background:var(--surface); }
39
+ .composer:focus-within { border-color:var(--p); box-shadow:0 0 0 3px color-mix(in srgb,var(--p) 18%,transparent); }
40
+ textarea { flex:1; min-width:0; border:0; outline:0; background:transparent; resize:none; min-height:24px; max-height:120px; padding:6px 0; field-sizing:content; }
41
+ textarea::placeholder { color:var(--sub); } textarea:focus-visible { outline:0; }
42
+ .send { width:36px; height:36px; border:0; border-radius:50%; background:var(--p); color:#fff; display:grid; place-items:center; flex:none; } .send svg { width:17px; height:17px; }
43
+ footer { padding:0 16px 12px; text-align:center; font-size:11.5px; } footer a { color:var(--sub); text-decoration:none; display:inline-flex; align-items:center; gap:6px; }
44
+ footer a:hover { color:var(--text); } footer svg { width:14px; height:14px; flex:none; }
45
+ @media (prefers-reduced-motion:reduce) { .typing i { animation:none; } }
46
+ `,j);v([b({attribute:"agent-id"})],y.prototype,"agentId"),v([b({attribute:"base-url"})],y.prototype,"baseUrl"),v([b({attribute:!1})],y.prototype,"client"),v([b({attribute:!1})],y.prototype,"theme"),v([b({attribute:!1})],y.prototype,"variants"),v([b({attribute:!1})],y.prototype,"strings"),v([b({attribute:"powered-by",converter:bi})],y.prototype,"poweredBy"),v([b({attribute:"new-chat",converter:bi})],y.prototype,"newChat"),v([b({attribute:"new-chat-history"})],y.prototype,"newChatHistory"),v([b({attribute:!1})],y.prototype,"header"),v([b({type:Boolean})],y.prototype,"closable"),v([b({attribute:"header-title"})],y.prototype,"headerTitle"),v([b({attribute:"header-subtitle"})],y.prototype,"headerSubtitle"),v([b({attribute:"header-avatar"})],y.prototype,"headerAvatar"),v([b({attribute:"primary-color"})],y.prototype,"primaryColor"),v([b()],y.prototype,"radius"),v([b()],y.prototype,"mode"),v([b()],y.prototype,"buttons"),v([b()],y.prototype,"carousel"),v([N()],y.prototype,"chatState"),v([N()],y.prototype,"draft"),v([N()],y.prototype,"busy"),v([N()],y.prototype,"typed");let yi=y;function L(s,t){typeof customElements>"u"||customElements.get(s)||customElements.define(s,t)}const Dt=s=>we(As(s)),pe=Gt`
47
+ :host { --p:${Dt("primary")}; --bg:${Dt("background")}; --surface:${Dt("surface")}; --text:${Dt("text")}; --r:var(--osvi-radius,14px);
48
+ --sub:color-mix(in srgb,var(--text) 58%,var(--bg)); --line:color-mix(in srgb,var(--text) 11%,var(--bg));
49
+ display:block; font:inherit; color:var(--text); }
50
+ * { box-sizing:border-box; }
51
+ p { margin:0 0 6px; } .label { font-weight:600; } .description { color:var(--sub); font-size:13px; }
52
+ .answer { display:inline-block; margin-top:2px; padding:4px 10px; border-radius:999px; background:color-mix(in srgb,var(--p) 12%,var(--bg)); color:var(--p); font-weight:600; font-size:13px; }
53
+ .sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; }
54
+ button { font:inherit; color:inherit; cursor:pointer; }
55
+ button:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:2px; }
56
+ button:disabled { opacity:.45; cursor:default; }
57
+ small { display:block; color:var(--sub); font-size:12px; font-weight:400; }
58
+ .chips { display:flex; flex-wrap:wrap; gap:8px; }
59
+ .chips button { border:1.5px solid color-mix(in srgb,var(--p) 55%,var(--line)); background:var(--bg); color:var(--p); border-radius:999px; padding:7px 14px; font-weight:600; font-size:13px; text-align:center; }
60
+ .chips button:hover:not(:disabled) { background:color-mix(in srgb,var(--p) 10%,var(--bg)); }
61
+ .text { display:grid; gap:1px; min-width:0; }
62
+ .chips small { color:inherit; opacity:.8; }
63
+ .list { display:grid; gap:6px; }
64
+ .list > button { display:flex; justify-content:space-between; align-items:center; gap:10px; width:100%; text-align:left; border:1px solid var(--line); background:var(--bg); border-radius:12px; padding:10px 12px; }
65
+ .list > button:hover:not(:disabled) { border-color:var(--p); }
66
+ .list > button svg { width:16px; height:16px; flex:none; color:var(--sub); }
67
+ .card { background:var(--bg); border:1px solid var(--line); border-radius:var(--r); overflow:hidden; box-shadow:0 6px 18px -10px rgb(16 18 30/.35); }
68
+ .card .body { padding:10px 12px 12px; display:grid; gap:4px; } .card h3 { margin:0; font-size:14px; } .card p { margin:0; color:var(--sub); font-size:12.5px; }
69
+ .image { aspect-ratio:16 / 9; max-width:100%; display:grid; place-items:center; overflow:hidden; background:var(--surface); color:var(--sub); font-size:12px; }
70
+ .image img { width:100%; height:100%; object-fit:cover; display:block; }
71
+ .primary { justify-self:start; margin-top:6px; border:0; border-radius:10px; background:var(--p); color:#fff; font-weight:600; font-size:13px; padding:8px 14px; }
72
+ .list .card { display:grid; grid-template-columns:minmax(0,88px) 1fr; } .list .card .image { aspect-ratio:auto; height:100%; min-height:88px; }
73
+ .list .card:not(:has(.image)) { grid-template-columns:1fr; }
74
+ .navigation { display:flex; align-items:center; justify-content:space-between; gap:8px; margin:10px 0 0; }
75
+ .round { width:32px; height:32px; border-radius:50%; border:1px solid var(--line); background:var(--bg); display:grid; place-items:center; padding:0; flex:none; }
76
+ .round:hover:not(:disabled) { border-color:var(--p); } .round svg { width:15px; height:15px; }
77
+ .dots { display:flex; gap:5px; align-items:center; } .dots i { width:6px; height:6px; border-radius:3px; background:var(--line); transition:width .2s; } .dots i.on { width:16px; background:var(--p); }
78
+ .calendar { border:1px solid var(--line); border-radius:var(--r); padding:10px; background:var(--bg); display:grid; gap:6px; }
79
+ .calendar .navigation { margin:0; font-weight:600; font-size:13px; }
80
+ .days, .weekdays { display:grid; grid-template-columns:repeat(7, minmax(0, 1fr)); gap:2px 0; text-align:center; }
81
+ .weekdays { color:var(--sub); font-size:11px; }
82
+ .days button { border:0; background:transparent; height:30px; border-radius:8px; padding:0; font-size:12.5px; font-variant-numeric:tabular-nums; }
83
+ .days button:hover:not(:disabled) { background:var(--surface); }
84
+ .days button.today { box-shadow:inset 0 0 0 1.5px var(--line); }
85
+ .days button.in { background:color-mix(in srgb,var(--p) 14%,transparent); border-radius:0; }
86
+ .days button[aria-pressed="true"] { background:var(--p); color:#fff; }
87
+ .days button.start:not(.end) { border-radius:8px 0 0 8px; } .days button.end:not(.start) { border-radius:0 8px 8px 0; }
88
+ .hint { color:var(--sub); font-size:12px; margin:0; }
89
+ @media (prefers-reduced-motion:reduce) { .dots i { transition:none; } }
90
+ `;var Vs=Object.defineProperty,Bt=(s,t,e,i)=>{for(var n=void 0,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=o(t,e,n)||n);return n&&Vs(t,e,n),n};class et extends Z{constructor(){super(...arguments),this.interaction=null,this.disabled=!1,this.baseUrl=""}get live(){return!this.disabled&&this.interaction?.interaction_status==="pending"}get valid(){const t=this.interaction;return!!t&&t.tool_type===this.toolType&&rs(t,t.presentation)}respond(t){!this.interaction||!this.live||!this.valid||this.dispatchEvent(new CustomEvent("osvi-respond",{bubbles:!0,composed:!0,detail:{interactionId:this.interaction.interaction_id,response:t}}))}updated(t){t.has("theme")&&le(this,this.theme)}}Bt([b({attribute:!1})],et.prototype,"interaction"),Bt([b({type:Boolean})],et.prototype,"disabled"),Bt([b({attribute:!1})],et.prototype,"theme"),Bt([b({attribute:"base-url"})],et.prototype,"baseUrl");var Ws=Object.defineProperty,Gs=(s,t,e,i)=>{for(var n=void 0,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=o(t,e,n)||n);return n&&Ws(t,e,n),n};const me=class me extends et{constructor(){super(...arguments),this.toolType="ui_buttons",this.variant="chips"}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return p`<p>${t.content}</p>`;const e=t.presentation,i=t.response_payload?.kind==="text"?t.response_payload.value:e.options.find(n=>n.id===(t.response_payload?.kind==="selection"?t.response_payload.value:t.selected_option_id))?.label;return p`<p class="label">${e.label}</p>${e.description?p`<p class="description">${e.description}</p>`:m}
91
+ ${this.live?p`<div role="group" aria-label="Options" class=${this.variant} @keydown=${this.onKey}>
92
+ ${e.options.map(n=>p`<button type="button" @click=${()=>this.pick(n.id,n.allow_input,n.input_placeholder)}><span class="text"><span>${n.label}</span>${n.description?p`<small>${n.description}</small>`:m}</span>${this.variant==="list"?ue:m}</button>`)}
93
+ </div>`:i?p`<p class="answer">${i}</p>`:m}`}pick(t,e,i){!this.live||!this.valid||!this.interaction||(this.interaction.schema_version===2&&e?this.dispatchEvent(new CustomEvent("osvi-request-input",{bubbles:!0,composed:!0,detail:{interactionId:this.interaction.interaction_id,placeholder:i}})):this.respond({kind:"selection",value:t}))}onKey(t){if(!["ArrowDown","ArrowUp","ArrowRight","ArrowLeft"].includes(t.key))return;const e=[...this.renderRoot.querySelectorAll("button")],i=e.indexOf(this.renderRoot.activeElement),n=t.key==="ArrowDown"||t.key==="ArrowRight"?1:-1;e[(i+n+e.length)%e.length]?.focus(),t.preventDefault()}};me.styles=pe;let xt=me;Gs([b()],xt.prototype,"variant");var Ks=Object.defineProperty,fe=(s,t,e,i)=>{for(var n=void 0,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=o(t,e,n)||n);return n&&Ks(t,e,n),n};const be=class be extends et{constructor(){super(...arguments),this.toolType="ui_carousel",this.variant="slider",this.index=0,this.imageFailed=new Set,this.suppressPointerClick=!1}willUpdate(t){t.has("interaction")&&(this.index=0,this.imageFailed=new Set,this.pointerStart=void 0,this.suppressPointerClick=!1)}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return p`<p>${t.content}</p>`;const e=t.presentation,i=e.items.find(n=>n.id===(t.response_payload?.kind==="selection"?t.response_payload.value:t.selected_option_id));return p`<p class="label">${e.label}</p>${e.description?p`<p class="description">${e.description}</p>`:m}
94
+ ${this.live?this.variant==="list"?p`<div class="list">${e.items.map((n,r)=>this.card(n,r))}</div>`:p`<div @pointerdown=${n=>{this.pointerStart=n.clientX,this.suppressPointerClick=!1}} @pointerup=${n=>{this.pointerStart!==void 0&&Math.abs(n.clientX-this.pointerStart)>40&&(this.suppressPointerClick=!0,this.navigate(n.clientX<this.pointerStart?1:-1,e.items.length)),this.pointerStart=void 0}} @pointercancel=${()=>{this.pointerStart=void 0}}>${this.card(e.items[this.index],this.index)}</div>
95
+ <div class="navigation"><button type="button" class="round" aria-label="Previous card" ?disabled=${this.index===0} @click=${()=>this.navigate(-1,e.items.length)}>${gi}</button>
96
+ <span class="dots" aria-hidden="true">${e.items.map((n,r)=>p`<i class=${r===this.index?"on":""}></i>`)}</span><span class="sr" aria-live="polite">${this.index+1} of ${e.items.length}</span>
97
+ <button type="button" class="round" aria-label="Next card" ?disabled=${this.index===e.items.length-1} @click=${()=>this.navigate(1,e.items.length)}>${ue}</button></div>`:i?p`<p class="answer">${i.title}</p>`:m}`}navigate(t,e){this.index=Math.max(0,Math.min(e-1,this.index+t))}select(t,e){if(this.suppressPointerClick&&t.detail!==0){this.suppressPointerClick=!1,t.preventDefault(),t.stopPropagation();return}this.respond({kind:"selection",value:e})}card(t,e){const i=t.image;return p`<article class="card">${i&&He(i.url)?p`<div class="image">${this.imageFailed.has(e)?p`<span role="img" aria-label="Image unavailable">Image unavailable</span>`:p`<img src=${this.baseUrl.replace(/\/$/,"")+i.url} alt=${i.alt} referrerpolicy="no-referrer" loading="lazy" @error=${()=>{this.imageFailed=new Set([...this.imageFailed,e])}}>`}</div>`:m}
98
+ <div class="body"><h3>${t.title}</h3>${t.description?p`<p>${t.description}</p>`:m}
99
+ <button type="button" class="primary" @click=${n=>this.select(n,t.id)}>${t.action_label??"Select"}</button></div></article>`}};be.styles=pe;let it=be;fe([b()],it.prototype,"variant"),fe([N()],it.prototype,"index"),fe([N()],it.prototype,"imageFailed");var Ys=Object.defineProperty,Lt=(s,t,e,i)=>{for(var n=void 0,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=o(t,e,n)||n);return n&&Ys(t,e,n),n};const vi=s=>`${String(s.getFullYear()).padStart(4,"0")}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`,jt=()=>vi(new Date),_i=s=>{const t=new Date(0);return t.setHours(0,0,0,0),t.setFullYear(Number(s.slice(0,4)),Number(s.slice(5,7))-1,Number(s.slice(8,10))),t},st=s=>s.slice(0,7),ye=class ye extends et{constructor(){super(...arguments),this.toolType="ui_date_picker",this.variant="grid",this.month=st(jt()),this.start="",this.end=""}earliest(t){return t.min_date&&t.min_date>jt()?t.min_date:jt()}willUpdate(t){t.has("interaction")&&(this.start="",this.end="",this.valid&&(this.month=st(this.earliest(this.interaction.presentation))))}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return p`<p>${t.content}</p>`;const e=t.presentation,i=t.response_payload,n=i?.kind==="date_range"?`${i.value.start_date} – ${i.value.end_date}`:i?.kind==="date"||i?.kind==="text"?i.value:t.selected_option_id;if(!this.live)return p`<p class="label">${e.label}</p>${e.description?p`<p class="description">${e.description}</p>`:m}${n?p`<p class="answer">${n}</p>`:m}`;const r=_i(`${this.month}-01`),o=new Date(r);o.setMonth(o.getMonth()+1,0);const a=this.earliest(e),c=Array.from({length:o.getDate()},(d,h)=>`${this.month}-${String(h+1).padStart(2,"0")}`),l=e.selection_mode==="range"?this.start?this.end?`${this.start} – ${this.end}`:`Check-in: ${this.start}. Choose check-out.`:"Choose check-in, then check-out.":this.start,f=jt();return p`<p class="label">${e.label}</p>${e.description?p`<p class="description">${e.description}</p>`:m}
100
+ <div class="calendar"><div class="navigation"><button type="button" class="round" aria-label="Previous month" ?disabled=${this.month<=st(a)} @click=${()=>this.moveMonth(-1,e)}>${gi}</button>
101
+ <span aria-live="polite">${r.toLocaleDateString(void 0,{month:"long",year:"numeric"})}</span>
102
+ <button type="button" class="round" aria-label="Next month" ?disabled=${!!e.max_date&&this.month>=st(e.max_date)} @click=${()=>this.moveMonth(1,e)}>${ue}</button></div>
103
+ <div class="weekdays" aria-hidden="true">${["Su","Mo","Tu","We","Th","Fr","Sa"].map(d=>p`<span>${d}</span>`)}</div>
104
+ <div class="days" role="group" aria-label="Choose date" @keydown=${this.onKey}>
105
+ ${Array.from({length:r.getDay()},()=>p`<span></span>`)}
106
+ ${c.map((d,h)=>p`<button type="button" class=${[d===f?"today":"",d===this.start?"start":"",d===this.end?"end":"",this.start&&this.end&&d>this.start&&d<this.end?"in":""].filter(Boolean).join(" ")} aria-label=${d} aria-pressed=${d===this.start||d===this.end} ?disabled=${d<a||!!e.max_date&&d>e.max_date} @click=${()=>this.pick(d,e)}>${h+1}</button>`)}
107
+ </div><p class="hint" aria-live="polite">${l}</p>
108
+ <button type="button" class="primary" ?disabled=${!this.start||e.selection_mode==="range"&&(!this.end||this.start>=this.end)} @click=${()=>this.confirm(e)}>${e.confirm_label??"Confirm date"}</button></div>`}moveMonth(t,e){const i=_i(`${this.month}-01`);i.setMonth(i.getMonth()+t);const n=st(vi(i));n>=st(this.earliest(e))&&(!e.max_date||n<=st(e.max_date))&&(this.month=n)}pick(t,e){!this.live||!this.valid||!q(t)||t<this.earliest(e)||e.max_date&&t>e.max_date||(e.selection_mode==="single"||!this.start||this.end||t<=this.start?(this.start=t,this.end=""):this.end=t)}confirm(t){!q(this.start)||this.start<this.earliest(t)||t.max_date&&this.start>t.max_date||(t.selection_mode==="single"?this.respond({kind:"date",value:this.start}):q(this.end)&&this.start<this.end&&(!t.max_date||this.end<=t.max_date)&&this.respond({kind:"date_range",value:{start_date:this.start,end_date:this.end}}))}onKey(t){const i={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7}[t.key];if(i===void 0)return;const n=[...this.renderRoot.querySelectorAll(".days button")],r=n.indexOf(this.renderRoot.activeElement);if(r<0)return;let o=r+i;for(;o>=0&&o<n.length&&n[o]?.disabled;)o+=i>0?1:-1;n[o]?.focus(),t.preventDefault()}};ye.styles=pe;let W=ye;Lt([b()],W.prototype,"variant"),Lt([N()],W.prototype,"month"),Lt([N()],W.prototype,"start"),Lt([N()],W.prototype,"end"),L("osvi-chat",yi),L("osvi-buttons",xt),L("osvi-carousel",it),L("osvi-date-picker",W);const C=s=>typeof s=="string"?s:void 0,dt=s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},Ht=s=>s===!0||s==="true"?!0:s===!1||s==="false"?!1:void 0;function ge(s,t){const e=dt(t),i=s?.dataset??{},n=dt(e.theme),r=dt(e.variants),o=dt(e.header),a={},c=dt(n.colors);for(const h of["primary","background","surface","text","userBubble","assistantBubble"]){const u=C(c[h]);u!==void 0&&(a[h]=u)}i.primaryColor&&(a.primary=i.primaryColor);const l=Mt(i.radius)??(typeof n.radius=="number"&&Number.isInteger(n.radius)&&n.radius>=0&&n.radius<=99?n.radius:Mt(C(n.radius))),f=$(i.mode,["light","dark"])??$(C(n.mode),["light","dark"]),d={};for(const[h,u]of Object.entries(dt(e.strings)))typeof u=="string"&&(d[h]=u);return{agentId:i.agent??C(e.agentId)??"",baseUrl:Ut(i.baseUrl)??Ut(C(e.baseUrl)),position:$(i.position,["right","left"])??$(C(e.position),["right","left"])??"right",launcher:$(i.launcher,["bubble","none"])??$(C(e.launcher),["bubble","none"])??"bubble",greeting:i.greeting??C(e.greeting),theme:{colors:a,...l!==void 0?{radius:l}:{},...f?{mode:f}:{}},variants:{buttons:$(i.buttons,["chips","list"])??$(C(r.buttons),["chips","list"]),carousel:$(i.carousel,["slider","list"])??$(C(r.carousel),["slider","list"])},strings:d,poweredBy:Ht(i.poweredBy)??Ht(e.poweredBy)??!0,newChat:Ht(i.newChat)??Ht(e.newChat)??!0,newChatHistory:$(i.newChatHistory,["clear","keep"])??$(C(e.newChatHistory),["clear","keep"])??"clear",header:{title:i.title??C(o.title),subtitle:i.subtitle??C(o.subtitle),avatarUrl:de(i.avatar)??de(C(o.avatarUrl))},auth:e.auth}}const Ft=class Ft extends Z{constructor(){super(...arguments),this.config={agentId:""},this.client=null,this.opened=!1,this.badge=0,this.greetingDismissed=!1,this.onToggle=()=>{},this.onClose=()=>{},this.onDismiss=()=>{}}get panel(){return this.renderRoot.querySelector("osvi-chat")}focusLauncher(){this.renderRoot.querySelector(".launcher")?.focus()}render(){const t=this.config;return p`${t.greeting&&!this.greetingDismissed&&!this.opened?p`<div class="greeting" part="greeting">${t.greeting}<button type="button" aria-label="Dismiss greeting" @click=${this.onDismiss}>${fi}</button></div>`:m}
109
+ ${t.launcher!=="none"?p`<button class="launcher" part="launcher" type="button" aria-label=${this.opened?"Close chat":"Open chat"} aria-expanded=${this.opened} @click=${this.onToggle}>${this.opened?js:Ls}${this.badge>0&&!this.opened?p`<span class="badge" part="badge" role="status" aria-label=${`${this.badge} unread messages`}>${this.badge}</span>`:m}</button>`:m}
110
+ ${this.client?p`<div class="panel" part="panel" ?hidden=${!this.opened}><osvi-chat .client=${this.client} .theme=${t.theme??{}} .variants=${t.variants??{}} .strings=${t.strings??{}} .header=${t.header??{}} .poweredBy=${t.poweredBy??!0} .newChat=${t.newChat??!0} .newChatHistory=${t.newChatHistory??"clear"} closable ?hidden=${!this.opened} @osvi-close=${this.onClose}></osvi-chat></div>`:m}`}};Ft.properties={config:{attribute:!1},client:{attribute:!1},opened:{type:Boolean},badge:{type:Number},greetingDismissed:{type:Boolean}},Ft.styles=Gt`
111
+ :host { --p:var(--osvi-color-primary,#4f46e5); position:fixed; bottom:20px; right:20px; z-index:2147483000; font-family:inherit; font-size:14px; line-height:1.5; display:flex; flex-direction:column; align-items:flex-end; }
112
+ :host([position="left"]) { right:auto; left:20px; align-items:flex-start; }
113
+ * { box-sizing:border-box; } button { font:inherit; cursor:pointer; }
114
+ button:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:3px; }
115
+ .launcher { position:relative; border:0; border-radius:50%; width:58px; height:58px; background:var(--p); color:#fff; display:grid; place-items:center;
116
+ box-shadow:0 10px 24px -6px color-mix(in srgb,var(--p) 60%,transparent),0 2px 6px rgb(0 0 0/.18); transition:transform .15s ease; }
117
+ .launcher:hover { transform:scale(1.06); } .launcher:active { transform:scale(.96); }
118
+ .launcher svg { width:26px; height:26px; }
119
+ .badge { position:absolute; top:-2px; right:-2px; min-width:20px; height:20px; border-radius:10px; background:#ef4444; color:#fff; font:700 11px/20px system-ui,sans-serif; text-align:center; padding:0 5px; border:2px solid #fff; }
120
+ .greeting { position:relative; background:#fff; color:#16171d; border-radius:14px; padding:10px 14px; margin-bottom:12px; max-width:240px; font-size:13px;
121
+ box-shadow:0 10px 30px -10px rgb(16 18 30/.35),0 0 0 1px rgb(16 18 30/.08); }
122
+ .greeting button { position:absolute; top:-8px; left:-8px; width:22px; height:22px; border:0; border-radius:50%; background:#fff; color:#555; box-shadow:0 1px 4px rgb(0 0 0/.25); display:grid; place-items:center; padding:0; }
123
+ .greeting button svg { width:12px; height:12px; }
124
+ .panel { position:absolute; bottom:76px; right:0; width:380px; height:min(620px,calc(100dvh - 100px)); border-radius:20px; overflow:hidden;
125
+ box-shadow:0 24px 60px -12px rgb(16 18 30/.32),0 0 0 1px rgb(16 18 30/.08); animation:osvi-in .18s ease-out; }
126
+ :host([position="left"]) .panel { right:auto; left:0; } .panel[hidden] { display:none; }
127
+ .panel osvi-chat { border-radius:0; }
128
+ @keyframes osvi-in { from { opacity:0; transform:translateY(8px) scale(.98); } to { opacity:1; transform:none; } }
129
+ @media (prefers-reduced-motion:reduce) { .launcher,.panel { transition:none; animation:none; } }
130
+ @media(max-width:639px) { .panel,:host([position="left"]) .panel { position:fixed; inset:0; width:100%; height:100dvh; border-radius:0; box-shadow:none; } }
131
+ `;let zt=Ft;customElements.get("osvi-chat-widget")||customElements.define("osvi-chat-widget",zt);const wi=s=>`osvi.chat.greetingDismissed.${s}`,kt=s=>`osvi.chat.seen.${s}`,Js=3e4;let nt=null;function Xs(s){if(L("osvi-chat",yi),L("osvi-buttons",xt),L("osvi-carousel",it),L("osvi-date-picker",W),L("osvi-chat-widget",zt),nt)return nt;let t=ge(null,s),e=null,i=null,n,r=!1,o=!1,a=-1/0,c=0,l=0,f=null;const d=Ke();let h=ae(),u=new Set,g=new Set;const x=w=>new Set([...w.items.flatMap(M=>M.kind==="message"&&M.role!=="user"?[`message:${M.serverId??M.id}`]:[]),...w.activeInteraction?[`interaction:${w.activeInteraction.interaction_id}`]:[]]),G=w=>{if(!e)return;const M=x(w);if(r){let I=T(h.get(kt(t.agentId)));for(const _ of w.items){const U=T(_.kind==="message"&&_.role!=="user"?_.serverId:_.kind==="interaction"?_.interaction.id:void 0);U!==null&&(I===null||P(U,I)>0)&&(I=U)}const K=T(h.get(kt(t.agentId)));I!==null&&(K===null||P(I,K)>0)&&h.set(kt(t.agentId),I),g.clear(),e.badge=0}else{const I=T(h.get(kt(t.agentId))),K=new Set(w.items.flatMap(_=>{if(_.kind!=="message"||_.role==="user")return[];const U=T(_.serverId);return U!==null&&I!==null&&P(U,I)<=0?[]:[`message:${_.serverId??_.id}`]}));if(w.activeInteraction){const _=T(w.activeInteraction.id);(_===null||I===null||P(_,I)>0)&&K.add(`interaction:${w.activeInteraction.interaction_id}`)}for(const _ of M)!u.has(_)&&K.has(_)&&g.add(_);e.badge=g.size}u=M},At=async()=>{if(t.auth?.mode==="server"||!e||o||!h.get(Ot(t.agentId)))return;a=Date.now();const w=c,M=++l;try{const I=await new Be(t.baseUrl??Je).bootstrap(t.agentId,lt(h));if(!e||c!==w||M!==l||o)return;const K=T(h.get(kt(t.agentId)));e.badge=K===null?0:(I.messages??[]).filter(_=>{if(!_||typeof _!="object")return!1;const U=_,ki=T(U.id);return U.role!=="user"&&U.role!=="system"&&ki!==null&&P(ki,K)>0}).length}catch{e&&c===w&&M===l&&!o&&(e.badge=0)}},$i=()=>{document.visibilityState==="visible"&&Date.now()-a>=Js&&At()},qt=()=>{r&&window.innerWidth<640?(f===null&&(f=document.documentElement.style.overflow),document.documentElement.style.overflow="hidden"):f!==null&&(document.documentElement.style.overflow=f,f=null)},xi=w=>{w.key==="Escape"&&r&&(O.close(),e?.focusLauncher())},O={open(){if(!e||r)return;r=!0,o=!0,e.opened=!0,e.badge=0,g.clear(),qt(),i||(i=ti({agentId:t.agentId,baseUrl:t.baseUrl,auth:t.auth,store:h}),e.client=i,u=x(i.getState()),n=i.subscribe(G),i.start().catch(()=>{})),G(i.getState());const w=e;w.updateComplete.then(()=>{e===w&&r&&w.panel?.focusActiveInteraction()})},close(){!e||!r||(r=!1,e.opened=!1,qt(),e.focusLauncher())},toggle(){r?O.close():O.open()},destroy(){O.close(),++c,n?.(),n=void 0,i?.destroy(),i=null,e?.remove(),e=null,document.removeEventListener("visibilitychange",$i),document.removeEventListener("keydown",xi),window.removeEventListener("resize",qt),delete window.__osviChatWidget,nt===O&&(nt=null)},init(w={}){if(!e&&!(nt&&nt!==O)){if(t=ge(null,{...t,...w}),!t.agentId){console.error("[osvi-chat] data-agent is required");return}h=t.auth?.mode==="server"?ae():d,r=!1,o=!1,a=-1/0,u=new Set,g=new Set,++c,e=document.createElement("osvi-chat-widget"),e.config=t,e.setAttribute("position",t.position??"right"),le(e,t.theme),e.greetingDismissed=!!h.get(wi(t.agentId)),e.onToggle=O.toggle,e.onClose=O.close,e.onDismiss=()=>{e&&(e.greetingDismissed=!0,h.set(wi(t.agentId),"true"))},document.body.append(e),nt=O,window.__osviChatWidget=!0,document.addEventListener("visibilitychange",$i),document.addEventListener("keydown",xi),window.addEventListener("resize",qt),At()}}};return O.init(),O}const St=window,Zs=document.currentScript;if(!St.__osviChatWidget){const s=ge(Zs,St.OsviChatConfig);if(!s.agentId)console.error("[osvi-chat] data-agent is required");else{const t=Array.isArray(St.OsviChat?.q)?[...St.OsviChat.q]:[],e=Xs(s);St.OsviChat=e;for(const i of t){if(!Array.isArray(i))continue;const n=i[0];(n==="open"||n==="close"||n==="toggle")&&e[n]()}}}})();
132
+ //# sourceMappingURL=widget.js.map