@osvi-ai/chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) 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-BsRyQwUM.js +1331 -0
  6. package/dist/index-BsRyQwUM.js.map +1 -0
  7. package/dist/types/core/client.d.ts +65 -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/index.d.ts +9 -0
  22. package/dist/types/ui/osvi-chat.d.ts +69 -0
  23. package/dist/types/ui/panel/attrs.d.ts +6 -0
  24. package/dist/types/ui/panel/composer.d.ts +10 -0
  25. package/dist/types/ui/panel/linkify.d.ts +7 -0
  26. package/dist/types/ui/panel/transcript.d.ts +4 -0
  27. package/dist/types/ui/strings.d.ts +27 -0
  28. package/dist/types/ui/styles.d.ts +1 -0
  29. package/dist/types/ui/theme.d.ts +22 -0
  30. package/dist/types/ui/tools/base.d.ts +14 -0
  31. package/dist/types/ui/tools/osvi-buttons.d.ts +10 -0
  32. package/dist/types/ui/tools/osvi-carousel.d.ts +16 -0
  33. package/dist/types/ui/tools/osvi-date-picker.d.ts +17 -0
  34. package/dist/types/widget/config.d.ts +22 -0
  35. package/dist/types/widget/index.d.ts +1 -0
  36. package/dist/types/widget/launcher.d.ts +35 -0
  37. package/dist/types/widget/widget.d.ts +13 -0
  38. package/dist/ui.js +49 -0
  39. package/dist/ui.js.map +1 -0
  40. package/dist/ui.mjs +570 -0
  41. package/dist/ui.mjs.map +1 -0
  42. package/dist/widget.js +59 -0
  43. package/dist/widget.js.map +1 -0
  44. 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/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 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', 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>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>${strings.sendFailed}</span><button type=\"button\" @click=${() => retry(item.id)}>${strings.retry}</button>` : 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>${strings.emptyState}</p>`}${state.awaitingReply ? html`<p aria-label=${strings.typing}>${strings.typing}<span aria-hidden=\"true\"> •••</span></p>` : nothing}`;\n}\n","import { html } from 'lit';\nimport { live } from 'lit/directives/live.js';\nimport type { ChatStrings } from '../strings';\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 aria-label=\"Message\" placeholder=${o.placeholder} .value=${live(o.draft)} ?disabled=${o.disabled} @input=${o.input} @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !o.disabled) { e.preventDefault(); o.send(); } }}></textarea><button type=\"button\" aria-label=${o.strings.send} ?disabled=${o.disabled || !o.draft.trim()} @click=${o.send}>${o.strings.send}</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';\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 { display:flex; flex-direction:column; height:100%; min-height:260px; color:var(--osvi-color-text,#18181b); background:var(--osvi-color-background,#fff); font:14px/1.5 system-ui,sans-serif; border-radius:var(--osvi-radius,10px); overflow:hidden; }\n header { display:flex; align-items:center; gap:10px; padding:14px; border-bottom:1px solid var(--osvi-color-surface,#f4f4f5); } header img { width:36px; height:36px; border-radius:50%; } .heading { flex:1; } h2,p { margin:0; } h2 { font-size:16px; } small { display:block; }\n .transcript { flex:1; overflow:auto; padding:16px; min-height:0; } .bubble { width:fit-content; max-width:85%; padding:10px 14px; margin:8px 0; border-radius:var(--osvi-radius,10px); background:var(--osvi-color-assistant-bubble,#f4f4f5); overflow-wrap:anywhere; white-space:pre-wrap; } .user { margin-left:auto; color:#fff; background:var(--osvi-color-user-bubble,#4f46e5); } .bubble a { color:inherit; } .divider { text-align:center; } .status { padding:0 14px; } .composer { display:flex; gap:8px; padding:14px; } textarea { flex:1; resize:vertical; min-width:0; } button,textarea { font:inherit; } button { cursor:pointer; } button:disabled { cursor:default; } footer { padding:0 14px 10px; text-align:center; } footer a { color:inherit; } osvi-buttons,osvi-carousel,osvi-date-picker { display:block; margin:8px 0; }\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: 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 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 return html`<header>${avatar ? html`<img src=${avatar} alt=\"\" referrerpolicy=\"no-referrer\">` : nothing}<div class=\"heading\"><h2>${this.headerTitle ?? this.header.title ?? s.agent?.name ?? strings.defaultTitle}</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\" ?disabled=${!client || this.sessionBusy} @click=${() => client && !this.sessionBusy && void this.run(() => client.newSession())}>${strings.newChat}</button>` : nothing}\n ${this.closable ? html`<button type=\"button\" aria-label=${strings.closeChat} @click=${() => this.dispatchEvent(new CustomEvent('osvi-close', { bubbles: true, composed: true }))}>×</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\">${strings.poweredBy}</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';\nexport const toolStyles = css`\n :host { display: block; font: inherit; color: ${unsafeCSS(cssVar('text'))}; background: ${unsafeCSS(cssVar('background'))}; }\n * { box-sizing: border-box; }\n button { font: inherit; color: inherit; background: ${unsafeCSS(cssVar('surface'))}; border: 1px solid currentColor; border-radius: var(--osvi-radius, 10px); padding: 10px 14px; cursor: pointer; }\n button:focus-visible { outline: 3px solid ${unsafeCSS(cssVar('primary'))}; outline-offset: 3px; }\n button:disabled { opacity: .5; cursor: default; }\n button[aria-pressed=\"true\"] { outline: 2px solid ${unsafeCSS(cssVar('primary'))}; }\n small { display: block; }\n .chips { display: flex; flex-wrap: wrap; gap: 8px; }\n .list { display: grid; gap: 6px; }\n .list button { width: 100%; text-align: left; }\n .card { background: ${unsafeCSS(cssVar('surface'))}; border-radius: var(--osvi-radius, 10px); padding: 12px; }\n .image { aspect-ratio: 16 / 9; display: grid; place-items: center; overflow: hidden; }\n .image img { width: 100%; height: 100%; object-fit: cover; }\n .navigation { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 10px 0; }\n .days, .weekdays { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 4px; text-align: center; }\n .days button { padding: 8px 0; }\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';\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>${p.label}</p>${p.description ? html`<p>${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>${o.label}</span>${o.description ? html`<small>${o.description}</small>` : nothing}</button>`)}\n </div>` : chosen ? html`<p>${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';\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>${p.label}</p>${p.description ? html`<p>${p.description}</p>` : nothing}\n ${!this.live ? chosen ? html`<p>${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\" aria-label=\"Previous card\" ?disabled=${this.index === 0} @click=${() => this.navigate(-1, p.items.length)}>Previous</button>\n <span aria-live=\"polite\">${this.index + 1} of ${p.items.length}</span>\n <button type=\"button\" aria-label=\"Next card\" ?disabled=${this.index === p.items.length - 1} @click=${() => this.navigate(1, p.items.length)}>Next</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 <h3>${item.title}</h3>${item.description ? html`<p>${item.description}</p>` : nothing}\n <button type=\"button\" @click=${(e: MouseEvent) => this.select(e, item.id)}>${item.action_label ?? 'Select'}</button></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';\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>${p.label}</p>${p.description ? html`<p>${p.description}</p>` : nothing}${chosen ? html`<p>${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 return html`<p>${p.label}</p>${p.description ? html`<p>${p.description}</p>` : nothing}\n <div class=\"navigation\"><button type=\"button\" aria-label=\"Previous month\" ?disabled=${this.month <= monthOf(earliest)} @click=${() => this.moveMonth(-1, p)}>Previous</button>\n <span aria-live=\"polite\">${first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</span>\n <button type=\"button\" aria-label=\"Next month\" ?disabled=${!!p.max_date && this.month >= monthOf(p.max_date)} @click=${() => this.moveMonth(1, p)}>Next</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\" 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 aria-live=\"polite\">${hint}</p>\n <button type=\"button\" ?disabled=${!this.start || p.selection_mode === 'range' && (!this.end || this.start >= this.end)} @click=${() => this.confirm(p)}>${p.confirm_label ?? 'Confirm date'}</button>`;\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","renderComposer","o","e","emptyState","bool","v","_OsviChat","_a","LitElement","client","typed","event","d","own","generation","attr","rawColors","mode","source","action","tool","id","log","avatar","el","createChatClient","css","__decorateClass","property","OsviChat","defineOnce","ctor","toolStyles","unsafeCSS","ToolElement","isInteractionPresentation","response","changed","_OsviButtons","chosen","allowInput","placeholder","list","at","step","OsviButtons","_OsviCarousel","n","delta","length","index","image","isProxyImageUrl","OsviCarousel","toIso","today","parseDate","iso","monthOf","_OsviDatePicker","first","earliest","days","_","hint","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,SAAS,WAAW,YAAY,WAAW,SAAS,WAAW,MAAM,WAAW,YAAY,WAAW,iBAAiB,UAAA,GACjIC,KAAQ,EAAE,MAAM,OAAO,IAAI,OAAO,IAAI,QAAQ,IAAI,QAAQ,MAAM,SAAA,GAChEC,IAAM,EAAE,SAAS,wBAAwB,YAAY,2BAA2B,SAAS,wBAAwB,MAAM,qBAAqB,YAAY,4BAA4B,iBAAiB,gCAAA,GAC9LC,IAAS,CAACC,MAAoC,OAAOF,EAAIE,CAAG,CAAC,KAAKL,EAAMK,CAAG,CAAC;AAClF,SAASC,EAAeC,GAAsD;AACnF,QAAMC,IAAS,EAAE,GAAID,GAAO,SAAS,SAASN,KAAOD,GAAQ,GAAGO,GAAO,OAAA,GACjEE,IAA8B,CAAA;AACpC,aAAWJ,KAAO,OAAO,KAAKF,CAAG,EAA6B,CAAAM,EAAIN,EAAIE,CAAG,CAAC,IAAIG,EAAOH,CAAG;AACxF,QAAMK,IAASH,GAAO,UAAU;AAChC,SAAAE,EAAI,eAAe,IAAI,OAAOC,KAAW,WAAW,GAAGA,CAAM,OAAOR,GAAMQ,CAAM,GACzED;AACT;AACO,SAASE,GAAuBJ,GAAsD;AAC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EAAA;AAAS,GAHC0C,EAGC,WAAA,SAAA;AACK3C,EAAA;AAAA,EAAhBxC,EAAA;AAAM,GAJImF,EAIM,WAAA,OAAA;AACA3C,EAAA;AAAA,EAAhBxC,EAAA;AAAM,GALImF,EAKM,WAAA,OAAA;AACA3C,EAAA;AAAA,EAAhBxC,EAAA;AAAM,GANImF,EAMM,WAAA,KAAA;ACXnBxC,EAAW,aAAaD,EAAQ;AAChCC,EAAW,gBAAgBe,CAAW;AACtCf,EAAW,iBAAiBuB,CAAY;AACxCvB,EAAW,oBAAoBwC,CAAc;"}
package/dist/widget.js ADDED
@@ -0,0 +1,59 @@
1
+ (function(){"use strict";var L;const xt=globalThis,qt=xt.ShadowRoot&&(xt.ShadyCSS===void 0||xt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Vt=Symbol(),ye=new WeakMap;let _e=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Vt)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(qt&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=ye.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&ye.set(e,t))}return t}toString(){return this.cssText}};const G=s=>new _e(typeof s=="string"?s:s+"",void 0,Vt),zt=(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,Vt)},bi=(s,t)=>{if(qt)s.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),n=xt.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},be=qt?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return G(e)})(s):s;const{is:vi,defineProperty:$i,getOwnPropertyDescriptor:wi,getOwnPropertyNames:Si,getOwnPropertySymbols:ki,getPrototypeOf:Ai}=Object,j=globalThis,ve=j.trustedTypes,Ci=ve?ve.emptyScript:"",xi=j.reactiveElementPolyfillSupport,dt=(s,t)=>s,It={toAttribute(s,t){switch(t){case Boolean:s=s?Ci: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}},Wt=(s,t)=>!vi(s,t),$e={attribute:!0,type:String,converter:It,reflect:!1,useDefault:!1,hasChanged:Wt};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),j.litPropertyMetadata??(j.litPropertyMetadata=new WeakMap);let nt=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=$e){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&&$i(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){const{get:n,set:r}=wi(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)??$e}static _$Ei(){if(this.hasOwnProperty(dt("elementProperties")))return;const t=Ai(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(dt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(dt("properties"))){const e=this.properties,i=[...Si(e),...ki(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(be(n))}else t!==void 0&&e.push(be(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 bi(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??Wt)(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){}};nt.elementStyles=[],nt.shadowRootOptions={mode:"open"},nt[dt("elementProperties")]=new Map,nt[dt("finalized")]=new Map,xi?.({ReactiveElement:nt}),(j.reactiveElementVersions??(j.reactiveElementVersions=[])).push("2.1.2");const ut=globalThis,we=s=>s,Et=ut.trustedTypes,Se=Et?Et.createPolicy("lit-html",{createHTML:s=>s}):void 0,ke="$lit$",F=`lit$${Math.random().toFixed(9).slice(2)}$`,Ae="?"+F,Ii=`<${Ae}>`,K=document,pt=()=>K.createComment(""),ft=s=>s===null||typeof s!="object"&&typeof s!="function",Gt=Array.isArray,Ei=s=>Gt(s)||typeof s?.[Symbol.iterator]=="function",Kt=`[
2
+ \f\r]`,gt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ce=/-->/g,xe=/>/g,Y=RegExp(`>|${Kt}(?:([^\\s"'>=/]+)(${Kt}*=${Kt}*(?:[^
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Ie=/'/g,Ee=/"/g,Te=/^(?:script|style|textarea|title)$/i,Ti=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),f=Ti(1),E=Symbol.for("lit-noChange"),m=Symbol.for("lit-nothing"),Pe=new WeakMap,J=K.createTreeWalker(K,129);function Re(s,t){if(!Gt(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return Se!==void 0?Se.createHTML(t):t}const Pi=(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 h,u,l=-1,d=0;for(;d<c.length&&(o.lastIndex=d,u=o.exec(c),u!==null);)d=o.lastIndex,o===gt?u[1]==="!--"?o=Ce:u[1]!==void 0?o=xe:u[2]!==void 0?(Te.test(u[2])&&(n=RegExp("</"+u[2],"g")),o=Y):u[3]!==void 0&&(o=Y):o===Y?u[0]===">"?(o=n??gt,l=-1):u[1]===void 0?l=-2:(l=o.lastIndex-u[2].length,h=u[1],o=u[3]===void 0?Y:u[3]==='"'?Ee:Ie):o===Ee||o===Ie?o=Y:o===Ce||o===xe?o=gt:(o=Y,n=void 0);const p=o===Y&&s[a+1].startsWith("/>")?" ":"";r+=o===gt?c+Ii:l>=0?(i.push(h),c.slice(0,l)+ke+c.slice(l)+F+p):c+F+(l===-2?a:p)}return[Re(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,[h,u]=Pi(t,e);if(this.el=mt.createElement(h,i),J.currentNode=this.el.content,e===2||e===3){const l=this.el.content.firstChild;l.replaceWith(...l.childNodes)}for(;(n=J.nextNode())!==null&&c.length<a;){if(n.nodeType===1){if(n.hasAttributes())for(const l of n.getAttributeNames())if(l.endsWith(ke)){const d=u[o++],p=n.getAttribute(l).split(F),g=/([.?@])?(.*)/.exec(d);c.push({type:1,index:r,name:g[2],strings:p,ctor:g[1]==="."?Oi:g[1]==="?"?Ui:g[1]==="@"?Mi:Tt}),n.removeAttribute(l)}else l.startsWith(F)&&(c.push({type:6,index:r}),n.removeAttribute(l));if(Te.test(n.tagName)){const l=n.textContent.split(F),d=l.length-1;if(d>0){n.textContent=Et?Et.emptyScript:"";for(let p=0;p<d;p++)n.append(l[p],pt()),J.nextNode(),c.push({type:2,index:++r});n.append(l[d],pt())}}}else if(n.nodeType===8)if(n.data===Ae)c.push({type:2,index:r});else{let l=-1;for(;(l=n.data.indexOf(F,l+1))!==-1;)c.push({type:7,index:r}),l+=F.length-1}r++}}static createElement(t,e){const i=K.createElement("template");return i.innerHTML=t,i}}function rt(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=rt(s,n._$AS(s,t.values),n,i)),t}class Ri{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??K).importNode(e,!0);J.currentNode=n;let r=J.nextNode(),o=0,a=0,c=i[0];for(;c!==void 0;){if(o===c.index){let h;c.type===2?h=new ot(r,r.nextSibling,this,t):c.type===1?h=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(h=new Ni(r,this,t)),this._$AV.push(h),c=i[++a]}o!==c?.index&&(r=J.nextNode(),o++)}return J.currentNode=K,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 ot{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=rt(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):Ei(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(K.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(Re(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(e);else{const r=new Ri(n,this),o=r.u(this.options);r.p(e),this.T(o),this._$AH=r}}_$AC(t){let e=Pe.get(t.strings);return e===void 0&&Pe.set(t.strings,e=new mt(t)),e}k(t){Gt(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 ot(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=we(t).nextSibling;we(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=rt(this,t,e,0),o=!ft(t)||t!==this._$AH&&t!==E,o&&(this._$AH=t);else{const a=t;let c,h;for(t=r[0],c=0;c<r.length-1;c++)h=rt(this,a[i+c],e,c),h===E&&(h=this._$AH[c]),o||(o=!ft(h)||h!==this._$AH[c]),h===m?t=m:t!==m&&(t+=(h??"")+r[c+1]),this._$AH[c]=h}o&&!n&&this.j(t)}j(t){t===m?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class Oi extends Tt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===m?void 0:t}}class Ui extends Tt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==m)}}class Mi extends Tt{constructor(t,e,i,n,r){super(t,e,i,n,r),this.type=5}_$AI(t,e=this){if((t=rt(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 Ni{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){rt(this,t)}}const Di={I:ot},Bi=ut.litHtmlPolyfillSupport;Bi?.(mt,ot),(ut.litHtmlVersions??(ut.litHtmlVersions=[])).push("3.3.3");const Li=(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 ot(t.insertBefore(pt(),r),r,void 0,e??{})}return n._$AI(s),n};const yt=globalThis;let X=class extends nt{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=Li(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return E}};X._$litElement$=!0,X.finalized=!0,yt.litElementHydrateSupport?.({LitElement:X});const ji=yt.litElementPolyfillSupport;ji?.({LitElement:X}),(yt.litElementVersions??(yt.litElementVersions=[])).push("4.2.2");const Fi={attribute:!0,type:String,converter:It,reflect:!1,hasChanged:Wt},Hi=(s=Fi,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 y(s){return(t,e)=>typeof e=="object"?Hi(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 M(s){return y({...s,state:!0,attribute:!1})}const qi="0.1.0",Vi=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"]),zi=new Set(["rate_limited","network","session_unavailable","stream_unavailable","token_failed"]);function k(s,t){const e=s&&Vi.has(s)?s:"unknown";return{code:e,message:t||e,retryable:zi.has(e)}}class C extends Error{constructor(t,e){super(t.message),this.error=t,this.status=e,this.name="ChatRequestError"}}const Wi=3e5;function Oe(s,t=Date.now()){return typeof s!="number"||!Number.isFinite(s)?t+Wi:s<1e12?s*1e3:s}class Ue{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 C(k("stream_unavailable"),200);return{token:e.token,wsUrl:e.ws_url,expiresAt:Oe(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 C(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 C(r,i.status)}return n?.data??n}}const Yt=[{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}],Gi=65536,Ki=2e3,Yi=8192,Me=2048,Jt=/^[A-Za-z0-9_-]{1,64}$/,N=s=>!!s&&typeof s=="object"&&!Array.isArray(s),H=(s,t)=>Object.keys(s).every(e=>t.includes(e)),Ji=s=>[...s].length,Ne=s=>new TextEncoder().encode(s).length,Xi=s=>[...s].some(t=>{const e=t.codePointAt(0)??0;return e===127||e<32&&e!==9&&e!==10&&e!==13}),Zi=s=>[...s].some(t=>{const e=t.codePointAt(0)??0;return e<=32||e===127}),A=(s,t,e=!1)=>typeof s=="string"&&Ji(s)<=t&&!Xi(s)&&(!e||s.trim().length>0),Xt=s=>Array.isArray(s)?s.map(Xt):N(s)?Object.fromEntries(Object.keys(s).sort().map(t=>[t,Xt(s[t])])):s,Zt=s=>{try{return Ne(JSON.stringify(Xt(s)))<=Gi}catch{return!1}};function De(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 Qi(s){if(typeof s!="string"||s.length===0||s.length>Me||Zi(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<=Me}catch{return!1}}function Pt(s,t){if(!N(s)||!H(s,["label","description","options"])||!A(s.label,160,!0)||"description"in s&&s.description!==void 0&&!A(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(!N(n)||!H(n,["id","label","description","allow_input","input_placeholder"])||typeof n.id!="string"||!Jt.test(n.id)||e.has(n.id)||!A(n.label,80,!0)||"description"in n&&n.description!==void 0&&!A(n.description,240))return!1;const r=n.allow_input===!0;if("allow_input"in n&&!r||"input_placeholder"in n&&(!r||!A(n.input_placeholder,160,!0))||(r&&(i+=1),i>1))return!1;e.add(n.id)}return Zt(s)}function Be(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 Le(s,t,e=!1){if(!N(s)||!H(s,["label","description","items"])||!A(s.label,160,!0)||"description"in s&&s.description!==void 0&&!A(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(!N(n)||!H(n,["id","title","description","image","action_label"])||typeof n.id!="string"||!Jt.test(n.id)||i.has(n.id)||!A(n.title,120,!0)||"description"in n&&n.description!==void 0&&!A(n.description,500)||"action_label"in n&&n.action_label!==void 0&&!A(n.action_label,80,!0)||"image"in n&&n.image!==void 0&&(!N(n.image)||!H(n.image,["url","alt"])||!(Qi(n.image.url)||e&&De(n.image.url))||!A(n.image.alt,240,!0)))return!1;i.add(n.id)}return Zt(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 Qt(s){return!N(s)||!H(s,["label","description","min_date","max_date","confirm_label","selection_mode"])||!A(s.label,160,!0)||!["single","range"].includes(String(s.selection_mode))||"description"in s&&s.description!==void 0&&!A(s.description,240)||"confirm_label"in s&&s.confirm_label!==void 0&&!A(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:Zt(s)}function ts(s,t){return s.tool_type==="ui_buttons"&&s.schema_version===1?Be(t):s.tool_type==="ui_buttons"&&s.schema_version===2?Pt(t):s.tool_type==="ui_carousel"&&s.schema_version===1?Le(t,void 0,!0):s.tool_type==="ui_date_picker"&&s.schema_version===1?Qt(t):!1}function je(s,t){return!N(t)||!H(t,["kind","value"])||Object.keys(t).length!==2?!1:t.kind==="date_range"?s.tool_type==="ui_date_picker"&&s.schema_version===1&&N(t.value)&&H(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")&&Jt.test(t.value):t.kind==="text"?s.tool_type==="ui_buttons"&&s.schema_version===2&&t.value===t.value.trim()&&A(t.value,Ki,!0)&&Ne(t.value)<=Yi:t.kind==="date"?s.tool_type==="ui_date_picker"&&s.schema_version===1&&q(t.value):!1}const te=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),es=new Set(["preparing","pending","accepted","resumed","cancelled","expired"]);function at(s){if(!te(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||!es.has(String(s.interaction_status))||!te(s.presentation))return null;const t={tool_type:s.tool_type,schema_version:Number(s.schema_version)},e=s.response_payload;return e!=null&&!je(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 D(s){if(!te(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=at({...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 ee(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 is=new Set(["user","ai","assistant","operator","support","system"]);function ie(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"||!is.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 _t=s=>["pending","accepted"].includes(s.interaction_status);class ss{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),...rs(t(ns(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?D(t.original):o))}mergeProjection(t,e){const i=D(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&&D(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 ee(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 h=a.active_interaction===null?null:at(a.active_interaction);if(a.active_interaction!==null&&(!h||!_t(h)))return;const u=a.messages.map(D).filter(g=>g!==null),l=D(a.interaction_response_message);h&&u.push(D(h)),l?.role==="user"&&u.push(l);const d=i.filter(g=>n(g)&&(h?.interaction_id!==g.interactionId||h.interaction_status==="accepted"&&l?.role==="user")),p=new Set(d.map(g=>g.messageId));this.setRows(g=>ee(g.filter(w=>!p.has(w.id)),u).sort((w,z)=>Date.parse(w.ts)-Date.parse(z.ts)||0)),d.forEach(g=>this.operations.delete(g.interactionId)),this.operation&&d.includes(this.operation)&&(this.operation=null),this._cursor=c,this.recoveryCursor=null,this.setCursor(c),this.setActive(h),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:at(t.active_interaction);if(!(t.active_interaction!==null&&(!n||!_t(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=at(t.payload);return!i||i.interaction_status==="preparing"||e===null||P(e,this._cursor)<=0?!0:this.hasMissingOutcome(i)||!_t(i)&&this.operations.has(i.interaction_id)&&!D(t.payload.interaction_response_message)?(this.refreshMissingOutcome(e),!0):(this._cursor=e,this.setCursor(e),this.mergeProjection(i,t.payload.interaction_response_message),_t(i)?this.setActive(i):this._active?.interaction_id===i.interaction_id&&this.setActive(null),this.operation&&(this.operation.interactionId!==i.interaction_id||!_t(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"||!Yt.some(h=>h.tool_type===i.tool_type&&h.schema_version===i.schema_version)||!je(i,e))return!1;const n=i.tool_type==="ui_buttons"&&i.schema_version===1;let r=null;if(n&&e.kind==="selection"&&Be(i.presentation))r=i.presentation.options.find(h=>h.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(h=>h.id===e.value)?.label??null;else if(e.kind==="selection"&&i.tool_type==="ui_carousel"&&Le(i.presentation,void 0,!0))r=i.presentation.items.find(h=>h.id===e.value)?.title??null;else if(e.kind==="date"&&i.tool_type==="ui_date_picker"&&i.schema_version===1&&Qt(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&&Qt(i.presentation)&&i.presentation.selection_mode==="range"){const{start_date:h,end_date:u}=e.value;(!i.presentation.min_date||h>=i.presentation.min_date)&&(!i.presentation.max_date||u<=i.presentation.max_date)&&(r=`${h} to ${u}`)}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:Yt}};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(h=>ee(h,[D(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 ns(s){const t=[];for(const e of s)e.kind==="interaction"?t.push(D(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 rs(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=at(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 os(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 as=25e3,cs=6e4,hs=3e4,Fe=6e4,bt=[1e3,2e3,4e3,8e3,16e3,3e4],se=1e4,ls=4e3,ds=2,He=new Set(["invalid_token","session_not_found","session_closed","origin_not_allowed","agent_archived","agent_not_found"]);function qe(){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 vt(s){s&&(s.onopen=null,s.onmessage=null,s.onclose=null,s.onerror=null)}class us{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??qe(),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){vt(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){vt(i),this.next=null,this.later(se,()=>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,vt(i);try{i?.close(ls,"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=os(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,vt(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>ds){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(Fe,()=>this.reconnectNow());return}if(t===1008){this.terminate(e||"policy");return}this.scheduleBackoff()}}handleMintFailure(t){const e=t instanceof C?t.error:k("network");if(e.code==="agent_inactive"){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(Fe,()=>this.reconnectNow());return}if(He.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,bt.length-1);if(this.failures+=1,this.failures>bt.length){this.opts.onStatus("offline"),this.retryWhenReachable();return}this.opts.onStatus(this.recoveringStatus());const e=Math.round(bt[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()},bt[bt.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>=cs){this.declareDead();return}this.send({type:"ping"})&&(this.lastPingSentAt=t)},as)}declareDead(){const t=this.socket;if(t){vt(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()-hs);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 C?i.error:k("network");if(He.has(n.code)){this.terminate(n.code);return}const r=n.retryAfterSeconds?n.retryAfterSeconds*1e3:se;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(se,()=>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 ne="osvi.chat.visitor",ps=/^web:[0-9a-f]{32}$/;function re(){const s=new Map;return{get:t=>s.get(t)??null,set:(t,e)=>{s.set(t,e)},remove:t=>{s.delete(t)}}}function Ve(){const s=re();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 ze=s=>`web:${Array.from(s,t=>t.toString(16).padStart(2,"0")).join("")}`;let oe=null;function ct(s,t){const e=s.get(ne);if(e&&ps.test(e))return e;e!==null&&s.remove(ne);let i;try{i=globalThis.crypto?.getRandomValues?.(new Uint8Array(16))}catch{}if(i){const n=ze(i);return s.set(ne,n),n}if(!oe){const n=new Uint8Array(16);for(let r=0;r<n.length;r+=1)n[r]=Math.floor(Math.random()*256);oe=ze(n)}return oe}function Rt(s){return`osvi.chat.session.${s}`}const We="https://api.osvi.ai",fs=12e4,gs=15e3,Ge=[1e3,2e3,4e3,8e3,16e3],ms=2048,ys=new Set(["session_closed","session_dormant","new_session"]);function Ot(){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 Ke=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Ye={user:"user",ai:"assistant",assistant:"assistant",operator:"human",support:"human"};class _s{constructor(t){this.opts=t,this.state=Ke(),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 Ue(t.baseUrl??We,t.fetch),this.store=t.store??Ve(),this.page=t.page??qe(),this.interactions=new ss({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:Ot})}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,ct(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(Rt(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=Ot(),n=Ot(),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(){return this.destroyed?Promise.resolve(!1):!this.sessionId&&this.ensureP?this.ensureP.then(t=>t!==null):this.serialize(async()=>{if(this.destroyed)return!1;if(this.sessionId&&this.endSession("new_session"),this.serverMode)return this.wantNewServerSession=!0,await this.openServerSession()!==null;try{const t=await this.http.createSession(this.opts.agentId,ct(this.store));return this.destroyed?!1:(this.adopt(t.id,null,"keep"),!0)}catch(t){return this.fail(t,!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=Ke(),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=ct(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 C)||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 C(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:Oe(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 C(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 C(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(Rt(this.opts.agentId),t),e&&this.applySnapshot(e,i);let a=n??null;const c=this.serverMode?null:ct(this.store);let h=!0,u=!1;const l=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 C(k("session_closed"),0);return this.latestToken=g.token,g}const d=h;h=!1;let p;try{p=await this.http.mintPublicToken(t)}catch(g){throw u=d&&r&&this.isCurrent(o,t)&&g instanceof C&&g.status===404&&g.error.code==="session_not_found"&&[...this.pending.values()].every(w=>w.gen===-1),g}this.assertCurrent(o,t);try{this.checkWsUrl(p.wsUrl)}catch(g){throw this.fail(g,!1),g}return this.latestToken=p.token,p};this.conn=new us({mint:l,sdkVersion:qi,page:this.page,random:this.opts.random,WebSocketImpl:this.opts.WebSocketImpl,onFrame:d=>this.onFrame(d),onStatus:d=>this.patch({status:d,...d==="open"?{error:null}:{}}),onOpen:()=>this.onOpen(),onReconnected:()=>{this.recover()},onError:d=>this.patch({error:d}),onClosed:d=>{if(!this.isCurrent(o,t))return;if(u&&c&&d==="session_not_found"){u=!1,this.serialize(()=>this.replaceBeforeFirstWrite(o,t,c));return}const p=this.switchTo;this.switchTo=null,this.endSession(d),p&&this.serialize(()=>this.openServerSession(p))}}),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 C)||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 C&&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,ct(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(Rt(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:Ot(),reason:"session_ended"};this.setAwaiting(!1),this.patch({status:"closed",mode:"ai",items:e.length&&i?.kind!=="divider"?[...e,n]:e,...ys.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>ms&&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=ie(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=ie({...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<Ge.length){const n=Ge[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=Ye[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 h=at(c);if(h){i.push({kind:"interaction",id:h.interaction_id,interaction:h});continue}const u=ie(c),l=u?Ye[u.role]:void 0;if(u&&l){i.push({kind:"message",id:`srv:${u.id}`,serverId:u.id,role:l,content:u.content,createdAt:u.created_at??new Date().toISOString(),status:"sent"});const d=c.message_id;typeof d=="string"&&n.set(u.id,d)}}let r=this.state.items;if(e==="replace")r=i;else if(e==="append"){let c=r.length;for(;c>0;){const h=r[c-1];if(h.kind==="message"&&h.role==="user"&&h.status==="sending"&&!h.serverId)c-=1;else break}r=[...r.slice(0,c),...i,...r.slice(c)]}else if(e==="reconcile"){const c=new Set(r.flatMap(h=>h.kind==="message"?[h.serverId]:h.kind==="interaction"?[h.id]:[]));for(const h of i){const u=h.kind==="message"?h.serverId:h.id;if(h.kind==="message"&&h.role==="user"&&!c.has(u)){const l=n.get(h.serverId),d=r.findIndex(p=>p.kind==="message"&&p.role==="user"&&!p.serverId&&(l?p.id===l:p.content===h.content));if(d>=0){const p=r[d];r=r.slice(),r[d]={...p,serverId:h.serverId,status:"sent"},this.dropPending(p.id),c.add(u);continue}}c.has(u)||(r=[...r,h],c.add(u))}}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:Yt}}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)},gs))}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})},fs)),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 C?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 Je(s){return new _s(s)}const Xe={primary:"#4f46e5",background:"#ffffff",surface:"#f4f4f5",text:"#18181b",userBubble:"#4f46e5",assistantBubble:"#f4f4f5"},bs={primary:"#6366f1",background:"#0a0a12",surface:"#1c1c27",text:"#f4f4f5",userBubble:"#6366f1",assistantBubble:"#1f1f2b"},vs={none:"0px",sm:"6px",md:"10px",lg:"16px",full:"9999px"},$t={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"},ht=s=>`var(${$t[s]}, ${Xe[s]})`;function Ze(s){const t={...s?.mode==="dark"?bs:Xe,...s?.colors},e={};for(const n of Object.keys($t))e[$t[n]]=t[n];const i=s?.radius??"md";return e["--osvi-radius"]=typeof i=="number"?`${i}px`:vs[i],e}function $s(s){if(!s)return{};if(s.mode)return Ze(s);const t=Ze(s),e={};for(const i of Object.keys(s.colors??{}))e[$t[i]]=t[$t[i]];return s.radius!==void 0&&(e["--osvi-radius"]=t["--osvi-radius"]),e}const Qe=new WeakMap;function ae(s,t){for(const i of Qe.get(s)??[])s.style.removeProperty(i);const e=$s(t);for(const[i,n]of Object.entries(e))s.style.setProperty(i,n);Qe.set(s,Object.keys(e))}const ti={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",newChat:"New chat",emptyState:"Send a message to start chatting.",defaultTitle:"Chat"},ei=new Set;function ii(s,t){ei.has(s)||(ei.add(s),console.warn(`[osvi-chat] ${t}`))}function S(s,t){return s!=null&&t.includes(s)?s:void 0}function Ut(s){if(s!=null)return S(s,["none","sm","md","lg","full"])??(/^\d{1,2}(?:px)?$/.test(s)?Number(s.replace(/px$/,"")):void 0)}function Mt(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{}ii("base-url","ignored an invalid base-url (https required, http only for localhost)")}}function ce(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 si(s,t){if(t){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}ii(s,`ignored invalid JSON in the ${s} attribute`)}}const Z={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4},ni=s=>(...t)=>({_$litDirective$:s,values:t});let ri=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:ws}=Di,oi=s=>s,Ss=s=>s.strings===void 0,ai=()=>document.createComment(""),wt=(s,t,e)=>{const i=s._$AA.parentNode,n=t===void 0?s._$AB:t._$AA;if(e===void 0){const r=i.insertBefore(ai(),n),o=i.insertBefore(ai(),n);e=new ws(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 h=oi(c).nextSibling;oi(i).insertBefore(c,n),c=h}}}return e},Q=(s,t,e=s)=>(s._$AI(t,e),s),ks={},ci=(s,t=ks)=>s._$AH=t,As=s=>s._$AH,he=s=>{s._$AR(),s._$AA.remove()};const hi=(s,t,e)=>{const i=new Map;for(let n=t;n<=e;n++)i.set(s[n],n);return i},Cs=ni(class extends ri{constructor(s){if(super(s),s.type!==Z.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=As(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 h,u,l=0,d=n.length-1,p=0,g=r.length-1;for(;l<=d&&p<=g;)if(n[l]===null)l++;else if(n[d]===null)d--;else if(a[l]===o[p])c[p]=Q(n[l],r[p]),l++,p++;else if(a[d]===o[g])c[g]=Q(n[d],r[g]),d--,g--;else if(a[l]===o[g])c[g]=Q(n[l],r[g]),wt(s,c[g+1],n[l]),l++,g--;else if(a[d]===o[p])c[p]=Q(n[d],r[p]),wt(s,n[l],n[d]),d--,p++;else if(h===void 0&&(h=hi(o,p,g),u=hi(a,l,d)),h.has(a[l]))if(h.has(a[d])){const w=u.get(o[p]),z=w!==void 0?n[w]:null;if(z===null){const Ct=wt(s,n[l]);Q(Ct,r[p]),c[p]=Ct}else c[p]=Q(z,r[p]),wt(s,n[l],z),n[w]=null;p++}else he(n[d]),d--;else he(n[l]),l++;for(;p<=g;){const w=wt(s,c[g+1]);Q(w,r[p]),c[p++]=w}for(;l<=d;){const w=n[l++];w!==null&&he(w)}return this.ut=o,ci(s,c),E}}),xs=/https?:\/\/[^\s<>"']+/g,Nt=(s,t)=>s.split(t).length-1;function Is(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 Es(s){const t=[];let e=0;for(const i of s.matchAll(xs)){const n=Is(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 Ts(s,t,e,i,n){return f`${s.items.length?Cs(s.items,r=>r.id,r=>{if(r.kind==="divider")return f`<p class="divider">${t.sessionEnded}</p>`;if(r.kind==="message")return f`<article class=${`bubble ${r.role}`}>${r.role==="human"?f`<small>Team</small>`:m}<p>${Es(r.content).map(h=>"href"in h?f`<a href=${h.href} target="_blank" rel="noopener noreferrer">${h.text}</a>`:h.text)}</p>${r.role==="user"&&r.status==="failed"?f`<span>${t.sendFailed}</span><button type="button" @click=${()=>n(r.id)}>${t.retry}</button>`: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 f`<osvi-buttons data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.buttons??"chips"} base-url=${i}></osvi-buttons>`;case"ui_carousel":return f`<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 f`<osvi-date-picker data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} base-url=${i}></osvi-date-picker>`;default:return f`<p>${o.content}</p>`}}):f`<p>${t.emptyState}</p>`}${s.awaitingReply?f`<p aria-label=${t.typing}>${t.typing}<span aria-hidden="true"> •••</span></p>`:m}`}const Ps=ni(class extends ri{constructor(s){if(super(s),s.type!==Z.PROPERTY&&s.type!==Z.ATTRIBUTE&&s.type!==Z.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!Ss(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===Z.PROPERTY){if(t===e[i])return E}else if(s.type===Z.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(i))return E}else if(s.type===Z.ATTRIBUTE&&e.getAttribute(i)===t+"")return E;return ci(s),t}});function Rs(s){return f`<div class="composer"><textarea aria-label="Message" placeholder=${s.placeholder} .value=${Ps(s.draft)} ?disabled=${s.disabled} @input=${s.input} @keydown=${t=>{t.key==="Enter"&&!t.shiftKey&&!t.isComposing&&!s.disabled&&(t.preventDefault(),s.send())}}></textarea><button type="button" aria-label=${s.strings.send} ?disabled=${s.disabled||!s.draft.trim()} @click=${s.send}>${s.strings.send}</button></div>`}var Os=Object.defineProperty,b=(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&&Os(t,e,n),n};const li=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),di={fromAttribute:s=>s!=="false"},_=(L=class extends X{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=li(),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(),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,Mt(this.baseUrl)]);if((this.client?this.boundClient===this.client&&!this.ownClient:this.ownClient&&t===this.ownKey)||(this.releaseClient(),this.chatState=li(),!this.client&&!this.agentId))return;const e=!this.client,i=this.client??L.clientFactory({agentId:this.agentId,baseUrl:Mt(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(),ae(this,this.mergedTheme())}mergedTheme(){const t=si("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=Ut(this.radius)??(typeof t?.radius=="number"&&Number.isInteger(t.radius)&&t.radius>=0&&t.radius<=99?t.radius:typeof t?.radius=="string"?Ut(t.radius):void 0),r=S(this.mode,["light","dark"])??S(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={...ti};for(const e of[this.strings,si("strings",this.stringsAttribute)])for(const i of Object.keys(ti))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=ce(this.headerAvatar??this.header.avatarUrl),r={...this.variants,...S(this.buttons,["chips","list"])?{buttons:S(this.buttons,["chips","list"])}:{},...S(this.carousel,["slider","list"])?{carousel:S(this.carousel,["slider","list"])}:{}};return f`<header>${n?f`<img src=${n} alt="" referrerpolicy="no-referrer">`:m}<div class="heading"><h2>${this.headerTitle??this.header.title??e.agent?.name??t.defaultTitle}</h2>${this.headerSubtitle??this.header.subtitle?f`<p>${this.headerSubtitle??this.header.subtitle}</p>`:m}${e.mode==="human"?f`<small>${t.humanJoined}</small>`:m}</div>
4
+ ${this.newChat?f`<button type="button" ?disabled=${!i||this.sessionBusy} @click=${()=>i&&!this.sessionBusy&&void this.run(()=>i.newSession())}>${t.newChat}</button>`:m}
5
+ ${this.closable?f`<button type="button" aria-label=${t.closeChat} @click=${()=>this.dispatchEvent(new CustomEvent("osvi-close",{bubbles:!0,composed:!0}))}>×</button>`:m}</header>
6
+ <div class="transcript" role="log" aria-live="polite" aria-label="Conversation" @scroll=${o=>{const a=o.currentTarget;this.followBottom=a.scrollHeight-a.scrollTop-a.clientHeight<=80}} @osvi-respond=${this.respond} @osvi-request-input=${this.requestInput}>${Ts(e,t,r,i?.resolveUrl("")??"",o=>{i&&this.run(()=>i.retry(o))})}</div>
7
+ <div class="status" role="status">${this.statusText(t)}${e.error?.retryable&&(e.status==="idle"||e.status==="closed")?f`<button type="button" ?disabled=${this.busy||!i} @click=${()=>i&&void this.run(()=>i.start())}>${t.tryAgain}</button>`:m}</div>
8
+ ${Rs({strings:t,draft:this.draft,placeholder:this.typed?.placeholder??t.placeholder,disabled:this.blocked,input:o=>{this.draft=o.target.value,this.requestUpdate()},send:this.send})}
9
+ ${this.poweredBy?f`<footer><a href="https://osvi.ai" target="_blank" rel="noopener noreferrer">${t.poweredBy}</a></footer>`:m}`}},L.clientFactory=Je,L.properties={themeAttribute:{attribute:"theme"},stringsAttribute:{attribute:"strings"}},L.styles=zt`
10
+ :host { display:flex; flex-direction:column; height:100%; min-height:260px; color:var(--osvi-color-text,#18181b); background:var(--osvi-color-background,#fff); font:14px/1.5 system-ui,sans-serif; border-radius:var(--osvi-radius,10px); overflow:hidden; }
11
+ header { display:flex; align-items:center; gap:10px; padding:14px; border-bottom:1px solid var(--osvi-color-surface,#f4f4f5); } header img { width:36px; height:36px; border-radius:50%; } .heading { flex:1; } h2,p { margin:0; } h2 { font-size:16px; } small { display:block; }
12
+ .transcript { flex:1; overflow:auto; padding:16px; min-height:0; } .bubble { width:fit-content; max-width:85%; padding:10px 14px; margin:8px 0; border-radius:var(--osvi-radius,10px); background:var(--osvi-color-assistant-bubble,#f4f4f5); overflow-wrap:anywhere; white-space:pre-wrap; } .user { margin-left:auto; color:#fff; background:var(--osvi-color-user-bubble,#4f46e5); } .bubble a { color:inherit; } .divider { text-align:center; } .status { padding:0 14px; } .composer { display:flex; gap:8px; padding:14px; } textarea { flex:1; resize:vertical; min-width:0; } button,textarea { font:inherit; } button { cursor:pointer; } button:disabled { cursor:default; } footer { padding:0 14px 10px; text-align:center; } footer a { color:inherit; } osvi-buttons,osvi-carousel,osvi-date-picker { display:block; margin:8px 0; }
13
+ `,L);b([y({attribute:"agent-id"})],_.prototype,"agentId"),b([y({attribute:"base-url"})],_.prototype,"baseUrl"),b([y({attribute:!1})],_.prototype,"client"),b([y({attribute:!1})],_.prototype,"theme"),b([y({attribute:!1})],_.prototype,"variants"),b([y({attribute:!1})],_.prototype,"strings"),b([y({attribute:"powered-by",converter:di})],_.prototype,"poweredBy"),b([y({attribute:"new-chat",converter:di})],_.prototype,"newChat"),b([y({attribute:!1})],_.prototype,"header"),b([y({type:Boolean})],_.prototype,"closable"),b([y({attribute:"header-title"})],_.prototype,"headerTitle"),b([y({attribute:"header-subtitle"})],_.prototype,"headerSubtitle"),b([y({attribute:"header-avatar"})],_.prototype,"headerAvatar"),b([y({attribute:"primary-color"})],_.prototype,"primaryColor"),b([y()],_.prototype,"radius"),b([y()],_.prototype,"mode"),b([y()],_.prototype,"buttons"),b([y()],_.prototype,"carousel"),b([M()],_.prototype,"chatState"),b([M()],_.prototype,"draft"),b([M()],_.prototype,"busy"),b([M()],_.prototype,"typed");let ui=_;function B(s,t){typeof customElements>"u"||customElements.get(s)||customElements.define(s,t)}const le=zt`
14
+ :host { display: block; font: inherit; color: ${G(ht("text"))}; background: ${G(ht("background"))}; }
15
+ * { box-sizing: border-box; }
16
+ button { font: inherit; color: inherit; background: ${G(ht("surface"))}; border: 1px solid currentColor; border-radius: var(--osvi-radius, 10px); padding: 10px 14px; cursor: pointer; }
17
+ button:focus-visible { outline: 3px solid ${G(ht("primary"))}; outline-offset: 3px; }
18
+ button:disabled { opacity: .5; cursor: default; }
19
+ button[aria-pressed="true"] { outline: 2px solid ${G(ht("primary"))}; }
20
+ small { display: block; }
21
+ .chips { display: flex; flex-wrap: wrap; gap: 8px; }
22
+ .list { display: grid; gap: 6px; }
23
+ .list button { width: 100%; text-align: left; }
24
+ .card { background: ${G(ht("surface"))}; border-radius: var(--osvi-radius, 10px); padding: 12px; }
25
+ .image { aspect-ratio: 16 / 9; display: grid; place-items: center; overflow: hidden; }
26
+ .image img { width: 100%; height: 100%; object-fit: cover; }
27
+ .navigation { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 10px 0; }
28
+ .days, .weekdays { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 4px; text-align: center; }
29
+ .days button { padding: 8px 0; }
30
+ `;var Us=Object.defineProperty,Dt=(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&&Us(t,e,n),n};class tt extends X{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&&ts(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")&&ae(this,this.theme)}}Dt([y({attribute:!1})],tt.prototype,"interaction"),Dt([y({type:Boolean})],tt.prototype,"disabled"),Dt([y({attribute:!1})],tt.prototype,"theme"),Dt([y({attribute:"base-url"})],tt.prototype,"baseUrl");var Ms=Object.defineProperty,Ns=(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&&Ms(t,e,n),n};const fe=class fe extends tt{constructor(){super(...arguments),this.toolType="ui_buttons",this.variant="chips"}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return f`<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 f`<p>${e.label}</p>${e.description?f`<p>${e.description}</p>`:m}
31
+ ${this.live?f`<div role="group" aria-label="Options" class=${this.variant} @keydown=${this.onKey}>
32
+ ${e.options.map(n=>f`<button type="button" @click=${()=>this.pick(n.id,n.allow_input,n.input_placeholder)}><span>${n.label}</span>${n.description?f`<small>${n.description}</small>`:m}</button>`)}
33
+ </div>`:i?f`<p>${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()}};fe.styles=le;let St=fe;Ns([y()],St.prototype,"variant");var Ds=Object.defineProperty,de=(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&&Ds(t,e,n),n};const ge=class ge extends tt{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 f`<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 f`<p>${e.label}</p>${e.description?f`<p>${e.description}</p>`:m}
34
+ ${this.live?this.variant==="list"?f`<div class="list">${e.items.map((n,r)=>this.card(n,r))}</div>`:f`<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>
35
+ <div class="navigation"><button type="button" aria-label="Previous card" ?disabled=${this.index===0} @click=${()=>this.navigate(-1,e.items.length)}>Previous</button>
36
+ <span aria-live="polite">${this.index+1} of ${e.items.length}</span>
37
+ <button type="button" aria-label="Next card" ?disabled=${this.index===e.items.length-1} @click=${()=>this.navigate(1,e.items.length)}>Next</button></div>`:i?f`<p>${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 f`<article class="card">${i&&De(i.url)?f`<div class="image">${this.imageFailed.has(e)?f`<span role="img" aria-label="Image unavailable">Image unavailable</span>`:f`<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}
38
+ <h3>${t.title}</h3>${t.description?f`<p>${t.description}</p>`:m}
39
+ <button type="button" @click=${n=>this.select(n,t.id)}>${t.action_label??"Select"}</button></article>`}};ge.styles=le;let et=ge;de([y()],et.prototype,"variant"),de([M()],et.prototype,"index"),de([M()],et.prototype,"imageFailed");var Bs=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&&Bs(t,e,n),n};const pi=s=>`${String(s.getFullYear()).padStart(4,"0")}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`,ue=()=>pi(new Date),fi=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},it=s=>s.slice(0,7),me=class me extends tt{constructor(){super(...arguments),this.toolType="ui_date_picker",this.variant="grid",this.month=it(ue()),this.start="",this.end=""}earliest(t){return t.min_date&&t.min_date>ue()?t.min_date:ue()}willUpdate(t){t.has("interaction")&&(this.start="",this.end="",this.valid&&(this.month=it(this.earliest(this.interaction.presentation))))}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return f`<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 f`<p>${e.label}</p>${e.description?f`<p>${e.description}</p>`:m}${n?f`<p>${n}</p>`:m}`;const r=fi(`${this.month}-01`),o=new Date(r);o.setMonth(o.getMonth()+1,0);const a=this.earliest(e),c=Array.from({length:o.getDate()},(u,l)=>`${this.month}-${String(l+1).padStart(2,"0")}`),h=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;return f`<p>${e.label}</p>${e.description?f`<p>${e.description}</p>`:m}
40
+ <div class="navigation"><button type="button" aria-label="Previous month" ?disabled=${this.month<=it(a)} @click=${()=>this.moveMonth(-1,e)}>Previous</button>
41
+ <span aria-live="polite">${r.toLocaleDateString(void 0,{month:"long",year:"numeric"})}</span>
42
+ <button type="button" aria-label="Next month" ?disabled=${!!e.max_date&&this.month>=it(e.max_date)} @click=${()=>this.moveMonth(1,e)}>Next</button></div>
43
+ <div class="weekdays" aria-hidden="true">${["Su","Mo","Tu","We","Th","Fr","Sa"].map(u=>f`<span>${u}</span>`)}</div>
44
+ <div class="days" role="group" aria-label="Choose date" @keydown=${this.onKey}>
45
+ ${Array.from({length:r.getDay()},()=>f`<span></span>`)}
46
+ ${c.map((u,l)=>f`<button type="button" aria-label=${u} aria-pressed=${u===this.start||u===this.end} ?disabled=${u<a||!!e.max_date&&u>e.max_date} @click=${()=>this.pick(u,e)}>${l+1}</button>`)}
47
+ </div><p aria-live="polite">${h}</p>
48
+ <button type="button" ?disabled=${!this.start||e.selection_mode==="range"&&(!this.end||this.start>=this.end)} @click=${()=>this.confirm(e)}>${e.confirm_label??"Confirm date"}</button>`}moveMonth(t,e){const i=fi(`${this.month}-01`);i.setMonth(i.getMonth()+t);const n=it(pi(i));n>=it(this.earliest(e))&&(!e.max_date||n<=it(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()}};me.styles=le;let V=me;Bt([y()],V.prototype,"variant"),Bt([M()],V.prototype,"month"),Bt([M()],V.prototype,"start"),Bt([M()],V.prototype,"end"),B("osvi-chat",ui),B("osvi-buttons",St),B("osvi-carousel",et),B("osvi-date-picker",V);const x=s=>typeof s=="string"?s:void 0,lt=s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},Lt=s=>s===!0||s==="true"?!0:s===!1||s==="false"?!1:void 0;function pe(s,t){const e=lt(t),i=s?.dataset??{},n=lt(e.theme),r=lt(e.variants),o=lt(e.header),a={},c=lt(n.colors);for(const d of["primary","background","surface","text","userBubble","assistantBubble"]){const p=x(c[d]);p!==void 0&&(a[d]=p)}i.primaryColor&&(a.primary=i.primaryColor);const h=Ut(i.radius)??(typeof n.radius=="number"&&Number.isInteger(n.radius)&&n.radius>=0&&n.radius<=99?n.radius:Ut(x(n.radius))),u=S(i.mode,["light","dark"])??S(x(n.mode),["light","dark"]),l={};for(const[d,p]of Object.entries(lt(e.strings)))typeof p=="string"&&(l[d]=p);return{agentId:i.agent??x(e.agentId)??"",baseUrl:Mt(i.baseUrl)??Mt(x(e.baseUrl)),position:S(i.position,["right","left"])??S(x(e.position),["right","left"])??"right",launcher:S(i.launcher,["bubble","none"])??S(x(e.launcher),["bubble","none"])??"bubble",greeting:i.greeting??x(e.greeting),theme:{colors:a,...h!==void 0?{radius:h}:{},...u?{mode:u}:{}},variants:{buttons:S(i.buttons,["chips","list"])??S(x(r.buttons),["chips","list"]),carousel:S(i.carousel,["slider","list"])??S(x(r.carousel),["slider","list"])},strings:l,poweredBy:Lt(i.poweredBy)??Lt(e.poweredBy)??!0,newChat:Lt(i.newChat)??Lt(e.newChat)??!0,header:{title:i.title??x(o.title),subtitle:i.subtitle??x(o.subtitle),avatarUrl:ce(i.avatar)??ce(x(o.avatarUrl))},auth:e.auth}}const Ft=class Ft extends X{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 f`${t.greeting&&!this.greetingDismissed&&!this.opened?f`<div class="greeting" part="greeting">${t.greeting}<button type="button" aria-label="Dismiss greeting" @click=${this.onDismiss}>×</button></div>`:m}
49
+ ${t.launcher!=="none"?f`<button class="launcher" part="launcher" type="button" aria-label=${this.opened?"Close chat":"Open chat"} aria-expanded=${this.opened} @click=${this.onToggle}>${this.opened?"×":"Chat"}${this.badge>0&&!this.opened?f`<span class="badge" part="badge" role="status" aria-label=${`${this.badge} unread messages`}>${this.badge}</span>`:m}</button>`:m}
50
+ ${this.client?f`<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} 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=zt`
51
+ :host { position:fixed; bottom:20px; right:20px; z-index:2147483000; font:14px/1.5 system-ui,sans-serif; }
52
+ :host([position="left"]) { right:auto; left:20px; }
53
+ button { font:inherit; cursor:pointer; } .launcher { position:relative; border:0; border-radius:50%; width:56px; height:56px; background:var(--osvi-color-primary,#4f46e5); color:white; box-shadow:0 4px 20px #0003; }
54
+ .badge { position:absolute; top:-4px; right:-4px; background:#dc2626; color:white; border-radius:99px; min-width:20px; padding:0 3px; }
55
+ .greeting { background:white; color:#18181b; border-radius:12px; padding:12px; margin-bottom:12px; box-shadow:0 4px 20px #0003; max-width:260px; } .greeting button { margin-left:8px; }
56
+ .panel { position:absolute; bottom:76px; right:0; width:380px; height:min(600px,calc(100dvh - 100px)); box-shadow:0 4px 30px #0003; border-radius:10px; overflow:hidden; } :host([position="left"]) .panel { right:auto; left:0; } .panel[hidden] { display:none; }
57
+ @media(max-width:639px) { .panel,:host([position="left"]) .panel { position:fixed; inset:0; width:100%; height:100dvh; border-radius:0; } }
58
+ `;let jt=Ft;customElements.get("osvi-chat-widget")||customElements.define("osvi-chat-widget",jt);const gi=s=>`osvi.chat.greetingDismissed.${s}`,kt=s=>`osvi.chat.seen.${s}`,Ls=3e4;let st=null;function js(s){if(B("osvi-chat",ui),B("osvi-buttons",St),B("osvi-carousel",et),B("osvi-date-picker",V),B("osvi-chat-widget",jt),st)return st;let t=pe(null,s),e=null,i=null,n,r=!1,o=!1,a=-1/0,c=0,h=0,u=null;const l=Ve();let d=re(),p=new Set,g=new Set;const w=$=>new Set([...$.items.flatMap(O=>O.kind==="message"&&O.role!=="user"?[`message:${O.serverId??O.id}`]:[]),...$.activeInteraction?[`interaction:${$.activeInteraction.interaction_id}`]:[]]),z=$=>{if(!e)return;const O=w($);if(r){let I=T(d.get(kt(t.agentId)));for(const v of $.items){const U=T(v.kind==="message"&&v.role!=="user"?v.serverId:v.kind==="interaction"?v.interaction.id:void 0);U!==null&&(I===null||P(U,I)>0)&&(I=U)}const W=T(d.get(kt(t.agentId)));I!==null&&(W===null||P(I,W)>0)&&d.set(kt(t.agentId),I),g.clear(),e.badge=0}else{const I=T(d.get(kt(t.agentId))),W=new Set($.items.flatMap(v=>{if(v.kind!=="message"||v.role==="user")return[];const U=T(v.serverId);return U!==null&&I!==null&&P(U,I)<=0?[]:[`message:${v.serverId??v.id}`]}));if($.activeInteraction){const v=T($.activeInteraction.id);(v===null||I===null||P(v,I)>0)&&W.add(`interaction:${$.activeInteraction.interaction_id}`)}for(const v of O)!p.has(v)&&W.has(v)&&g.add(v);e.badge=g.size}p=O},Ct=async()=>{if(t.auth?.mode==="server"||!e||o||!d.get(Rt(t.agentId)))return;a=Date.now();const $=c,O=++h;try{const I=await new Ue(t.baseUrl??We).bootstrap(t.agentId,ct(d));if(!e||c!==$||O!==h||o)return;const W=T(d.get(kt(t.agentId)));e.badge=W===null?0:(I.messages??[]).filter(v=>{if(!v||typeof v!="object")return!1;const U=v,_i=T(U.id);return U.role!=="user"&&U.role!=="system"&&_i!==null&&P(_i,W)>0}).length}catch{e&&c===$&&O===h&&!o&&(e.badge=0)}},mi=()=>{document.visibilityState==="visible"&&Date.now()-a>=Ls&&Ct()},Ht=()=>{r&&window.innerWidth<640?(u===null&&(u=document.documentElement.style.overflow),document.documentElement.style.overflow="hidden"):u!==null&&(document.documentElement.style.overflow=u,u=null)},yi=$=>{$.key==="Escape"&&r&&(R.close(),e?.focusLauncher())},R={open(){if(!e||r)return;r=!0,o=!0,e.opened=!0,e.badge=0,g.clear(),Ht(),i||(i=Je({agentId:t.agentId,baseUrl:t.baseUrl,auth:t.auth,store:d}),e.client=i,p=w(i.getState()),n=i.subscribe(z),i.start().catch(()=>{})),z(i.getState());const $=e;$.updateComplete.then(()=>{e===$&&r&&$.panel?.focusActiveInteraction()})},close(){!e||!r||(r=!1,e.opened=!1,Ht(),e.focusLauncher())},toggle(){r?R.close():R.open()},destroy(){R.close(),++c,n?.(),n=void 0,i?.destroy(),i=null,e?.remove(),e=null,document.removeEventListener("visibilitychange",mi),document.removeEventListener("keydown",yi),window.removeEventListener("resize",Ht),delete window.__osviChatWidget,st===R&&(st=null)},init($={}){if(!e&&!(st&&st!==R)){if(t=pe(null,{...t,...$}),!t.agentId){console.error("[osvi-chat] data-agent is required");return}d=t.auth?.mode==="server"?re():l,r=!1,o=!1,a=-1/0,p=new Set,g=new Set,++c,e=document.createElement("osvi-chat-widget"),e.config=t,e.setAttribute("position",t.position??"right"),ae(e,t.theme),e.greetingDismissed=!!d.get(gi(t.agentId)),e.onToggle=R.toggle,e.onClose=R.close,e.onDismiss=()=>{e&&(e.greetingDismissed=!0,d.set(gi(t.agentId),"true"))},document.body.append(e),st=R,window.__osviChatWidget=!0,document.addEventListener("visibilitychange",mi),document.addEventListener("keydown",yi),window.addEventListener("resize",Ht),Ct()}}};return R.init(),R}const At=window,Fs=document.currentScript;if(!At.__osviChatWidget){const s=pe(Fs,At.OsviChatConfig);if(!s.agentId)console.error("[osvi-chat] data-agent is required");else{const t=Array.isArray(At.OsviChat?.q)?[...At.OsviChat.q]:[],e=js(s);At.OsviChat=e;for(const i of t){if(!Array.isArray(i))continue;const n=i[0];(n==="open"||n==="close"||n==="toggle")&&e[n]()}}}})();
59
+ //# sourceMappingURL=widget.js.map