@osvi-ai/chat 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core.js +1 -1
- package/dist/{index-BsRyQwUM.js → index-HWHyM4-l.js} +9 -9
- package/dist/index-HWHyM4-l.js.map +1 -0
- package/dist/types/core/client.d.ts +3 -1
- package/dist/types/ui/icons.d.ts +9 -0
- package/dist/types/ui/osvi-chat.d.ts +1 -0
- package/dist/types/widget/config.d.ts +1 -0
- package/dist/ui.js +103 -43
- package/dist/ui.js.map +1 -1
- package/dist/ui.mjs +363 -287
- package/dist/ui.mjs.map +1 -1
- package/dist/widget.js +129 -56
- package/dist/widget.js.map +1 -1
- package/package.json +2 -2
- package/dist/index-BsRyQwUM.js.map +0 -1
package/dist/ui.js
CHANGED
|
@@ -1,49 +1,109 @@
|
|
|
1
|
-
var OsviChatUi=(function(
|
|
2
|
-
\f\r]`,
|
|
3
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),he=/'/g,le=/"/g,de=/^(?:script|style|textarea|title)$/i,rs=i=>(t,...e)=>({_$litType$:i,strings:t,values:e}),u=rs(1),k=Symbol.for("lit-noChange"),m=Symbol.for("lit-nothing"),ue=new WeakMap,B=N.createTreeWalker(N,129);function pe(i,t){if(!Ct(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ne!==void 0?ne.createHTML(t):t}const os=(i,t)=>{const e=i.length-1,s=[];let n,r=t===2?"<svg>":t===3?"<math>":"",o=st;for(let a=0;a<e;a++){const c=i[a];let h,d,l=-1,p=0;for(;p<c.length&&(o.lastIndex=p,d=o.exec(c),d!==null);)p=o.lastIndex,o===st?d[1]==="!--"?o=ae:d[1]!==void 0?o=ce:d[2]!==void 0?(de.test(d[2])&&(n=RegExp("</"+d[2],"g")),o=D):d[3]!==void 0&&(o=D):o===D?d[0]===">"?(o=n??st,l=-1):d[1]===void 0?l=-2:(l=o.lastIndex-d[2].length,h=d[1],o=d[3]===void 0?D:d[3]==='"'?le:he):o===le||o===he?o=D:o===ae||o===ce?o=st:(o=D,n=void 0);const f=o===D&&i[a+1].startsWith("/>")?" ":"";r+=o===st?c+is:l>=0?(s.push(h),c.slice(0,l)+re+c.slice(l)+P+f):c+P+(l===-2?a:f)}return[pe(i,r+(i[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class it{constructor({strings:t,_$litType$:e},s){let n;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[h,d]=os(t,e);if(this.el=it.createElement(h,s),B.currentNode=this.el.content,e===2||e===3){const l=this.el.content.firstChild;l.replaceWith(...l.childNodes)}for(;(n=B.nextNode())!==null&&c.length<a;){if(n.nodeType===1){if(n.hasAttributes())for(const l of n.getAttributeNames())if(l.endsWith(re)){const p=d[o++],f=n.getAttribute(l).split(P),g=/([.?@])?(.*)/.exec(p);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?cs:g[1]==="?"?hs:g[1]==="@"?ls:_t}),n.removeAttribute(l)}else l.startsWith(P)&&(c.push({type:6,index:r}),n.removeAttribute(l));if(de.test(n.tagName)){const l=n.textContent.split(P),p=l.length-1;if(p>0){n.textContent=mt?mt.emptyScript:"";for(let f=0;f<p;f++)n.append(l[f],tt()),B.nextNode(),c.push({type:2,index:++r});n.append(l[p],tt())}}}else if(n.nodeType===8)if(n.data===oe)c.push({type:2,index:r});else{let l=-1;for(;(l=n.data.indexOf(P,l+1))!==-1;)c.push({type:7,index:r}),l+=P.length-1}r++}}static createElement(t,e){const s=N.createElement("template");return s.innerHTML=t,s}}function G(i,t,e=i,s){if(t===k)return t;let n=s!==void 0?e._$Co?.[s]:e._$Cl;const r=et(t)?void 0:t._$litDirective$;return n?.constructor!==r&&(n?._$AO?.(!1),r===void 0?n=void 0:(n=new r(i),n._$AT(i,e,s)),s!==void 0?(e._$Co??(e._$Co=[]))[s]=n:e._$Cl=n),n!==void 0&&(t=G(i,n._$AS(i,t.values),n,s)),t}class as{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:s}=this._$AD,n=(t?.creationScope??N).importNode(e,!0);B.currentNode=n;let r=B.nextNode(),o=0,a=0,c=s[0];for(;c!==void 0;){if(o===c.index){let h;c.type===2?h=new K(r,r.nextSibling,this,t):c.type===1?h=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(h=new ds(r,this,t)),this._$AV.push(h),c=s[++a]}o!==c?.index&&(r=B.nextNode(),o++)}return B.currentNode=N,n}p(t){let e=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,e),e+=s.strings.length-2):s._$AI(t[e])),e++}}class K{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,s,n){this.type=2,this._$AH=m,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=s,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=G(this,t,e),et(t)?t===m||t==null||t===""?(this._$AH!==m&&this._$AR(),this._$AH=m):t!==this._$AH&&t!==k&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):ns(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&&et(this._$AH)?this._$AA.nextSibling.data=t:this.T(N.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:s}=t,n=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=it.createElement(pe(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===n)this._$AH.p(e);else{const r=new as(n,this),o=r.u(this.options);r.p(e),this.T(o),this._$AH=r}}_$AC(t){let e=ue.get(t.strings);return e===void 0&&ue.set(t.strings,e=new it(t)),e}k(t){Ct(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let s,n=0;for(const r of t)n===e.length?e.push(s=new K(this.O(tt()),this.O(tt()),this,this.options)):s=e[n],s._$AI(r),n++;n<e.length&&(this._$AR(s&&s._$AB.nextSibling,n),e.length=n)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){const s=ie(t).nextSibling;ie(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}class _t{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,s,n,r){this.type=1,this._$AH=m,this._$AN=void 0,this.element=t,this.name=e,this._$AM=n,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=m}_$AI(t,e=this,s,n){const r=this.strings;let o=!1;if(r===void 0)t=G(this,t,e,0),o=!et(t)||t!==this._$AH&&t!==k,o&&(this._$AH=t);else{const a=t;let c,h;for(t=r[0],c=0;c<r.length-1;c++)h=G(this,a[s+c],e,c),h===k&&(h=this._$AH[c]),o||(o=!et(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 cs extends _t{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===m?void 0:t}}class hs extends _t{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==m)}}class ls extends _t{constructor(t,e,s,n,r){super(t,e,s,n,r),this.type=5}_$AI(t,e=this){if((t=G(this,t,e,0)??m)===k)return;const s=this._$AH,n=t===m&&s!==m||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==m&&(s===m||n);n&&this.element.removeEventListener(this.name,this,s),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 ds{constructor(t,e,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){G(this,t)}}const us={I:K},ps=Q.litHtmlPolyfillSupport;ps?.(it,K),(Q.litHtmlVersions??(Q.litHtmlVersions=[])).push("3.3.3");const fs=(i,t,e)=>{const s=e?.renderBefore??t;let n=s._$litPart$;if(n===void 0){const r=e?.renderBefore??null;s._$litPart$=n=new K(t.insertBefore(tt(),r),r,void 0,e??{})}return n._$AI(i),n};const nt=globalThis;let Y=class extends z{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=fs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return k}};Y._$litElement$=!0,Y.finalized=!0,nt.litElementHydrateSupport?.({LitElement:Y});const gs=nt.litElementPolyfillSupport;gs?.({LitElement:Y}),(nt.litElementVersions??(nt.litElementVersions=[])).push("4.2.2");const ms={attribute:!0,type:String,converter:gt,reflect:!1,hasChanged:kt},_s=(i=ms,t,e)=>{const{kind:s,metadata:n}=e;let r=globalThis.litPropertyMetadata.get(n);if(r===void 0&&globalThis.litPropertyMetadata.set(n,r=new Map),s==="setter"&&((i=Object.create(i)).wrapped=!0),r.set(e.name,i),s==="accessor"){const{name:o}=e;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(o,c,i,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,i,a),a}}}if(s==="setter"){const{name:o}=e;return function(a){const c=this[o];t.call(this,a),this.requestUpdate(o,c,i,!0,a)}}throw Error("Unsupported decorator location: "+s)};function _(i){return(t,e)=>typeof e=="object"?_s(i,t,e):((s,n,r)=>{const o=n.hasOwnProperty(r);return n.constructor.createProperty(r,s),o?Object.getOwnPropertyDescriptor(n,r):void 0})(i,t,e)}function C(i){return _({...i,state:!0,attribute:!1})}const ys="0.1.0",bs=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"]),vs=new Set(["rate_limited","network","session_unavailable","stream_unavailable","token_failed"]);function v(i,t){const e=i&&bs.has(i)?i:"unknown";return{code:e,message:t||e,retryable:vs.has(e)}}class S extends Error{constructor(t,e){super(t.message),this.error=t,this.status=e,this.name="ChatRequestError"}}const $s=3e5;function fe(i,t=Date.now()){return typeof i!="number"||!Number.isFinite(i)?t+$s:i<1e12?i*1e3:i}class ws{constructor(t,e=(...s)=>globalThis.fetch.bind(globalThis)(...s)){this.fetchImpl=e,this.base=t.replace(/\/+$/,"")}resolveUrl(t){return`${this.base}${t}`}bootstrap(t,e,s){const n=`?customer_id=${encodeURIComponent(e)}`;return this.request(`/public/chat/agents/${encodeURIComponent(t)}/bootstrap${n}`,{signal:s})}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 S(v("stream_unavailable"),200);return{token:e.token,wsUrl:e.ws_url,expiresAt:fe(e.expires_at)}}snapshot(t,e){return this.request(`/public/chat/session/${encodeURIComponent(t)}/snapshot`,{headers:{Authorization:`Bearer ${e}`}})}async request(t,e={}){let s;try{const r=this.fetchImpl,o={...e.headers};e.body!==void 0&&(o["Content-Type"]="application/json"),s=await r(this.resolveUrl(t),{...e,credentials:"omit",headers:o})}catch(r){throw r?.name==="AbortError"?r:new S(v("network","Network error"),0)}let n=null;try{n=await s.json()}catch{n=null}if(!s.ok||n?.success===!1){const r=v(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),s.status===429){r.code="rate_limited",r.retryable=!0;const o=Number(s.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 S(r,s.status)}return n?.data??n}}const It=[{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}],Ss=65536,As=2e3,ks=8192,ge=2048,Et=/^[A-Za-z0-9_-]{1,64}$/,T=i=>!!i&&typeof i=="object"&&!Array.isArray(i),O=(i,t)=>Object.keys(i).every(e=>t.includes(e)),Cs=i=>[...i].length,me=i=>new TextEncoder().encode(i).length,Ts=i=>[...i].some(t=>{const e=t.codePointAt(0)??0;return e===127||e<32&&e!==9&&e!==10&&e!==13}),Is=i=>[...i].some(t=>{const e=t.codePointAt(0)??0;return e<=32||e===127}),$=(i,t,e=!1)=>typeof i=="string"&&Cs(i)<=t&&!Ts(i)&&(!e||i.trim().length>0),xt=i=>Array.isArray(i)?i.map(xt):T(i)?Object.fromEntries(Object.keys(i).sort().map(t=>[t,xt(i[t])])):i,Pt=i=>{try{return me(JSON.stringify(xt(i)))<=Ss}catch{return!1}};function _e(i){return typeof i=="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(i)}function Es(i){if(typeof i!="string"||i.length===0||i.length>ge||Is(i))return!1;try{const t=new URL(i),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<=ge}catch{return!1}}function yt(i,t){if(!T(i)||!O(i,["label","description","options"])||!$(i.label,160,!0)||"description"in i&&i.description!==void 0&&!$(i.description,240)||!Array.isArray(i.options)||i.options.length===0||t!==void 0)return!1;const e=new Set;let s=0;for(const n of i.options){if(!T(n)||!O(n,["id","label","description","allow_input","input_placeholder"])||typeof n.id!="string"||!Et.test(n.id)||e.has(n.id)||!$(n.label,80,!0)||"description"in n&&n.description!==void 0&&!$(n.description,240))return!1;const r=n.allow_input===!0;if("allow_input"in n&&!r||"input_placeholder"in n&&(!r||!$(n.input_placeholder,160,!0))||(r&&(s+=1),s>1))return!1;e.add(n.id)}return Pt(i)}function ye(i,t){return yt(i,t)&&i.options.every(e=>!Object.prototype.hasOwnProperty.call(e,"allow_input")&&!Object.prototype.hasOwnProperty.call(e,"input_placeholder"))}function be(i,t,e=!1){if(!T(i)||!O(i,["label","description","items"])||!$(i.label,160,!0)||"description"in i&&i.description!==void 0&&!$(i.description,240)||!Array.isArray(i.items)||i.items.length===0||t!==void 0)return!1;const s=new Set;for(const n of i.items){if(!T(n)||!O(n,["id","title","description","image","action_label"])||typeof n.id!="string"||!Et.test(n.id)||s.has(n.id)||!$(n.title,120,!0)||"description"in n&&n.description!==void 0&&!$(n.description,500)||"action_label"in n&&n.action_label!==void 0&&!$(n.action_label,80,!0)||"image"in n&&n.image!==void 0&&(!T(n.image)||!O(n.image,["url","alt"])||!(Es(n.image.url)||e&&_e(n.image.url))||!$(n.image.alt,240,!0)))return!1;s.add(n.id)}return Pt(i)}function R(i){if(typeof i!="string"||!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(i))return!1;const t=Number(i.slice(0,4)),e=Number(i.slice(5,7)),s=Number(i.slice(8,10));if(t<1||t>9999||e<1||e>12||s<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 s<=r[e-1]}function Ot(i){return!T(i)||!O(i,["label","description","min_date","max_date","confirm_label","selection_mode"])||!$(i.label,160,!0)||!["single","range"].includes(String(i.selection_mode))||"description"in i&&i.description!==void 0&&!$(i.description,240)||"confirm_label"in i&&i.confirm_label!==void 0&&!$(i.confirm_label,80,!0)||"min_date"in i&&i.min_date!==void 0&&!R(i.min_date)||"max_date"in i&&i.max_date!==void 0&&!R(i.max_date)||typeof i.min_date=="string"&&typeof i.max_date=="string"&&i.min_date>i.max_date?!1:Pt(i)}function xs(i,t){return i.tool_type==="ui_buttons"&&i.schema_version===1?ye(t):i.tool_type==="ui_buttons"&&i.schema_version===2?yt(t):i.tool_type==="ui_carousel"&&i.schema_version===1?be(t,void 0,!0):i.tool_type==="ui_date_picker"&&i.schema_version===1?Ot(t):!1}function ve(i,t){return!T(t)||!O(t,["kind","value"])||Object.keys(t).length!==2?!1:t.kind==="date_range"?i.tool_type==="ui_date_picker"&&i.schema_version===1&&T(t.value)&&O(t.value,["start_date","end_date"])&&Object.keys(t.value).length===2&&R(t.value.start_date)&&R(t.value.end_date)&&t.value.start_date<t.value.end_date:typeof t.value!="string"?!1:t.kind==="selection"?(i.tool_type==="ui_buttons"||i.tool_type==="ui_carousel")&&Et.test(t.value):t.kind==="text"?i.tool_type==="ui_buttons"&&i.schema_version===2&&t.value===t.value.trim()&&$(t.value,As,!0)&&me(t.value)<=ks:t.kind==="date"?i.tool_type==="ui_date_picker"&&i.schema_version===1&&R(t.value):!1}const Rt=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),Ps=new Set(["preparing","pending","accepted","resumed","cancelled","expired"]);function J(i){if(!Rt(i)||i.type!=="interaction"||typeof i.id!="string"||!i.id||i.role!=="assistant"||typeof i.content!="string"||typeof i.interaction_id!="string"||!i.interaction_id||typeof i.tool_type!="string"||!Number.isSafeInteger(i.schema_version)||Number(i.schema_version)<1||!Number.isSafeInteger(i.interaction_revision)||Number(i.interaction_revision)<1||!Ps.has(String(i.interaction_status))||!Rt(i.presentation))return null;const t={tool_type:i.tool_type,schema_version:Number(i.schema_version)},e=i.response_payload;return e!=null&&!ve(t,e)?null:{id:i.id,type:"interaction",role:"assistant",content:i.content,interaction_id:i.interaction_id,tool_type:i.tool_type,schema_version:Number(i.schema_version),presentation:i.presentation,interaction_status:i.interaction_status,interaction_revision:Number(i.interaction_revision),...typeof i.created_at=="string"?{created_at:i.created_at}:{},...typeof i.selected_option_id=="string"?{selected_option_id:i.selected_option_id}:{},...e!==void 0?{response_payload:e}:{}}}function I(i){if(!Rt(i)||typeof i.id!="string"&&typeof i.id!="number"||typeof i.content!="string"||!["assistant","user","operator","system"].includes(String(i.role)))return null;const t=J({...i,id:String(i.id)});return{id:String(i.id),content:i.content,type:i.type==="interaction"?"interaction":"message",ts:typeof i.created_at=="string"?i.created_at:typeof i.ts=="string"?i.ts:new Date().toISOString(),...t??{},role:i.role}}function Ut(i){return typeof i=="string"&&/^\d+$/.test(i)?i.replace(/^0+(?=\d)/,""):null}function X(i,t){return i.length===t.length?i===t?0:i>t?1:-1:i.length>t.length?1:-1}function Mt(i,t){const e=[...i];for(const s of t){const n=e.findIndex(r=>r.id===s.id||s.interaction_id&&r.interaction_id===s.interaction_id);if(n<0)e.push(s);else{const r=e[n],o=c=>c.interaction_status==="preparing"?0:c.interaction_status==="pending"?1:c.interaction_status==="accepted"?2:3;!(s.interaction_revision===r.interaction_revision&&o(s)<o(r))&&(!s.interaction_revision||!r.interaction_revision||s.interaction_revision>=r.interaction_revision)&&(e[n]={...r,...s})}}return e}const Os=new Set(["user","ai","assistant","operator","support","system"]);function Nt(i){if(!i||typeof i!="object")return null;const t=i,e=typeof t.id=="number"?String(t.id):t.id;if(typeof e!="string"||e===""||typeof t.content!="string"||typeof t.role!="string"||!Os.has(t.role))return null;const s={id:e,role:t.role,content:t.content};return typeof t.created_at=="string"&&(s.created_at=t.created_at),(t.type==="interaction"||t.type==="message")&&(s.type=t.type),s}const rt=i=>["pending","accepted"].includes(i.interaction_status);class Rs{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 s=e.length;for(;s>0&&e[s-1].kind!=="divider";)s-=1;const n=e.slice(s);return[...e.slice(0,s),...Ms(t(Us(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 s=this._active,n=s?.interaction_id===t.interactionId&&s.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?I(t.original):o))}mergeProjection(t,e){const s=I(e),n=t&&this.operations.get(t.interaction_id);n&&s?.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&&I(t),s?.role==="user"?s:null].filter(o=>o!==null);this.setRows(o=>{const a=n&&s?.role==="user"&&o.some(c=>c.id===n.messageId)?o.flatMap(c=>c.id===n.messageId?[s]:c.id===s.id?[]:[c]):o;return Mt(a,r)})}refreshMissingOutcome(t){if(this.operations.size===0){this.recoveryCursor=null;return}if((this.recoveryCursor===null||X(t,this.recoveryCursor)>0)&&(this.recoveryCursor=t),this.refreshInFlight)return;const e=this.recoveryCursor,s=[...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||!s.some(n))return;const c=Ut(a.interaction_cursor);if(c===null||X(c,this.recoveryCursor??e)<0||X(c,this._cursor)<0)return;const h=a.active_interaction===null?null:J(a.active_interaction);if(a.active_interaction!==null&&(!h||!rt(h)))return;const d=a.messages.map(I).filter(g=>g!==null),l=I(a.interaction_response_message);h&&d.push(I(h)),l?.role==="user"&&d.push(l);const p=s.filter(g=>n(g)&&(h?.interaction_id!==g.interactionId||h.interaction_status==="accepted"&&l?.role==="user")),f=new Set(p.map(g=>g.messageId));this.setRows(g=>Mt(g.filter(w=>!f.has(w.id)),d).sort((w,pt)=>Date.parse(w.ts)-Date.parse(pt.ts)||0)),p.forEach(g=>this.operations.delete(g.interactionId)),this.operation&&p.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&&s.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&&X(a,e)>0&&this.refreshMissingOutcome(a)}})}hasMissingOutcome(t){return[...this.operations.values()].some(e=>!t||e.interactionId!==t.interaction_id)}applySnapshot(t){const e=Ut(t.interaction_cursor);if(e===null||!Object.prototype.hasOwnProperty.call(t,"active_interaction"))return;const s=X(e,this._cursor);if(s<0)return;const n=t.active_interaction===null?null:J(t.active_interaction);if(!(t.active_interaction!==null&&(!n||!rt(n)))){if(s>0&&this.hasMissingOutcome(n)){this.refreshMissingOutcome(e);return}s===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=Ut(t.payload.interaction_cursor),s=J(t.payload);return!s||s.interaction_status==="preparing"||e===null||X(e,this._cursor)<=0?!0:this.hasMissingOutcome(s)||!rt(s)&&this.operations.has(s.interaction_id)&&!I(t.payload.interaction_response_message)?(this.refreshMissingOutcome(e),!0):(this._cursor=e,this.setCursor(e),this.mergeProjection(s,t.payload.interaction_response_message),rt(s)?this.setActive(s):this._active?.interaction_id===s.interaction_id&&this.setActive(null),this.operation&&(this.operation.interactionId!==s.interaction_id||!rt(s))&&(this.operation=null,this.setSelectionPending(!1)),!0)}handleWriteResult(t){const e=t,s=[...this.operations.values()].find(n=>n.messageId===e.message_id);if(!s)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(s,{code:n,message:String(e.error||e.reason||"The selection was not accepted. Please try again.")})}else s.acknowledged=!0,this.operation===s&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(null);return!0}respond(t,e){const s=this._active;if(!this.host.sessionId()||this.host.humanConnected()||this.operation||!s||s.interaction_id!==t||s.interaction_status!=="pending"||!It.some(h=>h.tool_type===s.tool_type&&h.schema_version===s.schema_version)||!ve(s,e))return!1;const n=s.tool_type==="ui_buttons"&&s.schema_version===1;let r=null;if(n&&e.kind==="selection"&&ye(s.presentation))r=s.presentation.options.find(h=>h.id===e.value)?.label??null;else if(!n&&e.kind==="text"&&s.tool_type==="ui_buttons"&&yt(s.presentation))r=e.value;else if(!n&&e.kind==="selection"&&s.tool_type==="ui_buttons"&&yt(s.presentation))r=s.presentation.options.find(h=>h.id===e.value)?.label??null;else if(e.kind==="selection"&&s.tool_type==="ui_carousel"&&be(s.presentation,void 0,!0))r=s.presentation.items.find(h=>h.id===e.value)?.title??null;else if(e.kind==="date"&&s.tool_type==="ui_date_picker"&&s.schema_version===1&&Ot(s.presentation)&&s.presentation.selection_mode==="single")(!s.presentation.min_date||e.value>=s.presentation.min_date)&&(!s.presentation.max_date||e.value<=s.presentation.max_date)&&(r=e.value);else if(e.kind==="date_range"&&s.tool_type==="ui_date_picker"&&s.schema_version===1&&Ot(s.presentation)&&s.presentation.selection_mode==="range"){const{start_date:h,end_date:d}=e.value;(!s.presentation.min_date||h>=s.presentation.min_date)&&(!s.presentation.max_date||d<=s.presentation.max_date)&&(r=`${h} to ${d}`)}if(!r)return!1;const o=this.host.newId(),a={interactionId:t,messageId:o,original:s,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:It}};this.operations.set(t,a),this.operation=a,this.setSelectionPending(!0),this.setInteractionError(null);const c={...s,interaction_status:"accepted",...n?{selected_option_id:e.value}:{response_payload:e}};return this.setActive(c),this.setRows(h=>Mt(h,[I(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 Us(i){const t=[];for(const e of i)e.kind==="interaction"?t.push(I(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 Ms(i,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 s=[];for(const n of i){if(n.type==="interaction"&&n.interaction_id){const o=J(n);o&&s.push({kind:"interaction",id:n.interaction_id,interaction:o});continue}if(n.role==="system")continue;const r=e.get(n.id);if(r){s.push(r.content===n.content?r:{...r,content:n.content});continue}if(n.local){s.push({kind:"message",id:n.id,role:"user",content:n.content,createdAt:n.ts,status:"sending"});continue}s.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 s}function Ns(i){let t=i;if(typeof i=="string")try{t=JSON.parse(i)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const e=t;if(typeof e.type!="string")return null;const s=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{};return{...e,type:e.type,payload:s}}const Ds=25e3,Bs=6e4,js=3e4,$e=6e4,ot=[1e3,2e3,4e3,8e3,16e3,3e4],Dt=1e4,Fs=4e3,Ls=2,we=new Set(["invalid_token","session_not_found","session_closed","origin_not_allowed","agent_archived","agent_not_found"]);function Se(){return{isVisible:()=>typeof document>"u"||document.visibilityState!=="hidden",onVisible:i=>{const t=()=>{document.visibilityState!=="hidden"&&i()};return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))},onOnline:i=>typeof window>"u"?()=>{}:(window.addEventListener("online",i),()=>window.removeEventListener("online",i))}}function at(i){i&&(i.onopen=null,i.onmessage=null,i.onclose=null,i.onerror=null)}class Hs{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??Se(),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){at(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(s){if(this.stopped||t!==this.epoch)return;this.handleMintFailure(s);return}if(!(this.stopped||t!==this.epoch))try{this.openSocket(e,!1)}catch(s){this.handleMintFailure(s)}}openSocket(t,e){const s=new this.WS(this.urlFor(t));e?this.next=s:(this.socket=s,this.expiresAt=t.expiresAt),s.onopen=()=>{this.stopped||(e?this.next===s&&this.swapIn(s,t.expiresAt):this.socket===s&&this.handleOpen())},s.onmessage=n=>{this.socket===s&&this.handleMessage(n.data)},s.onclose=n=>{if(!this.stopped){if(this.next===s){at(s),this.next=null,this.later(Dt,()=>this.whenVisible(()=>{this.rotate()}));return}this.socket===s&&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 s=this.socket;this.next=null,this.socket=t,this.expiresAt=e,this.failures=0,this.authCloses=0,this.pingSupported=!0,at(s);try{s?.close(Fs,"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=Ns(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,at(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>Ls){this.opts.onError(v("invalid_token")),this.scheduleBackoff();return}this.opts.onStatus(this.recoveringStatus()),this.whenVisible(()=>this.reconnectNow());return}if(t===1008&&e==="agent_inactive"){this.opts.onError(v("agent_inactive")),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later($e,()=>this.reconnectNow());return}if(t===1008){this.terminate(e||"policy");return}this.scheduleBackoff()}}handleMintFailure(t){const e=t instanceof S?t.error:v("network");if(e.code==="agent_inactive"){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later($e,()=>this.reconnectNow());return}if(we.has(e.code)){this.terminate(e.code);return}if(e.code==="rate_limited"&&e.retryAfterSeconds){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(e.retryAfterSeconds*1e3,()=>this.reconnectNow());return}this.scheduleBackoff()}reconnectNow(){this.stopped||(this.opts.onStatus(this.recoveringStatus()),this.connect())}scheduleBackoff(){if(this.stopped)return;const t=Math.min(this.failures,ot.length-1);if(this.failures+=1,this.failures>ot.length){this.opts.onStatus("offline"),this.retryWhenReachable();return}this.opts.onStatus(this.recoveringStatus());const e=Math.round(ot[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)},s=()=>{t||this.stopped||(t=!0,e(),this.reconnectNow())},n=this.page.onVisible(s),r=this.page.onOnline(s),o=setTimeout(()=>{this.stopped||s()},ot[ot.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 s=this.page.onVisible(()=>{e||this.stopped||!this.page.isVisible()||(e=!0,s(),this.waitingForPage.delete(s),t())});this.waitingForPage.add(s)}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>=Bs){this.declareDead();return}this.send({type:"ping"})&&(this.lastPingSentAt=t)},Ds)}declareDead(){const t=this.socket;if(t){at(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()-js);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(s){if(this.stopped||t!==this.epoch)return;this.rotating=!1;const n=s instanceof S?s.error:v("network");if(we.has(n.code)){this.terminate(n.code);return}const r=n.retryAfterSeconds?n.retryAfterSeconds*1e3:Dt;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(Dt,()=>this.whenVisible(()=>{this.rotate()}))}}}terminate(t){this.stop(),this.opts.onClosed(t)}later(t,e){if(this.stopped)return;const s=setTimeout(()=>{this.timers.delete(s),this.stopped||e()},t);this.timers.add(s)}clearPageListeners(){this.waitingForPage.forEach(t=>t()),this.waitingForPage.clear()}clearTimers(){this.timers.forEach(clearTimeout),this.timers.clear()}}const Bt="osvi.chat.visitor",Vs=/^web:[0-9a-f]{32}$/;function qs(){const i=new Map;return{get:t=>i.get(t)??null,set:(t,e)=>{i.set(t,e)},remove:t=>{i.delete(t)}}}function Ws(){const i=qs();let t=!1;const e=(s,n)=>{if(t)return n();try{return s()}catch{return t=!0,n()}};return{get:s=>e(()=>window.localStorage.getItem(s),()=>i.get(s)),set:(s,n)=>e(()=>window.localStorage.setItem(s,n),()=>i.set(s,n)),remove:s=>e(()=>window.localStorage.removeItem(s),()=>i.remove(s))}}const Ae=i=>`web:${Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}`;let jt=null;function ct(i,t){const e=i.get(Bt);if(e&&Vs.test(e))return e;e!==null&&i.remove(Bt);let s;try{s=globalThis.crypto?.getRandomValues?.(new Uint8Array(16))}catch{}if(s){const n=Ae(s);return i.set(Bt,n),n}if(!jt){const n=new Uint8Array(16);for(let r=0;r<n.length;r+=1)n[r]=Math.floor(Math.random()*256);jt=Ae(n)}return jt}function Ft(i){return`osvi.chat.session.${i}`}const zs="https://api.osvi.ai",Gs=12e4,Ks=15e3,ke=[1e3,2e3,4e3,8e3,16e3],Ys=2048,Js=new Set(["session_closed","session_dormant","new_session"]);function bt(){const i=globalThis.crypto;if(i?.randomUUID)return i.randomUUID();if(i?.getRandomValues){const t=i.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,s=>s.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 Ce=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Te={user:"user",ai:"assistant",assistant:"assistant",operator:"human",support:"human"};class Xs{constructor(t){this.opts=t,this.state=Ce(),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 ws(t.baseUrl??zs,t.fetch),this.store=t.store??Ws(),this.page=t.page??Se(),this.interactions=new Rs({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:bt})}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(Ft(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 s=bt(),n=bt(),r={kind:"message",id:s,role:"user",content:e,createdAt:new Date().toISOString(),status:"sending",idempotencyKey:n};return this.patch({items:[...this.state.items,r]}),this.pending.set(s,{frame:this.frameFor(r),attempts:0,gen:-1,ackTimer:null}),await this.ensureSession()?(this.transmit(s),{ok:!0,messageId:s}):(this.dropPending(s),this.setMessage(s,{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(s=>s.kind==="message"&&s.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=Ce(),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 s=await this.http.createSession(this.opts.agentId,t);return this.destroyed?null:(this.adopt(s.id,null,"keep"),this.sessionId)}catch(t){return this.fail(t,!1),null}}async openServerSession(t){const e=this.sessionGeneration;try{let s=t?this.accept(t):await this.serverToken(e);this.assertCurrent(e),this.latestToken=s.token;let n;try{n=await this.http.snapshot(s.sessionId,s.token)}catch(r){if(this.assertCurrent(e),!(r instanceof S)||r.error.code!=="invalid_token")throw r;s=await this.serverToken(e),this.assertCurrent(e),this.latestToken=s.token,n=await this.http.snapshot(s.sessionId,s.token)}return this.assertCurrent(e),this.adopt(s.sessionId,n,this.state.items.length?"append":"replace",s),this.sessionId}catch(s){return this.isCurrent(e)&&this.fail(s,!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 s=this.wantNewServerSession;this.wantNewServerSession=!1;try{e=await(s?this.opts.auth.getToken({newSession:!0}):this.opts.auth.getToken())}catch{throw new S(v("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:fe(t.expiresAt)}}checkWsUrl(t){let e=null;try{e=new URL(t)}catch{}const s=e?.hostname==="localhost"||e?.hostname==="127.0.0.1";if(e&&(e.protocol==="wss:"||e.protocol==="ws:"&&s))return;const n=v("token_failed","The chat stream URL must use wss://");throw new S(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 S(v("session_closed"),0)}adopt(t,e,s,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(Ft(this.opts.agentId),t),e&&this.applySnapshot(e,s);let a=n??null;const c=this.serverMode?null:ct(this.store);let h=!0,d=!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 S(v("session_closed"),0);return this.latestToken=g.token,g}const p=h;h=!1;let f;try{f=await this.http.mintPublicToken(t)}catch(g){throw d=p&&r&&this.isCurrent(o,t)&&g instanceof S&&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(f.wsUrl)}catch(g){throw this.fail(g,!1),g}return this.latestToken=f.token,f};this.conn=new Hs({mint:l,sdkVersion:ys,page:this.page,random:this.opts.random,WebSocketImpl:this.opts.WebSocketImpl,onFrame:p=>this.onFrame(p),onStatus:p=>this.patch({status:p,...p==="open"?{error:null}:{}}),onOpen:()=>this.onOpen(),onReconnected:()=>{this.recover()},onError:p=>this.patch({error:p}),onClosed:p=>{if(!this.isCurrent(o,t))return;if(d&&c&&p==="session_not_found"){d=!1,this.serialize(()=>this.replaceBeforeFirstWrite(o,t,c));return}const f=this.switchTo;this.switchTo=null,this.endSession(p),f&&this.serialize(()=>this.openServerSession(f))}}),this.conn.start()}async replaceBeforeFirstWrite(t,e,s){if(this.isCurrent(t,e))try{const n=await this.http.bootstrap(this.opts.agentId,s);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!==s||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,s=await this.fetchSnapshot();s&&t&&this.isCurrent(e,t)&&this.applySnapshot(s,"reconcile")}async fetchSnapshot(){if(this.destroyed)return null;const t=this.sessionId,e=this.sessionGeneration;if(!t)return null;try{try{const s=await this.http.snapshot(t,this.latestToken??await this.mintFresh(t));return this.isCurrent(e,t)?s:null}catch(s){if(this.assertCurrent(e,t),!(s instanceof S)||s.error.code!=="invalid_token")throw s;const n=await this.http.snapshot(t,await this.mintFresh(t));return this.isCurrent(e,t)?n:null}}catch(s){if(s instanceof S&&s.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 s=await this.http.mintPublicToken(t);return this.assertCurrent(e,t),this.checkWsUrl(s.wsUrl),this.latestToken=s.token,s.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(Ft(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),s=e[e.length-1],n={kind:"divider",id:bt(),reason:"session_ended"};this.setAwaiting(!1),this.patch({status:"closed",mode:"ai",items:e.length&&s?.kind!=="divider"?[...e,n]:e,...Js.has(t)?{}:{error:v(t)}})}onFrame(t){if(this.destroyed)return;if(t.event_id!==void 0){const s=String(t.event_id);if(this.seenSet.has(s))return;this.seenSet.add(s),this.seen.push(s),this.seen.length>Ys&&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 s=Nt(e);if(!s)return;s.role==="user"?this.onUserEcho(s.id,s.content,s.created_at,typeof e.message_id=="string"?e.message_id:void 0):this.appendRemote(s.id,s.role,s.content,s.created_at);return}case"operator_message":{const s=Nt({...e,role:"operator"});s&&this.appendRemote(s.id,"operator",s.content,s.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 s=this.pending.get(e);if(s){if(s.ackTimer&&(clearTimeout(s.ackTimer),s.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"&&s.attempts<ke.length){const n=ke[s.attempts];s.attempts+=1,this.later(n,()=>{this.pending.get(e)===s&&(s.gen=-1,this.transmit(e))});return}this.pending.delete(e),this.setMessage(e,{status:"failed"}),this.patch({error:v(t.error,t.error)})}}onUserEcho(t,e,s,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,s)}appendRemote(t,e,s,n){const r=Te[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:s,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 s=[],n=new Map;for(const c of t.messages??[]){const h=J(c);if(h){s.push({kind:"interaction",id:h.interaction_id,interaction:h});continue}const d=Nt(c),l=d?Te[d.role]:void 0;if(d&&l){s.push({kind:"message",id:`srv:${d.id}`,serverId:d.id,role:l,content:d.content,createdAt:d.created_at??new Date().toISOString(),status:"sent"});const p=c.message_id;typeof p=="string"&&n.set(d.id,p)}}let r=this.state.items;if(e==="replace")r=s;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),...s,...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 s){const d=h.kind==="message"?h.serverId:h.id;if(h.kind==="message"&&h.role==="user"&&!c.has(d)){const l=n.get(h.serverId),p=r.findIndex(f=>f.kind==="message"&&f.role==="user"&&!f.serverId&&(l?f.id===l:f.content===h.content));if(p>=0){const f=r[p];r=r.slice(),r[p]={...f,serverId:h.serverId,status:"sent"},this.dropPending(f.id),c.add(d);continue}}c.has(d)||(r=[...r,h],c.add(d))}}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:It}}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)},Ks))}async onAckTimeout(t){const e=this.pending.get(t);if(!e||this.destroyed||(e.ackTimer=null,!this.conn?.isOpen))return;const s=this.openGen;await this.recover(),!(this.destroyed||this.pending.get(t)!==e||!this.conn?.isOpen||s!==this.openGen)&&(this.dropPending(t),this.setMessage(t,{status:"failed"}),this.patch({error:v("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})},Gs)),this.state.awaitingReply!==t&&this.patch({awaitingReply:t})}setMessage(t,e){this.patch({items:this.state.items.map(s=>s.kind==="message"&&s.id===t?{...s,...e}:s)})}fail(t,e){const s=t instanceof S?t.error:v("network","Network error");this.patch({error:s,...e||!s.retryable?{status:"closed"}:{}})}later(t,e){const s=setTimeout(()=>{this.timers.delete(s),this.destroyed||e()},t);this.timers.add(s)}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 Zs(i){return new Xs(i)}const Ie={primary:"#4f46e5",background:"#ffffff",surface:"#f4f4f5",text:"#18181b",userBubble:"#4f46e5",assistantBubble:"#f4f4f5"},Qs={primary:"#6366f1",background:"#0a0a12",surface:"#1c1c27",text:"#f4f4f5",userBubble:"#6366f1",assistantBubble:"#1f1f2b"},ti={none:"0px",sm:"6px",md:"10px",lg:"16px",full:"9999px"},ht={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"},j=i=>`var(${ht[i]}, ${Ie[i]})`;function Lt(i){const t={...i?.mode==="dark"?Qs:Ie,...i?.colors},e={};for(const n of Object.keys(ht))e[ht[n]]=t[n];const s=i?.radius??"md";return e["--osvi-radius"]=typeof s=="number"?`${s}px`:ti[s],e}function Ee(i){if(!i)return{};if(i.mode)return Lt(i);const t=Lt(i),e={};for(const s of Object.keys(i.colors??{}))e[ht[s]]=t[ht[s]];return i.radius!==void 0&&(e["--osvi-radius"]=t["--osvi-radius"]),e}const xe=new WeakMap;function Ht(i,t){for(const s of xe.get(i)??[])i.style.removeProperty(s);const e=Ee(t);for(const[s,n]of Object.entries(e))i.style.setProperty(s,n);xe.set(i,Object.keys(e))}const Vt={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"},Pe=new Set;function Oe(i,t){Pe.has(i)||(Pe.add(i),console.warn(`[osvi-chat] ${t}`))}function F(i,t){return i!=null&&t.includes(i)?i:void 0}function Re(i){if(i!=null)return F(i,["none","sm","md","lg","full"])??(/^\d{1,2}(?:px)?$/.test(i)?Number(i.replace(/px$/,"")):void 0)}function Ue(i){if(i){try{const t=new URL(i);if(!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1"].includes(t.hostname)))return i.replace(/\/+$/,"")}catch{}Oe("base-url","ignored an invalid base-url (https required, http only for localhost)")}}function ei(i){if(i){if(/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/]+={0,2}$/i.test(i))return i;try{const t=new URL(i);if(t.protocol==="https:"&&!t.username&&!t.password)return i}catch{}}}function Me(i,t){if(t){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}Oe(i,`ignored invalid JSON in the ${i} attribute`)}}const L={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4},Ne=i=>(...t)=>({_$litDirective$:i,values:t});let De=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,s){this._$Ct=t,this._$AM=e,this._$Ci=s}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const{I:si}=us,Be=i=>i,ii=i=>i.strings===void 0,je=()=>document.createComment(""),lt=(i,t,e)=>{const s=i._$AA.parentNode,n=t===void 0?i._$AB:t._$AA;if(e===void 0){const r=s.insertBefore(je(),n),o=s.insertBefore(je(),n);e=new si(r,o,i,i.options)}else{const r=e._$AB.nextSibling,o=e._$AM,a=o!==i;if(a){let c;e._$AQ?.(i),e._$AM=i,e._$AP!==void 0&&(c=i._$AU)!==o._$AU&&e._$AP(c)}if(r!==n||a){let c=e._$AA;for(;c!==r;){const h=Be(c).nextSibling;Be(s).insertBefore(c,n),c=h}}}return e},H=(i,t,e=i)=>(i._$AI(t,e),i),ni={},Fe=(i,t=ni)=>i._$AH=t,ri=i=>i._$AH,qt=i=>{i._$AR(),i._$AA.remove()};const Le=(i,t,e)=>{const s=new Map;for(let n=t;n<=e;n++)s.set(i[n],n);return s},oi=Ne(class extends De{constructor(i){if(super(i),i.type!==L.CHILD)throw Error("repeat() can only be used in text expressions")}dt(i,t,e){let s;e===void 0?e=t:t!==void 0&&(s=t);const n=[],r=[];let o=0;for(const a of i)n[o]=s?s(a,o):o,r[o]=e(a,o),o++;return{values:r,keys:n}}render(i,t,e){return this.dt(i,t,e).values}update(i,[t,e,s]){const n=ri(i),{values:r,keys:o}=this.dt(t,e,s);if(!Array.isArray(n))return this.ut=o,r;const a=this.ut??(this.ut=[]),c=[];let h,d,l=0,p=n.length-1,f=0,g=r.length-1;for(;l<=p&&f<=g;)if(n[l]===null)l++;else if(n[p]===null)p--;else if(a[l]===o[f])c[f]=H(n[l],r[f]),l++,f++;else if(a[p]===o[g])c[g]=H(n[p],r[g]),p--,g--;else if(a[l]===o[g])c[g]=H(n[l],r[g]),lt(i,c[g+1],n[l]),l++,g--;else if(a[p]===o[f])c[f]=H(n[p],r[f]),lt(i,n[l],n[p]),p--,f++;else if(h===void 0&&(h=Le(o,f,g),d=Le(a,l,p)),h.has(a[l]))if(h.has(a[p])){const w=d.get(o[f]),pt=w!==void 0?n[w]:null;if(pt===null){const Ge=lt(i,n[l]);H(Ge,r[f]),c[f]=Ge}else c[f]=H(pt,r[f]),lt(i,n[l],pt),n[w]=null;f++}else qt(n[p]),p--;else qt(n[l]),l++;for(;f<=g;){const w=lt(i,c[g+1]);H(w,r[f]),c[f++]=w}for(;l<=p;){const w=n[l++];w!==null&&qt(w)}return this.ut=o,Fe(i,c),k}}),ai=/https?:\/\/[^\s<>"']+/g,vt=(i,t)=>i.split(t).length-1;function ci(i){for(;;){const t=i[i.length-1];if(t&&".,!?;:".includes(t)||t===")"&&vt(i,")")>vt(i,"(")||t==="]"&&vt(i,"]")>vt(i,"[")){i=i.slice(0,-1);continue}return i}}function hi(i){const t=[];let e=0;for(const s of i.matchAll(ai)){const n=ci(s[0]),r=s.index;try{const o=new URL(n);if(!["http:","https:"].includes(o.protocol))continue}catch{continue}r>e&&t.push({text:i.slice(e,r)}),t.push({href:n,text:n}),e=r+n.length}return e<i.length&&t.push({text:i.slice(e)}),t.length?t:[{text:i}]}function li(i,t,e,s,n){return u`${i.items.length?oi(i.items,r=>r.id,r=>{if(r.kind==="divider")return u`<p class="divider">${t.sessionEnded}</p>`;if(r.kind==="message")return u`<article class=${`bubble ${r.role}`}>${r.role==="human"?u`<small>Team</small>`:m}<p>${hi(r.content).map(h=>"href"in h?u`<a href=${h.href} target="_blank" rel="noopener noreferrer">${h.text}</a>`:h.text)}</p>${r.role==="user"&&r.status==="failed"?u`<span>${t.sendFailed}</span><button type="button" @click=${()=>n(r.id)}>${t.retry}</button>`:m}</article>`;const o=r.interaction,a=o.interaction_id===i.activeInteraction?.interaction_id&&o.interaction_status==="pending",c=!a||i.interactionPending||i.mode==="human";switch(o.tool_type){case"ui_buttons":return u`<osvi-buttons data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.buttons??"chips"} base-url=${s}></osvi-buttons>`;case"ui_carousel":return u`<osvi-carousel data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.carousel??"slider"} base-url=${s}></osvi-carousel>`;case"ui_date_picker":return u`<osvi-date-picker data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} base-url=${s}></osvi-date-picker>`;default:return u`<p>${o.content}</p>`}}):u`<p>${t.emptyState}</p>`}${i.awaitingReply?u`<p aria-label=${t.typing}>${t.typing}<span aria-hidden="true"> •••</span></p>`:m}`}const di=Ne(class extends De{constructor(i){if(super(i),i.type!==L.PROPERTY&&i.type!==L.ATTRIBUTE&&i.type!==L.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!ii(i))throw Error("`live` bindings can only contain a single expression")}render(i){return i}update(i,[t]){if(t===k||t===m)return t;const e=i.element,s=i.name;if(i.type===L.PROPERTY){if(t===e[s])return k}else if(i.type===L.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(s))return k}else if(i.type===L.ATTRIBUTE&&e.getAttribute(s)===t+"")return k;return Fe(i),t}});function ui(i){return u`<div class="composer"><textarea aria-label="Message" placeholder=${i.placeholder} .value=${di(i.draft)} ?disabled=${i.disabled} @input=${i.input} @keydown=${t=>{t.key==="Enter"&&!t.shiftKey&&!t.isComposing&&!i.disabled&&(t.preventDefault(),i.send())}}></textarea><button type="button" aria-label=${i.strings.send} ?disabled=${i.disabled||!i.draft.trim()} @click=${i.send}>${i.strings.send}</button></div>`}var pi=Object.defineProperty,b=(i,t,e,s)=>{for(var n=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(n=o(t,e,n)||n);return n&&pi(t,e,n),n};const He=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Ve={fromAttribute:i=>i!=="false"},y=(E=class extends Y{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=He(),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(),s=this.typed;this.draft="",s&&this.restoreDraft(),this.requestUpdate(),this.run(()=>s?t.respond(s.id,{kind:"text",value:e}):t.send(e))},this.respond=t=>{const e=t.detail,s=this.chatState;if(!e||this.busy||s.mode!=="ai"||s.interactionPending||s.activeInteraction?.interaction_status!=="pending"||e.interactionId!==s.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,s=this.chatState;!e||this.busy||s.mode!=="ai"||s.interactionPending||s.activeInteraction?.interaction_status!=="pending"||e.interactionId!==s.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,Ue(this.baseUrl)]);if((this.client?this.boundClient===this.client&&!this.ownClient:this.ownClient&&t===this.ownKey)||(this.releaseClient(),this.chatState=He(),!this.client&&!this.agentId))return;const e=!this.client,s=this.client??E.clientFactory({agentId:this.agentId,baseUrl:Ue(this.baseUrl)});this.boundClient=s,e&&(this.ownClient=s,this.ownKey=t);const n=this.generation;this.chatState=s.getState(),this.requestUpdate(),this.unsubscribe=s.subscribe(r=>{this.generation!==n||this.boundClient!==s||(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(()=>s.start())}willUpdate(){this.syncClient(),Ht(this,this.mergedTheme())}mergedTheme(){const t=Me("theme",this.themeAttribute),e={},s=t?.colors;if(s&&typeof s=="object"&&!Array.isArray(s))for(const o of["primary","background","surface","text","userBubble","assistantBubble"]){const a=s[o];typeof a=="string"&&(e[o]=a)}typeof this.primaryColor=="string"&&(e.primary=this.primaryColor);const n=Re(this.radius)??(typeof t?.radius=="number"&&Number.isInteger(t.radius)&&t.radius>=0&&t.radius<=99?t.radius:typeof t?.radius=="string"?Re(t.radius):void 0),r=F(this.mode,["light","dark"])??F(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={...Vt};for(const e of[this.strings,Me("strings",this.stringsAttribute)])for(const s of Object.keys(Vt))typeof e?.[s]=="string"&&(t[s]=e[s]);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,s=this.boundClient,n=ei(this.headerAvatar??this.header.avatarUrl),r={...this.variants,...F(this.buttons,["chips","list"])?{buttons:F(this.buttons,["chips","list"])}:{},...F(this.carousel,["slider","list"])?{carousel:F(this.carousel,["slider","list"])}:{}};return u`<header>${n?u`<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?u`<p>${this.headerSubtitle??this.header.subtitle}</p>`:m}${e.mode==="human"?u`<small>${t.humanJoined}</small>`:m}</div>
|
|
4
|
-
${this.newChat?u`<button type="button" ?disabled=${!
|
|
5
|
-
${this.closable?u`<button type="button" aria-label=${t.closeChat} @click=${()=>this.dispatchEvent(new CustomEvent("osvi-close",{bubbles:!0,composed:!0}))}
|
|
6
|
-
<div class="transcript" role="log" aria-live="polite" aria-label="Conversation" @scroll=${
|
|
7
|
-
<div class="status" role="status">${this.statusText(t)}${e.error?.retryable&&(e.status==="idle"||e.status==="closed")?u`<button type="button" ?disabled=${this.busy||!
|
|
8
|
-
${
|
|
9
|
-
${this.poweredBy?u`<footer><a href="https://osvi.ai" target="_blank" rel="noopener noreferrer">${t.poweredBy}</a></footer>`:m}`}},E.clientFactory=
|
|
10
|
-
:host {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
1
|
+
var OsviChatUi=(function(S){"use strict";var E;const ft=globalThis,kt=ft.ShadowRoot&&(ft.ShadyCSS===void 0||ft.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,At=Symbol(),Qt=new WeakMap;let te=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==At)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(kt&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=Qt.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Qt.set(e,t))}return t}toString(){return this.cssText}};const ee=s=>new te(typeof s=="string"?s:s+"",void 0,At),ie=(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 te(e,s,At)},ti=(s,t)=>{if(kt)s.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),n=ft.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},se=kt?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return ee(e)})(s):s;const{is:ei,defineProperty:ii,getOwnPropertyDescriptor:si,getOwnPropertyNames:ni,getOwnPropertySymbols:ri,getPrototypeOf:oi}=Object,P=globalThis,ne=P.trustedTypes,ai=ne?ne.emptyScript:"",ci=P.reactiveElementPolyfillSupport,Z=(s,t)=>s,gt={toAttribute(s,t){switch(t){case Boolean:s=s?ai: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}},Ct=(s,t)=>!ei(s,t),re={attribute:!0,type:String,converter:gt,reflect:!1,useDefault:!1,hasChanged:Ct};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),P.litPropertyMetadata??(P.litPropertyMetadata=new WeakMap);let W=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=re){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&&ii(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){const{get:n,set:r}=si(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)??re}static _$Ei(){if(this.hasOwnProperty(Z("elementProperties")))return;const t=oi(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Z("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Z("properties"))){const e=this.properties,i=[...ni(e),...ri(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(se(n))}else t!==void 0&&e.push(se(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 ti(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:gt).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:gt;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??Ct)(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){}};W.elementStyles=[],W.shadowRootOptions={mode:"open"},W[Z("elementProperties")]=new Map,W[Z("finalized")]=new Map,ci?.({ReactiveElement:W}),(P.reactiveElementVersions??(P.reactiveElementVersions=[])).push("2.1.2");const Q=globalThis,oe=s=>s,mt=Q.trustedTypes,ae=mt?mt.createPolicy("lit-html",{createHTML:s=>s}):void 0,ce="$lit$",O=`lit$${Math.random().toFixed(9).slice(2)}$`,le="?"+O,li=`<${le}>`,D=document,tt=()=>D.createComment(""),et=s=>s===null||typeof s!="object"&&typeof s!="function",Tt=Array.isArray,hi=s=>Tt(s)||typeof s?.[Symbol.iterator]=="function",It=`[
|
|
2
|
+
\f\r]`,it=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,he=/-->/g,de=/>/g,B=RegExp(`>|${It}(?:([^\\s"'>=/]+)(${It}*=${It}*(?:[^
|
|
3
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),ue=/'/g,pe=/"/g,fe=/^(?:script|style|textarea|title)$/i,ge=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),u=ge(1),A=ge(2),k=Symbol.for("lit-noChange"),m=Symbol.for("lit-nothing"),me=new WeakMap,L=D.createTreeWalker(D,129);function ye(s,t){if(!Tt(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return ae!==void 0?ae.createHTML(t):t}const di=(s,t)=>{const e=s.length-1,i=[];let n,r=t===2?"<svg>":t===3?"<math>":"",o=it;for(let a=0;a<e;a++){const c=s[a];let l,f,h=-1,d=0;for(;d<c.length&&(o.lastIndex=d,f=o.exec(c),f!==null);)d=o.lastIndex,o===it?f[1]==="!--"?o=he:f[1]!==void 0?o=de:f[2]!==void 0?(fe.test(f[2])&&(n=RegExp("</"+f[2],"g")),o=B):f[3]!==void 0&&(o=B):o===B?f[0]===">"?(o=n??it,h=-1):f[1]===void 0?h=-2:(h=o.lastIndex-f[2].length,l=f[1],o=f[3]===void 0?B:f[3]==='"'?pe:ue):o===pe||o===ue?o=B:o===he||o===de?o=it:(o=B,n=void 0);const p=o===B&&s[a+1].startsWith("/>")?" ":"";r+=o===it?c+li:h>=0?(i.push(l),c.slice(0,h)+ce+c.slice(h)+O+p):c+O+(h===-2?a:p)}return[ye(s,r+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]};class st{constructor({strings:t,_$litType$:e},i){let n;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[l,f]=di(t,e);if(this.el=st.createElement(l,i),L.currentNode=this.el.content,e===2||e===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(n=L.nextNode())!==null&&c.length<a;){if(n.nodeType===1){if(n.hasAttributes())for(const h of n.getAttributeNames())if(h.endsWith(ce)){const d=f[o++],p=n.getAttribute(h).split(O),g=/([.?@])?(.*)/.exec(d);c.push({type:1,index:r,name:g[2],strings:p,ctor:g[1]==="."?pi:g[1]==="?"?fi:g[1]==="@"?gi:yt}),n.removeAttribute(h)}else h.startsWith(O)&&(c.push({type:6,index:r}),n.removeAttribute(h));if(fe.test(n.tagName)){const h=n.textContent.split(O),d=h.length-1;if(d>0){n.textContent=mt?mt.emptyScript:"";for(let p=0;p<d;p++)n.append(h[p],tt()),L.nextNode(),c.push({type:2,index:++r});n.append(h[d],tt())}}}else if(n.nodeType===8)if(n.data===le)c.push({type:2,index:r});else{let h=-1;for(;(h=n.data.indexOf(O,h+1))!==-1;)c.push({type:7,index:r}),h+=O.length-1}r++}}static createElement(t,e){const i=D.createElement("template");return i.innerHTML=t,i}}function G(s,t,e=s,i){if(t===k)return t;let n=i!==void 0?e._$Co?.[i]:e._$Cl;const r=et(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=G(s,n._$AS(s,t.values),n,i)),t}class ui{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??D).importNode(e,!0);L.currentNode=n;let r=L.nextNode(),o=0,a=0,c=i[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new K(r,r.nextSibling,this,t):c.type===1?l=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(l=new mi(r,this,t)),this._$AV.push(l),c=i[++a]}o!==c?.index&&(r=L.nextNode(),o++)}return L.currentNode=D,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 K{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=G(this,t,e),et(t)?t===m||t==null||t===""?(this._$AH!==m&&this._$AR(),this._$AH=m):t!==this._$AH&&t!==k&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):hi(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&&et(this._$AH)?this._$AA.nextSibling.data=t:this.T(D.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=st.createElement(ye(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(e);else{const r=new ui(n,this),o=r.u(this.options);r.p(e),this.T(o),this._$AH=r}}_$AC(t){let e=me.get(t.strings);return e===void 0&&me.set(t.strings,e=new st(t)),e}k(t){Tt(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 K(this.O(tt()),this.O(tt()),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=oe(t).nextSibling;oe(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}class yt{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=G(this,t,e,0),o=!et(t)||t!==this._$AH&&t!==k,o&&(this._$AH=t);else{const a=t;let c,l;for(t=r[0],c=0;c<r.length-1;c++)l=G(this,a[i+c],e,c),l===k&&(l=this._$AH[c]),o||(o=!et(l)||l!==this._$AH[c]),l===m?t=m:t!==m&&(t+=(l??"")+r[c+1]),this._$AH[c]=l}o&&!n&&this.j(t)}j(t){t===m?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class pi extends yt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===m?void 0:t}}class fi extends yt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==m)}}class gi extends yt{constructor(t,e,i,n,r){super(t,e,i,n,r),this.type=5}_$AI(t,e=this){if((t=G(this,t,e,0)??m)===k)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 mi{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){G(this,t)}}const yi={I:K},bi=Q.litHtmlPolyfillSupport;bi?.(st,K),(Q.litHtmlVersions??(Q.litHtmlVersions=[])).push("3.3.3");const _i=(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 K(t.insertBefore(tt(),r),r,void 0,e??{})}return n._$AI(s),n};const nt=globalThis;let Y=class extends W{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=_i(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return k}};Y._$litElement$=!0,Y.finalized=!0,nt.litElementHydrateSupport?.({LitElement:Y});const vi=nt.litElementPolyfillSupport;vi?.({LitElement:Y}),(nt.litElementVersions??(nt.litElementVersions=[])).push("4.2.2");const $i={attribute:!0,type:String,converter:gt,reflect:!1,hasChanged:Ct},wi=(s=$i,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"?wi(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 C(s){return y({...s,state:!0,attribute:!1})}const xi="0.1.1",Si=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"]),ki=new Set(["rate_limited","network","session_unavailable","stream_unavailable","token_failed"]);function v(s,t){const e=s&&Si.has(s)?s:"unknown";return{code:e,message:t||e,retryable:ki.has(e)}}class x extends Error{constructor(t,e){super(t.message),this.error=t,this.status=e,this.name="ChatRequestError"}}const Ai=3e5;function be(s,t=Date.now()){return typeof s!="number"||!Number.isFinite(s)?t+Ai:s<1e12?s*1e3:s}class Ci{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 x(v("stream_unavailable"),200);return{token:e.token,wsUrl:e.ws_url,expiresAt:be(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 x(v("network","Network error"),0)}let n=null;try{n=await i.json()}catch{n=null}if(!i.ok||n?.success===!1){const r=v(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 x(r,i.status)}return n?.data??n}}const Et=[{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}],Ti=65536,Ii=2e3,Ei=8192,_e=2048,Pt=/^[A-Za-z0-9_-]{1,64}$/,T=s=>!!s&&typeof s=="object"&&!Array.isArray(s),R=(s,t)=>Object.keys(s).every(e=>t.includes(e)),Pi=s=>[...s].length,ve=s=>new TextEncoder().encode(s).length,Oi=s=>[...s].some(t=>{const e=t.codePointAt(0)??0;return e===127||e<32&&e!==9&&e!==10&&e!==13}),Ri=s=>[...s].some(t=>{const e=t.codePointAt(0)??0;return e<=32||e===127}),$=(s,t,e=!1)=>typeof s=="string"&&Pi(s)<=t&&!Oi(s)&&(!e||s.trim().length>0),Ot=s=>Array.isArray(s)?s.map(Ot):T(s)?Object.fromEntries(Object.keys(s).sort().map(t=>[t,Ot(s[t])])):s,Rt=s=>{try{return ve(JSON.stringify(Ot(s)))<=Ti}catch{return!1}};function $e(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 Mi(s){if(typeof s!="string"||s.length===0||s.length>_e||Ri(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<=_e}catch{return!1}}function bt(s,t){if(!T(s)||!R(s,["label","description","options"])||!$(s.label,160,!0)||"description"in s&&s.description!==void 0&&!$(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(!T(n)||!R(n,["id","label","description","allow_input","input_placeholder"])||typeof n.id!="string"||!Pt.test(n.id)||e.has(n.id)||!$(n.label,80,!0)||"description"in n&&n.description!==void 0&&!$(n.description,240))return!1;const r=n.allow_input===!0;if("allow_input"in n&&!r||"input_placeholder"in n&&(!r||!$(n.input_placeholder,160,!0))||(r&&(i+=1),i>1))return!1;e.add(n.id)}return Rt(s)}function we(s,t){return bt(s,t)&&s.options.every(e=>!Object.prototype.hasOwnProperty.call(e,"allow_input")&&!Object.prototype.hasOwnProperty.call(e,"input_placeholder"))}function xe(s,t,e=!1){if(!T(s)||!R(s,["label","description","items"])||!$(s.label,160,!0)||"description"in s&&s.description!==void 0&&!$(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(!T(n)||!R(n,["id","title","description","image","action_label"])||typeof n.id!="string"||!Pt.test(n.id)||i.has(n.id)||!$(n.title,120,!0)||"description"in n&&n.description!==void 0&&!$(n.description,500)||"action_label"in n&&n.action_label!==void 0&&!$(n.action_label,80,!0)||"image"in n&&n.image!==void 0&&(!T(n.image)||!R(n.image,["url","alt"])||!(Mi(n.image.url)||e&&$e(n.image.url))||!$(n.image.alt,240,!0)))return!1;i.add(n.id)}return Rt(s)}function M(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 Mt(s){return!T(s)||!R(s,["label","description","min_date","max_date","confirm_label","selection_mode"])||!$(s.label,160,!0)||!["single","range"].includes(String(s.selection_mode))||"description"in s&&s.description!==void 0&&!$(s.description,240)||"confirm_label"in s&&s.confirm_label!==void 0&&!$(s.confirm_label,80,!0)||"min_date"in s&&s.min_date!==void 0&&!M(s.min_date)||"max_date"in s&&s.max_date!==void 0&&!M(s.max_date)||typeof s.min_date=="string"&&typeof s.max_date=="string"&&s.min_date>s.max_date?!1:Rt(s)}function Ui(s,t){return s.tool_type==="ui_buttons"&&s.schema_version===1?we(t):s.tool_type==="ui_buttons"&&s.schema_version===2?bt(t):s.tool_type==="ui_carousel"&&s.schema_version===1?xe(t,void 0,!0):s.tool_type==="ui_date_picker"&&s.schema_version===1?Mt(t):!1}function Se(s,t){return!T(t)||!R(t,["kind","value"])||Object.keys(t).length!==2?!1:t.kind==="date_range"?s.tool_type==="ui_date_picker"&&s.schema_version===1&&T(t.value)&&R(t.value,["start_date","end_date"])&&Object.keys(t.value).length===2&&M(t.value.start_date)&&M(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")&&Pt.test(t.value):t.kind==="text"?s.tool_type==="ui_buttons"&&s.schema_version===2&&t.value===t.value.trim()&&$(t.value,Ii,!0)&&ve(t.value)<=Ei:t.kind==="date"?s.tool_type==="ui_date_picker"&&s.schema_version===1&&M(t.value):!1}const Ut=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),Ni=new Set(["preparing","pending","accepted","resumed","cancelled","expired"]);function J(s){if(!Ut(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||!Ni.has(String(s.interaction_status))||!Ut(s.presentation))return null;const t={tool_type:s.tool_type,schema_version:Number(s.schema_version)},e=s.response_payload;return e!=null&&!Se(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 I(s){if(!Ut(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=J({...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 Nt(s){return typeof s=="string"&&/^\d+$/.test(s)?s.replace(/^0+(?=\d)/,""):null}function X(s,t){return s.length===t.length?s===t?0:s>t?1:-1:s.length>t.length?1:-1}function Dt(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 Di=new Set(["user","ai","assistant","operator","support","system"]);function Bt(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"||!Di.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 rt=s=>["pending","accepted"].includes(s.interaction_status);class Bi{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),...ji(t(Li(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?I(t.original):o))}mergeProjection(t,e){const i=I(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&&I(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 Dt(a,r)})}refreshMissingOutcome(t){if(this.operations.size===0){this.recoveryCursor=null;return}if((this.recoveryCursor===null||X(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=Nt(a.interaction_cursor);if(c===null||X(c,this.recoveryCursor??e)<0||X(c,this._cursor)<0)return;const l=a.active_interaction===null?null:J(a.active_interaction);if(a.active_interaction!==null&&(!l||!rt(l)))return;const f=a.messages.map(I).filter(g=>g!==null),h=I(a.interaction_response_message);l&&f.push(I(l)),h?.role==="user"&&f.push(h);const d=i.filter(g=>n(g)&&(l?.interaction_id!==g.interactionId||l.interaction_status==="accepted"&&h?.role==="user")),p=new Set(d.map(g=>g.messageId));this.setRows(g=>Dt(g.filter(w=>!p.has(w.id)),f).sort((w,pt)=>Date.parse(w.ts)-Date.parse(pt.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(l),this.setSelectionPending(this.operation!==null),this.setInteractionError(null)}).catch(()=>{r===this.generation&&i.some(n)&&this.setInteractionError({code:"network",message:"Reconnecting to confirm your selection…"})}).finally(()=>{if(r===this.generation){if(this.refreshInFlight=!1,this.operations.size===0){this.recoveryCursor=null;return}const a=this.recoveryCursor;a!==null&&X(a,e)>0&&this.refreshMissingOutcome(a)}})}hasMissingOutcome(t){return[...this.operations.values()].some(e=>!t||e.interactionId!==t.interaction_id)}applySnapshot(t){const e=Nt(t.interaction_cursor);if(e===null||!Object.prototype.hasOwnProperty.call(t,"active_interaction"))return;const i=X(e,this._cursor);if(i<0)return;const n=t.active_interaction===null?null:J(t.active_interaction);if(!(t.active_interaction!==null&&(!n||!rt(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=Nt(t.payload.interaction_cursor),i=J(t.payload);return!i||i.interaction_status==="preparing"||e===null||X(e,this._cursor)<=0?!0:this.hasMissingOutcome(i)||!rt(i)&&this.operations.has(i.interaction_id)&&!I(t.payload.interaction_response_message)?(this.refreshMissingOutcome(e),!0):(this._cursor=e,this.setCursor(e),this.mergeProjection(i,t.payload.interaction_response_message),rt(i)?this.setActive(i):this._active?.interaction_id===i.interaction_id&&this.setActive(null),this.operation&&(this.operation.interactionId!==i.interaction_id||!rt(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"||!Et.some(l=>l.tool_type===i.tool_type&&l.schema_version===i.schema_version)||!Se(i,e))return!1;const n=i.tool_type==="ui_buttons"&&i.schema_version===1;let r=null;if(n&&e.kind==="selection"&&we(i.presentation))r=i.presentation.options.find(l=>l.id===e.value)?.label??null;else if(!n&&e.kind==="text"&&i.tool_type==="ui_buttons"&&bt(i.presentation))r=e.value;else if(!n&&e.kind==="selection"&&i.tool_type==="ui_buttons"&&bt(i.presentation))r=i.presentation.options.find(l=>l.id===e.value)?.label??null;else if(e.kind==="selection"&&i.tool_type==="ui_carousel"&&xe(i.presentation,void 0,!0))r=i.presentation.items.find(l=>l.id===e.value)?.title??null;else if(e.kind==="date"&&i.tool_type==="ui_date_picker"&&i.schema_version===1&&Mt(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&&Mt(i.presentation)&&i.presentation.selection_mode==="range"){const{start_date:l,end_date:f}=e.value;(!i.presentation.min_date||l>=i.presentation.min_date)&&(!i.presentation.max_date||f<=i.presentation.max_date)&&(r=`${l} to ${f}`)}if(!r)return!1;const o=this.host.newId(),a={interactionId:t,messageId:o,original:i,acknowledged:!1,sent:!1,frame:{type:"interaction_response",interaction_id:t,...n?{option_id:e.value}:{response:e},message_id:o,idempotency_key:this.host.newId(),supported_interactions:Et}};this.operations.set(t,a),this.operation=a,this.setSelectionPending(!0),this.setInteractionError(null);const c={...i,interaction_status:"accepted",...n?{selected_option_id:e.value}:{response_payload:e}};return this.setActive(c),this.setRows(l=>Dt(l,[I(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 Li(s){const t=[];for(const e of s)e.kind==="interaction"?t.push(I(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 ji(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=J(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 Fi(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 Hi=25e3,zi=6e4,Vi=3e4,ke=6e4,ot=[1e3,2e3,4e3,8e3,16e3,3e4],Lt=1e4,qi=4e3,Wi=2,Ae=new Set(["invalid_token","session_not_found","session_closed","origin_not_allowed","agent_archived","agent_not_found"]);function Ce(){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 at(s){s&&(s.onopen=null,s.onmessage=null,s.onclose=null,s.onerror=null)}class Gi{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??Ce(),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){at(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){at(i),this.next=null,this.later(Lt,()=>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,at(i);try{i?.close(qi,"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=Fi(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,at(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>Wi){this.opts.onError(v("invalid_token")),this.scheduleBackoff();return}this.opts.onStatus(this.recoveringStatus()),this.whenVisible(()=>this.reconnectNow());return}if(t===1008&&e==="agent_inactive"){this.opts.onError(v("agent_inactive")),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(ke,()=>this.reconnectNow());return}if(t===1008){this.terminate(e||"policy");return}this.scheduleBackoff()}}handleMintFailure(t){const e=t instanceof x?t.error:v("network");if(e.code==="agent_inactive"){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(ke,()=>this.reconnectNow());return}if(Ae.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,ot.length-1);if(this.failures+=1,this.failures>ot.length){this.opts.onStatus("offline"),this.retryWhenReachable();return}this.opts.onStatus(this.recoveringStatus());const e=Math.round(ot[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()},ot[ot.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>=zi){this.declareDead();return}this.send({type:"ping"})&&(this.lastPingSentAt=t)},Hi)}declareDead(){const t=this.socket;if(t){at(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()-Vi);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 x?i.error:v("network");if(Ae.has(n.code)){this.terminate(n.code);return}const r=n.retryAfterSeconds?n.retryAfterSeconds*1e3:Lt;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(Lt,()=>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 jt="osvi.chat.visitor",Ki=/^web:[0-9a-f]{32}$/;function Yi(){const s=new Map;return{get:t=>s.get(t)??null,set:(t,e)=>{s.set(t,e)},remove:t=>{s.delete(t)}}}function Ji(){const s=Yi();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 Te=s=>`web:${Array.from(s,t=>t.toString(16).padStart(2,"0")).join("")}`;let Ft=null;function ct(s,t){const e=s.get(jt);if(e&&Ki.test(e))return e;e!==null&&s.remove(jt);let i;try{i=globalThis.crypto?.getRandomValues?.(new Uint8Array(16))}catch{}if(i){const n=Te(i);return s.set(jt,n),n}if(!Ft){const n=new Uint8Array(16);for(let r=0;r<n.length;r+=1)n[r]=Math.floor(Math.random()*256);Ft=Te(n)}return Ft}function Ht(s){return`osvi.chat.session.${s}`}const Xi="https://api.osvi.ai",Zi=12e4,Qi=15e3,Ie=[1e3,2e3,4e3,8e3,16e3],ts=2048,es=new Set(["session_closed","session_dormant","new_session"]);function _t(){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 Ee=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Pe={user:"user",ai:"assistant",assistant:"assistant",operator:"human",support:"human"};class is{constructor(t){this.opts=t,this.state=Ee(),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 Ci(t.baseUrl??Xi,t.fetch),this.store=t.store??Ji(),this.page=t.page??Ce(),this.interactions=new Bi({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:_t})}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(Ht(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=_t(),n=_t(),r={kind:"message",id:i,role:"user",content:e,createdAt:new Date().toISOString(),status:"sending",idempotencyKey:n};return this.patch({items:[...this.state.items,r]}),this.pending.set(i,{frame:this.frameFor(r),attempts:0,gen:-1,ackTimer:null}),await this.ensureSession()?(this.transmit(i),{ok:!0,messageId:i}):(this.dropPending(i),this.setMessage(i,{status:"failed"}),{ok:!1,reason:"unavailable"})}async respond(t,e){return this.destroyed?!1:this.interactions.respond(t,e)}async retry(t){const e=this.state.items.find(i=>i.kind==="message"&&i.id===t);return!e||e.status!=="failed"||!e.idempotencyKey||this.destroyed?!1:(this.dropPending(t),this.pending.set(t,{frame:this.frameFor(e),attempts:0,gen:-1,ackTimer:null}),this.setMessage(t,{status:"sending"}),await this.ensureSession()?(this.transmit(t),!0):(this.dropPending(t),this.setMessage(t,{status:"failed"}),!1))}newSession(t={}){return this.destroyed?Promise.resolve(!1):!this.sessionId&&this.ensureP?this.ensureP.then(e=>e!==null):this.serialize(async()=>{if(this.destroyed)return!1;if(this.sessionId&&this.endSession("new_session"),t.keepHistory===!1&&this.patch({items:[]}),this.serverMode)return this.wantNewServerSession=!0,await this.openServerSession()!==null;try{const e=await this.http.createSession(this.opts.agentId,ct(this.store));return this.destroyed?!1:(this.adopt(e.id,null,"keep"),!0)}catch(e){return this.fail(e,!1),!1}})}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getState(){return this.state}resolveUrl(t){return this.http.resolveUrl(t)}destroy(){this.destroyed||(this.destroyed=!0,this.sessionGeneration+=1,this.conn?.stop(),this.conn=null,this.timers.forEach(clearTimeout),this.timers.clear(),this.pending.forEach(t=>{t.ackTimer&&clearTimeout(t.ackTimer)}),this.pending.clear(),this.awaitingTimer&&clearTimeout(this.awaitingTimer),this.interactions.reset(),this.sessionId=null,this.latestToken=null,this.switchTo=null,this.state=Ee(),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 x)||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 x(v("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:be(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=v("token_failed","The chat stream URL must use wss://");throw new x(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 x(v("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(Ht(this.opts.agentId),t),e&&this.applySnapshot(e,i);let a=n??null;const c=this.serverMode?null:ct(this.store);let l=!0,f=!1;const h=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 x(v("session_closed"),0);return this.latestToken=g.token,g}const d=l;l=!1;let p;try{p=await this.http.mintPublicToken(t)}catch(g){throw f=d&&r&&this.isCurrent(o,t)&&g instanceof x&&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 Gi({mint:h,sdkVersion:xi,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(f&&c&&d==="session_not_found"){f=!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 x)||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 x&&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(Ht(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:_t(),reason:"session_ended"};this.setAwaiting(!1),this.patch({status:"closed",mode:"ai",items:e.length&&i?.kind!=="divider"?[...e,n]:e,...es.has(t)?{}:{error:v(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>ts&&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=Bt(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=Bt({...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<Ie.length){const n=Ie[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:v(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=Pe[e];if(!r||this.state.items.some(a=>a.kind==="message"&&a.serverId===t))return;const o={kind:"message",id:`srv:${t}`,serverId:t,role:r,content:i,createdAt:n??new Date().toISOString(),status:"sent"};this.patch({items:[...this.state.items,o]}),r!=="user"&&this.setAwaiting(!1)}applySnapshot(t,e){if(this.destroyed)return;const i=[],n=new Map;for(const c of t.messages??[]){const l=J(c);if(l){i.push({kind:"interaction",id:l.interaction_id,interaction:l});continue}const f=Bt(c),h=f?Pe[f.role]:void 0;if(f&&h){i.push({kind:"message",id:`srv:${f.id}`,serverId:f.id,role:h,content:f.content,createdAt:f.created_at??new Date().toISOString(),status:"sent"});const d=c.message_id;typeof d=="string"&&n.set(f.id,d)}}let r=this.state.items;if(e==="replace")r=i;else if(e==="append"){let c=r.length;for(;c>0;){const l=r[c-1];if(l.kind==="message"&&l.role==="user"&&l.status==="sending"&&!l.serverId)c-=1;else break}r=[...r.slice(0,c),...i,...r.slice(c)]}else if(e==="reconcile"){const c=new Set(r.flatMap(l=>l.kind==="message"?[l.serverId]:l.kind==="interaction"?[l.id]:[]));for(const l of i){const f=l.kind==="message"?l.serverId:l.id;if(l.kind==="message"&&l.role==="user"&&!c.has(f)){const h=n.get(l.serverId),d=r.findIndex(p=>p.kind==="message"&&p.role==="user"&&!p.serverId&&(h?p.id===h:p.content===l.content));if(d>=0){const p=r[d];r=r.slice(),r[d]={...p,serverId:l.serverId,status:"sent"},this.dropPending(p.id),c.add(f);continue}}c.has(f)||(r=[...r,l],c.add(f))}}const o=t.session;this.patch({items:r,...o?{mode:o.mode==="support"?"human":"ai"}:{}}),this.interactions.applySnapshot(t);const a=r.filter(c=>c.kind!=="divider").at(-1);a&&!(a.kind==="message"&&a.role==="user")&&this.setAwaiting(!1),this.patch({})}frameFor(t){return{type:"message",content:t.content,message_id:t.id,idempotency_key:t.idempotencyKey,supported_interactions:Et}}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)},Qi))}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:v("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})},Zi)),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 x?t.error:v("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 ss(s){return new is(s)}const Oe={primary:"#4f46e5",background:"#ffffff",surface:"#f4f4f5",text:"#18181b",userBubble:"#4f46e5",assistantBubble:"#f4f4f5"},ns={primary:"#6366f1",background:"#0a0a12",surface:"#1c1c27",text:"#f4f4f5",userBubble:"#6366f1",assistantBubble:"#1f1f2b"},rs={none:"0px",sm:"6px",md:"10px",lg:"16px",full:"9999px"},lt={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"},Re=s=>`var(${lt[s]}, ${Oe[s]})`;function zt(s){const t={...s?.mode==="dark"?ns:Oe,...s?.colors};!s?.colors?.userBubble&&s?.colors?.primary&&(t.userBubble=s.colors.primary);const e={};for(const n of Object.keys(lt))e[lt[n]]=t[n];const i=s?.radius??"md";return e["--osvi-radius"]=typeof i=="number"?`${i}px`:rs[i],e}function Me(s){if(!s)return{};if(s.mode)return zt(s);const t=zt(s),e={};for(const i of Object.keys(s.colors??{}))e[lt[i]]=t[lt[i]];return s.radius!==void 0&&(e["--osvi-radius"]=t["--osvi-radius"]),e}const Ue=new WeakMap;function Vt(s,t){for(const i of Ue.get(s)??[])s.style.removeProperty(i);const e=Me(t);for(const[i,n]of Object.entries(e))s.style.setProperty(i,n);Ue.set(s,Object.keys(e))}const qt={placeholder:"Type your message…",send:"Send",typing:"Typing…",humanJoined:"A team member has joined",chooseOption:"Choose an option to continue.",typeAnswer:"Type your answer below, then press Send.",sending:"Sending your response…",pausedForHuman:"Choices are paused while a team member is connected.",sendFailed:"Message not sent.",retry:"Retry",sessionEnded:"Conversation ended",reconnecting:"Reconnecting…",offline:"You are offline. We will reconnect automatically.",unavailable:"This chat is unavailable.",originBlocked:"This chat is not enabled for this website.",rateLimited:"Too many requests. Please try again in a few minutes.",tryAgain:"Try again",closeChat:"Close chat",poweredBy:"Powered by Osvi AI",newChat:"New chat",emptyState:"Send a message to start chatting.",defaultTitle:"Chat"},Ne=new Set;function De(s,t){Ne.has(s)||(Ne.add(s),console.warn(`[osvi-chat] ${t}`))}function j(s,t){return s!=null&&t.includes(s)?s:void 0}function Be(s){if(s!=null)return j(s,["none","sm","md","lg","full"])??(/^\d{1,2}(?:px)?$/.test(s)?Number(s.replace(/px$/,"")):void 0)}function Le(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{}De("base-url","ignored an invalid base-url (https required, http only for localhost)")}}function os(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 je(s,t){if(t){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}De(s,`ignored invalid JSON in the ${s} attribute`)}}const F={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4},Fe=s=>(...t)=>({_$litDirective$:s,values:t});let He=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:as}=yi,ze=s=>s,cs=s=>s.strings===void 0,Ve=()=>document.createComment(""),ht=(s,t,e)=>{const i=s._$AA.parentNode,n=t===void 0?s._$AB:t._$AA;if(e===void 0){const r=i.insertBefore(Ve(),n),o=i.insertBefore(Ve(),n);e=new as(r,o,s,s.options)}else{const r=e._$AB.nextSibling,o=e._$AM,a=o!==s;if(a){let c;e._$AQ?.(s),e._$AM=s,e._$AP!==void 0&&(c=s._$AU)!==o._$AU&&e._$AP(c)}if(r!==n||a){let c=e._$AA;for(;c!==r;){const l=ze(c).nextSibling;ze(i).insertBefore(c,n),c=l}}}return e},H=(s,t,e=s)=>(s._$AI(t,e),s),ls={},qe=(s,t=ls)=>s._$AH=t,hs=s=>s._$AH,Wt=s=>{s._$AR(),s._$AA.remove()};const We=(s,t,e)=>{const i=new Map;for(let n=t;n<=e;n++)i.set(s[n],n);return i},ds=Fe(class extends He{constructor(s){if(super(s),s.type!==F.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=hs(s),{values:r,keys:o}=this.dt(t,e,i);if(!Array.isArray(n))return this.ut=o,r;const a=this.ut??(this.ut=[]),c=[];let l,f,h=0,d=n.length-1,p=0,g=r.length-1;for(;h<=d&&p<=g;)if(n[h]===null)h++;else if(n[d]===null)d--;else if(a[h]===o[p])c[p]=H(n[h],r[p]),h++,p++;else if(a[d]===o[g])c[g]=H(n[d],r[g]),d--,g--;else if(a[h]===o[g])c[g]=H(n[h],r[g]),ht(s,c[g+1],n[h]),h++,g--;else if(a[d]===o[p])c[p]=H(n[d],r[p]),ht(s,n[h],n[d]),d--,p++;else if(l===void 0&&(l=We(o,p,g),f=We(a,h,d)),l.has(a[h]))if(l.has(a[d])){const w=f.get(o[p]),pt=w!==void 0?n[w]:null;if(pt===null){const Qe=ht(s,n[h]);H(Qe,r[p]),c[p]=Qe}else c[p]=H(pt,r[p]),ht(s,n[h],pt),n[w]=null;p++}else Wt(n[d]),d--;else Wt(n[h]),h++;for(;p<=g;){const w=ht(s,c[g+1]);H(w,r[p]),c[p++]=w}for(;h<=d;){const w=n[h++];w!==null&&Wt(w)}return this.ut=o,qe(s,c),k}}),us=/https?:\/\/[^\s<>"']+/g,vt=(s,t)=>s.split(t).length-1;function ps(s){for(;;){const t=s[s.length-1];if(t&&".,!?;:".includes(t)||t===")"&&vt(s,")")>vt(s,"(")||t==="]"&&vt(s,"]")>vt(s,"[")){s=s.slice(0,-1);continue}return s}}function fs(s){const t=[];let e=0;for(const i of s.matchAll(us)){const n=ps(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 gs(s,t,e,i,n){return u`${s.items.length?ds(s.items,r=>r.id,r=>{if(r.kind==="divider")return u`<p class="divider">${t.sessionEnded}</p>`;if(r.kind==="message")return u`<article class=${`bubble ${r.role}`}>${r.role==="human"?u`<small class="team">Team</small>`:m}<p>${fs(r.content).map(l=>"href"in l?u`<a href=${l.href} target="_blank" rel="noopener noreferrer">${l.text}</a>`:l.text)}</p>${r.role==="user"&&r.status==="failed"?u`<span class="failed"><span>${t.sendFailed}</span><button type="button" @click=${()=>n(r.id)}>${t.retry}</button></span>`:m}</article>`;const o=r.interaction,a=o.interaction_id===s.activeInteraction?.interaction_id&&o.interaction_status==="pending",c=!a||s.interactionPending||s.mode==="human";switch(o.tool_type){case"ui_buttons":return u`<osvi-buttons data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.buttons??"chips"} base-url=${i}></osvi-buttons>`;case"ui_carousel":return u`<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 u`<osvi-date-picker data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} base-url=${i}></osvi-date-picker>`;default:return u`<p>${o.content}</p>`}}):u`<p class="empty">${t.emptyState}</p>`}${s.awaitingReply?u`<div class="typing" role="img" aria-label=${t.typing}><i></i><i></i><i></i></div>`:m}`}const ms=Fe(class extends He{constructor(s){if(super(s),s.type!==F.PROPERTY&&s.type!==F.ATTRIBUTE&&s.type!==F.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!cs(s))throw Error("`live` bindings can only contain a single expression")}render(s){return s}update(s,[t]){if(t===k||t===m)return t;const e=s.element,i=s.name;if(s.type===F.PROPERTY){if(t===e[i])return k}else if(s.type===F.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(i))return k}else if(s.type===F.ATTRIBUTE&&e.getAttribute(i)===t+"")return k;return qe(s),t}}),U=(s,t="")=>A`<svg class=${t} viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${s}</svg>`;U(A`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z"/><path d="M8.5 8.5h7M8.5 11.5h4"/>`);const ys=U(A`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z"/><path d="M12 6.5v6M9 9.5h6"/>`),bs=U(A`<path d="M6 6l12 12M18 6L6 18"/>`);U(A`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6c-.5.4-1.3.1-1.3-.6V16A2.5 2.5 0 0 1 4 13.5z"/><path d="M8.5 8.5h7M8.5 11.5h4"/>`,"chat"),U(A`<path d="M6 6l12 12M18 6L6 18"/>`,"close");const _s=U(A`<path d="M12 19V5M5.5 11.5L12 5l6.5 6.5"/>`),Ge=U(A`<path d="M15 6l-6 6 6 6"/>`),Gt=U(A`<path d="M9 6l6 6-6 6"/>`),vs=A`<svg viewBox="0 0 134 134" aria-hidden="true" focusable="false"><defs><linearGradient id="osvi-g" x1="-36.28" y1="32.2" x2="161.98" y2="93.64" gradientUnits="userSpaceOnUse"><stop offset=".304" stop-color="#155DFC"/><stop offset=".822" stop-color="#353333"/></linearGradient><mask id="osvi-m" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="-7" y="-6" width="149" height="150"><path fill-rule="evenodd" clip-rule="evenodd" fill="#0F0F0F" d="M141.385 114.008L141.622 108.411V29.4704L141.385 23.8743C139.964 7.44314 126.224 -5.41602 109.523 -5.41602H25.3094C8.60869 -5.41602 -5.13083 7.44314 -6.55216 23.8743L-6.78906 29.4704V108.411L-6.55216 114.008C-5.13083 130.439 8.60869 143.298 25.3094 143.298H109.523C126.224 143.298 139.964 130.439 141.385 114.008ZM25.3094 102.339C9.55625 102.339 65.7059 83.8874 53.6176 66.6191C42.3654 50.5452 93.7703 32.6852 109.523 32.6852C125.277 32.6852 73.161 54.1172 81.4521 80.9071C86.1899 96.2156 40.944 102.339 25.3094 102.339Z"/></mask></defs><g mask="url(#osvi-m)"><ellipse cx="66.88" cy="66.79" rx="67.22" ry="66.81" fill="url(#osvi-g)"/></g></svg>`;function $s(s){return u`<div class="composer"><textarea rows="1" aria-label="Message" placeholder=${s.placeholder} .value=${ms(s.draft)} ?disabled=${s.disabled} @input=${t=>{const e=t.target;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,s.input(t)}} @keydown=${t=>{t.key==="Enter"&&!t.shiftKey&&!t.isComposing&&!s.disabled&&(t.preventDefault(),s.send())}}></textarea><button type="button" class="send" title=${s.strings.send} aria-label=${s.strings.send} ?disabled=${s.disabled||!s.draft.trim()} @click=${s.send}>${_s}<span class="sr">${s.strings.send}</span></button></div>`}var ws=Object.defineProperty,_=(s,t,e,i)=>{for(var n=void 0,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=o(t,e,n)||n);return n&&ws(t,e,n),n};const Ke=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Ye={fromAttribute:s=>s!=="false"},b=(E=class extends Y{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=Ke(),this.draft="",this.busy=!1,this.typed=null,this.ownClient=null,this.boundClient=null,this.ownKey="",this.generation=0,this.followBottom=!0,this.focusedInteraction=null,this.send=()=>{if(this.blocked||!this.draft.trim()||!this.boundClient)return;const t=this.boundClient,e=this.draft.trim(),i=this.typed;this.draft="",i&&this.restoreDraft(),this.requestUpdate();const n=this.renderRoot.querySelector("textarea");n&&(n.style.height=""),this.run(()=>i?t.respond(i.id,{kind:"text",value:e}):t.send(e))},this.respond=t=>{const e=t.detail,i=this.chatState;if(!e||this.busy||i.mode!=="ai"||i.interactionPending||i.activeInteraction?.interaction_status!=="pending"||e.interactionId!==i.activeInteraction.interaction_id)return;t.stopPropagation();const n=this.boundClient;n&&this.run(()=>n.respond(e.interactionId,e.response))},this.requestInput=t=>{const e=t.detail,i=this.chatState;!e||this.busy||i.mode!=="ai"||i.interactionPending||i.activeInteraction?.interaction_status!=="pending"||e.interactionId!==i.activeInteraction.interaction_id||(t.stopPropagation(),this.typed={id:e.interactionId,placeholder:typeof e.placeholder=="string"?e.placeholder:void 0,previousDraft:this.typed?.previousDraft??this.draft},this.draft="",this.requestUpdate(),this.updateComplete.then(()=>this.renderRoot.querySelector("textarea")?.focus()))}}connectedCallback(){super.connectedCallback(),this.syncClient()}disconnectedCallback(){super.disconnectedCallback(),this.releaseClient()}releaseClient(){++this.generation,this.unsubscribe?.(),this.unsubscribe=void 0,this.boundClient=null;const t=this.ownClient;this.ownClient=null,this.ownKey="",t?.destroy(),this.busy=!1,this.typed=null,this.focusedInteraction=null,this.requestUpdate()}syncClient(){if(!this.isConnected||!this.client&&!this.agentId&&!this.boundClient)return;const t=JSON.stringify([this.agentId,Le(this.baseUrl)]);if((this.client?this.boundClient===this.client&&!this.ownClient:this.ownClient&&t===this.ownKey)||(this.releaseClient(),this.chatState=Ke(),!this.client&&!this.agentId))return;const e=!this.client,i=this.client??E.clientFactory({agentId:this.agentId,baseUrl:Le(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(),Vt(this,this.mergedTheme())}mergedTheme(){const t=je("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=Be(this.radius)??(typeof t?.radius=="number"&&Number.isInteger(t.radius)&&t.radius>=0&&t.radius<=99?t.radius:typeof t?.radius=="string"?Be(t.radius):void 0),r=j(this.mode,["light","dark"])??j(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={...qt};for(const e of[this.strings,je("strings",this.stringsAttribute)])for(const i of Object.keys(qt))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=os(this.headerAvatar??this.header.avatarUrl),r={...this.variants,...j(this.buttons,["chips","list"])?{buttons:j(this.buttons,["chips","list"])}:{},...j(this.carousel,["slider","list"])?{carousel:j(this.carousel,["slider","list"])}:{}},o=this.headerTitle??this.header.title??e.agent?.name??t.defaultTitle;return u`<header>${n?u`<img class="avatar" src=${n} alt="" referrerpolicy="no-referrer">`:u`<span class="avatar" aria-hidden="true">${o.trim().charAt(0).toUpperCase()}</span>`}<div class="heading"><h2>${o}</h2>${this.headerSubtitle??this.header.subtitle?u`<p>${this.headerSubtitle??this.header.subtitle}</p>`:m}${e.mode==="human"?u`<small>${t.humanJoined}</small>`:m}</div>
|
|
4
|
+
${this.newChat?u`<button type="button" class="icon" title=${t.newChat} ?disabled=${!i||this.sessionBusy} @click=${()=>i&&!this.sessionBusy&&void this.run(()=>i.newSession({keepHistory:this.newChatHistory==="keep"}))}>${ys}<span class="sr">${t.newChat}</span></button>`:m}
|
|
5
|
+
${this.closable?u`<button type="button" class="icon" title=${t.closeChat} aria-label=${t.closeChat} @click=${()=>this.dispatchEvent(new CustomEvent("osvi-close",{bubbles:!0,composed:!0}))}>${bs}</button>`:m}</header>
|
|
6
|
+
<div class="transcript" role="log" aria-live="polite" aria-label="Conversation" @scroll=${a=>{const c=a.currentTarget;this.followBottom=c.scrollHeight-c.scrollTop-c.clientHeight<=80}} @osvi-respond=${this.respond} @osvi-request-input=${this.requestInput}>${gs(e,t,r,i?.resolveUrl("")??"",a=>{i&&this.run(()=>i.retry(a))})}</div>
|
|
7
|
+
<div class="status" role="status">${this.statusText(t)}${e.error?.retryable&&(e.status==="idle"||e.status==="closed")?u`<button type="button" ?disabled=${this.busy||!i} @click=${()=>i&&void this.run(()=>i.start())}>${t.tryAgain}</button>`:m}</div>
|
|
8
|
+
${$s({strings:t,draft:this.draft,placeholder:this.typed?.placeholder??t.placeholder,disabled:this.blocked,input:a=>{this.draft=a.target.value,this.requestUpdate()},send:this.send})}
|
|
9
|
+
${this.poweredBy?u`<footer><a href="https://osvi.ai" target="_blank" rel="noopener noreferrer">${vs}<span>${t.poweredBy}</span></a></footer>`:m}`}},E.clientFactory=ss,E.properties={themeAttribute:{attribute:"theme"},stringsAttribute:{attribute:"strings"}},E.styles=ie`
|
|
10
|
+
:host { --p:var(--osvi-color-primary,#4f46e5); --bg:var(--osvi-color-background,#fff); --surface:var(--osvi-color-surface,#f4f4f5); --text:var(--osvi-color-text,#18181b);
|
|
11
|
+
--ub:var(--osvi-color-user-bubble,var(--p)); --ab:var(--osvi-color-assistant-bubble,var(--surface)); --r:var(--osvi-radius,14px);
|
|
12
|
+
--sub:color-mix(in srgb,var(--text) 58%,var(--bg)); --line:color-mix(in srgb,var(--text) 11%,var(--bg));
|
|
13
|
+
display:flex; flex-direction:column; height:100%; min-height:260px; color:var(--text); background:var(--bg); font-family:inherit; font-size:14px; line-height:1.5; border-radius:var(--r); overflow:hidden; }
|
|
14
|
+
* { box-sizing:border-box; } h2,p { margin:0; }
|
|
15
|
+
button,textarea { font:inherit; color:inherit; } button { cursor:pointer; } button:disabled { cursor:default; opacity:.45; }
|
|
16
|
+
button:focus-visible,textarea:focus-visible,a:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:2px; }
|
|
17
|
+
.sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; }
|
|
18
|
+
header { display:flex; align-items:center; gap:12px; padding:14px 12px 14px 16px; border-bottom:1px solid var(--line); }
|
|
19
|
+
.avatar { width:38px; height:38px; border-radius:50%; flex:none; object-fit:cover; display:grid; place-items:center; background:var(--p); color:#fff; font-weight:700; font-size:15px; }
|
|
20
|
+
.heading { flex:1; min-width:0; } h2 { font-size:15px; line-height:1.3; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
21
|
+
.heading p,.heading small { display:block; font-size:12.5px; color:var(--sub); }
|
|
22
|
+
.heading small { color:var(--p); font-weight:600; }
|
|
23
|
+
.icon { width:34px; height:34px; border:0; border-radius:10px; background:transparent; color:var(--sub); display:grid; place-items:center; flex:none; }
|
|
24
|
+
.icon:hover:not(:disabled) { background:var(--surface); color:var(--text); } .icon svg { width:18px; height:18px; }
|
|
25
|
+
.transcript { flex:1; overflow:auto; padding:18px 16px; min-height:0; display:flex; flex-direction:column; gap:10px; }
|
|
26
|
+
.empty { margin:auto; color:var(--sub); text-align:center; }
|
|
27
|
+
.bubble { width:fit-content; max-width:84%; padding:10px 14px; border-radius:var(--r); border-bottom-left-radius:6px; background:var(--ab); overflow-wrap:anywhere; white-space:pre-wrap; }
|
|
28
|
+
.bubble.user { align-self:flex-end; color:#fff; background:var(--ub); border-bottom-left-radius:var(--r); border-bottom-right-radius:6px; }
|
|
29
|
+
.bubble a { color:inherit; } .team { display:block; font-size:11px; font-weight:600; color:var(--p); margin-bottom:2px; }
|
|
30
|
+
.failed { display:flex; align-items:center; gap:8px; font-size:12px; margin-top:6px; } .failed button { border:0; background:rgb(255 255 255/.2); border-radius:8px; padding:2px 8px; }
|
|
31
|
+
.divider { display:flex; align-items:center; gap:10px; color:var(--sub); font-size:12px; } .divider::before,.divider::after { content:""; flex:1; height:1px; background:var(--line); }
|
|
32
|
+
.typing { display:inline-flex; gap:4px; padding:12px 14px; background:var(--ab); border-radius:var(--r); border-bottom-left-radius:6px; width:fit-content; }
|
|
33
|
+
.typing i { width:6px; height:6px; border-radius:50%; background:var(--sub); animation:osvi-dot 1.2s infinite; } .typing i:nth-child(2) { animation-delay:.15s; } .typing i:nth-child(3) { animation-delay:.3s; }
|
|
34
|
+
@keyframes osvi-dot { 0%,60%,100% { opacity:.35; transform:none; } 30% { opacity:1; transform:translateY(-3px); } }
|
|
35
|
+
osvi-buttons,osvi-carousel,osvi-date-picker { display:block; max-width:100%; }
|
|
36
|
+
.status { padding:0 16px; font-size:12.5px; color:var(--sub); display:flex; gap:8px; align-items:center; } .status:empty { display:none; }
|
|
37
|
+
.status button { border:1px solid var(--line); background:var(--bg); border-radius:8px; padding:3px 10px; }
|
|
38
|
+
.composer { margin:10px 12px; display:flex; align-items:flex-end; gap:8px; border:1px solid var(--line); border-radius:18px; padding:6px 6px 6px 14px; background:var(--surface); }
|
|
39
|
+
.composer:focus-within { border-color:var(--p); box-shadow:0 0 0 3px color-mix(in srgb,var(--p) 18%,transparent); }
|
|
40
|
+
textarea { flex:1; min-width:0; border:0; outline:0; background:transparent; resize:none; min-height:24px; max-height:120px; padding:6px 0; field-sizing:content; }
|
|
41
|
+
textarea::placeholder { color:var(--sub); } textarea:focus-visible { outline:0; }
|
|
42
|
+
.send { width:36px; height:36px; border:0; border-radius:50%; background:var(--p); color:#fff; display:grid; place-items:center; flex:none; } .send svg { width:17px; height:17px; }
|
|
43
|
+
footer { padding:0 16px 12px; text-align:center; font-size:11.5px; } footer a { color:var(--sub); text-decoration:none; display:inline-flex; align-items:center; gap:6px; }
|
|
44
|
+
footer a:hover { color:var(--text); } footer svg { width:14px; height:14px; flex:none; }
|
|
45
|
+
@media (prefers-reduced-motion:reduce) { .typing i { animation:none; } }
|
|
46
|
+
`,E);_([y({attribute:"agent-id"})],b.prototype,"agentId"),_([y({attribute:"base-url"})],b.prototype,"baseUrl"),_([y({attribute:!1})],b.prototype,"client"),_([y({attribute:!1})],b.prototype,"theme"),_([y({attribute:!1})],b.prototype,"variants"),_([y({attribute:!1})],b.prototype,"strings"),_([y({attribute:"powered-by",converter:Ye})],b.prototype,"poweredBy"),_([y({attribute:"new-chat",converter:Ye})],b.prototype,"newChat"),_([y({attribute:"new-chat-history"})],b.prototype,"newChatHistory"),_([y({attribute:!1})],b.prototype,"header"),_([y({type:Boolean})],b.prototype,"closable"),_([y({attribute:"header-title"})],b.prototype,"headerTitle"),_([y({attribute:"header-subtitle"})],b.prototype,"headerSubtitle"),_([y({attribute:"header-avatar"})],b.prototype,"headerAvatar"),_([y({attribute:"primary-color"})],b.prototype,"primaryColor"),_([y()],b.prototype,"radius"),_([y()],b.prototype,"mode"),_([y()],b.prototype,"buttons"),_([y()],b.prototype,"carousel"),_([C()],b.prototype,"chatState"),_([C()],b.prototype,"draft"),_([C()],b.prototype,"busy"),_([C()],b.prototype,"typed");let Je=b;function dt(s,t){typeof customElements>"u"||customElements.get(s)||customElements.define(s,t)}const $t=s=>ee(Re(s)),Kt=ie`
|
|
47
|
+
:host { --p:${$t("primary")}; --bg:${$t("background")}; --surface:${$t("surface")}; --text:${$t("text")}; --r:var(--osvi-radius,14px);
|
|
48
|
+
--sub:color-mix(in srgb,var(--text) 58%,var(--bg)); --line:color-mix(in srgb,var(--text) 11%,var(--bg));
|
|
49
|
+
display:block; font:inherit; color:var(--text); }
|
|
50
|
+
* { box-sizing:border-box; }
|
|
51
|
+
p { margin:0 0 6px; } .label { font-weight:600; } .description { color:var(--sub); font-size:13px; }
|
|
52
|
+
.answer { display:inline-block; margin-top:2px; padding:4px 10px; border-radius:999px; background:color-mix(in srgb,var(--p) 12%,var(--bg)); color:var(--p); font-weight:600; font-size:13px; }
|
|
53
|
+
.sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; }
|
|
54
|
+
button { font:inherit; color:inherit; cursor:pointer; }
|
|
55
|
+
button:focus-visible { outline:3px solid color-mix(in srgb,var(--p) 55%,transparent); outline-offset:2px; }
|
|
56
|
+
button:disabled { opacity:.45; cursor:default; }
|
|
57
|
+
small { display:block; color:var(--sub); font-size:12px; font-weight:400; }
|
|
58
|
+
.chips { display:flex; flex-wrap:wrap; gap:8px; }
|
|
59
|
+
.chips button { border:1.5px solid color-mix(in srgb,var(--p) 55%,var(--line)); background:var(--bg); color:var(--p); border-radius:999px; padding:7px 14px; font-weight:600; font-size:13px; text-align:center; }
|
|
60
|
+
.chips button:hover:not(:disabled) { background:color-mix(in srgb,var(--p) 10%,var(--bg)); }
|
|
61
|
+
.text { display:grid; gap:1px; min-width:0; }
|
|
62
|
+
.chips small { color:inherit; opacity:.8; }
|
|
63
|
+
.list { display:grid; gap:6px; }
|
|
64
|
+
.list > button { display:flex; justify-content:space-between; align-items:center; gap:10px; width:100%; text-align:left; border:1px solid var(--line); background:var(--bg); border-radius:12px; padding:10px 12px; }
|
|
65
|
+
.list > button:hover:not(:disabled) { border-color:var(--p); }
|
|
66
|
+
.list > button svg { width:16px; height:16px; flex:none; color:var(--sub); }
|
|
67
|
+
.card { background:var(--bg); border:1px solid var(--line); border-radius:var(--r); overflow:hidden; box-shadow:0 6px 18px -10px rgb(16 18 30/.35); }
|
|
68
|
+
.card .body { padding:10px 12px 12px; display:grid; gap:4px; } .card h3 { margin:0; font-size:14px; } .card p { margin:0; color:var(--sub); font-size:12.5px; }
|
|
69
|
+
.image { aspect-ratio:16 / 9; max-width:100%; display:grid; place-items:center; overflow:hidden; background:var(--surface); color:var(--sub); font-size:12px; }
|
|
70
|
+
.image img { width:100%; height:100%; object-fit:cover; display:block; }
|
|
71
|
+
.primary { justify-self:start; margin-top:6px; border:0; border-radius:10px; background:var(--p); color:#fff; font-weight:600; font-size:13px; padding:8px 14px; }
|
|
72
|
+
.list .card { display:grid; grid-template-columns:minmax(0,88px) 1fr; } .list .card .image { aspect-ratio:auto; height:100%; min-height:88px; }
|
|
73
|
+
.list .card:not(:has(.image)) { grid-template-columns:1fr; }
|
|
74
|
+
.navigation { display:flex; align-items:center; justify-content:space-between; gap:8px; margin:10px 0 0; }
|
|
75
|
+
.round { width:32px; height:32px; border-radius:50%; border:1px solid var(--line); background:var(--bg); display:grid; place-items:center; padding:0; flex:none; }
|
|
76
|
+
.round:hover:not(:disabled) { border-color:var(--p); } .round svg { width:15px; height:15px; }
|
|
77
|
+
.dots { display:flex; gap:5px; align-items:center; } .dots i { width:6px; height:6px; border-radius:3px; background:var(--line); transition:width .2s; } .dots i.on { width:16px; background:var(--p); }
|
|
78
|
+
.calendar { border:1px solid var(--line); border-radius:var(--r); padding:10px; background:var(--bg); display:grid; gap:6px; }
|
|
79
|
+
.calendar .navigation { margin:0; font-weight:600; font-size:13px; }
|
|
80
|
+
.days, .weekdays { display:grid; grid-template-columns:repeat(7, minmax(0, 1fr)); gap:2px 0; text-align:center; }
|
|
81
|
+
.weekdays { color:var(--sub); font-size:11px; }
|
|
82
|
+
.days button { border:0; background:transparent; height:30px; border-radius:8px; padding:0; font-size:12.5px; font-variant-numeric:tabular-nums; }
|
|
83
|
+
.days button:hover:not(:disabled) { background:var(--surface); }
|
|
84
|
+
.days button.today { box-shadow:inset 0 0 0 1.5px var(--line); }
|
|
85
|
+
.days button.in { background:color-mix(in srgb,var(--p) 14%,transparent); border-radius:0; }
|
|
86
|
+
.days button[aria-pressed="true"] { background:var(--p); color:#fff; }
|
|
87
|
+
.days button.start:not(.end) { border-radius:8px 0 0 8px; } .days button.end:not(.start) { border-radius:0 8px 8px 0; }
|
|
88
|
+
.hint { color:var(--sub); font-size:12px; margin:0; }
|
|
89
|
+
@media (prefers-reduced-motion:reduce) { .dots i { transition:none; } }
|
|
90
|
+
`;var xs=Object.defineProperty,wt=(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&&xs(t,e,n),n};class z extends Y{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&&Ui(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")&&Vt(this,this.theme)}}wt([y({attribute:!1})],z.prototype,"interaction"),wt([y({type:Boolean})],z.prototype,"disabled"),wt([y({attribute:!1})],z.prototype,"theme"),wt([y({attribute:"base-url"})],z.prototype,"baseUrl");var Ss=Object.defineProperty,ks=(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&&Ss(t,e,n),n};const Jt=class Jt extends z{constructor(){super(...arguments),this.toolType="ui_buttons",this.variant="chips"}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return u`<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 u`<p class="label">${e.label}</p>${e.description?u`<p class="description">${e.description}</p>`:m}
|
|
31
91
|
${this.live?u`<div role="group" aria-label="Options" class=${this.variant} @keydown=${this.onKey}>
|
|
32
|
-
${e.options.map(n=>u`<button type="button" @click=${()=>this.pick(n.id,n.allow_input,n.input_placeholder)}><span>${n.label}</span>${n.description?u`<small>${n.description}</small>`:m}</button>`)}
|
|
33
|
-
</div>`:
|
|
92
|
+
${e.options.map(n=>u`<button type="button" @click=${()=>this.pick(n.id,n.allow_input,n.input_placeholder)}><span class="text"><span>${n.label}</span>${n.description?u`<small>${n.description}</small>`:m}</span>${this.variant==="list"?Gt:m}</button>`)}
|
|
93
|
+
</div>`:i?u`<p class="answer">${i}</p>`:m}`}pick(t,e,i){!this.live||!this.valid||!this.interaction||(this.interaction.schema_version===2&&e?this.dispatchEvent(new CustomEvent("osvi-request-input",{bubbles:!0,composed:!0,detail:{interactionId:this.interaction.interaction_id,placeholder:i}})):this.respond({kind:"selection",value:t}))}onKey(t){if(!["ArrowDown","ArrowUp","ArrowRight","ArrowLeft"].includes(t.key))return;const e=[...this.renderRoot.querySelectorAll("button")],i=e.indexOf(this.renderRoot.activeElement),n=t.key==="ArrowDown"||t.key==="ArrowRight"?1:-1;e[(i+n+e.length)%e.length]?.focus(),t.preventDefault()}};Jt.styles=Kt;let ut=Jt;ks([y()],ut.prototype,"variant");var As=Object.defineProperty,Yt=(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&&As(t,e,n),n};const Xt=class Xt extends z{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 u`<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 u`<p class="label">${e.label}</p>${e.description?u`<p class="description">${e.description}</p>`:m}
|
|
34
94
|
${this.live?this.variant==="list"?u`<div class="list">${e.items.map((n,r)=>this.card(n,r))}</div>`:u`<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)}
|
|
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)}
|
|
38
|
-
<h3>${t.title}</h3>${t.description?u`<p>${t.description}</p>`:m}
|
|
39
|
-
<button type="button" @click=${n=>this.select(n,t.id)}>${t.action_label??"Select"}</button></article>`}};
|
|
40
|
-
<div class="navigation"><button type="button" aria-label="Previous month" ?disabled=${this.month<=
|
|
95
|
+
<div class="navigation"><button type="button" class="round" aria-label="Previous card" ?disabled=${this.index===0} @click=${()=>this.navigate(-1,e.items.length)}>${Ge}</button>
|
|
96
|
+
<span class="dots" aria-hidden="true">${e.items.map((n,r)=>u`<i class=${r===this.index?"on":""}></i>`)}</span><span class="sr" aria-live="polite">${this.index+1} of ${e.items.length}</span>
|
|
97
|
+
<button type="button" class="round" aria-label="Next card" ?disabled=${this.index===e.items.length-1} @click=${()=>this.navigate(1,e.items.length)}>${Gt}</button></div>`:i?u`<p class="answer">${i.title}</p>`:m}`}navigate(t,e){this.index=Math.max(0,Math.min(e-1,this.index+t))}select(t,e){if(this.suppressPointerClick&&t.detail!==0){this.suppressPointerClick=!1,t.preventDefault(),t.stopPropagation();return}this.respond({kind:"selection",value:e})}card(t,e){const i=t.image;return u`<article class="card">${i&&$e(i.url)?u`<div class="image">${this.imageFailed.has(e)?u`<span role="img" aria-label="Image unavailable">Image unavailable</span>`:u`<img src=${this.baseUrl.replace(/\/$/,"")+i.url} alt=${i.alt} referrerpolicy="no-referrer" loading="lazy" @error=${()=>{this.imageFailed=new Set([...this.imageFailed,e])}}>`}</div>`:m}
|
|
98
|
+
<div class="body"><h3>${t.title}</h3>${t.description?u`<p>${t.description}</p>`:m}
|
|
99
|
+
<button type="button" class="primary" @click=${n=>this.select(n,t.id)}>${t.action_label??"Select"}</button></div></article>`}};Xt.styles=Kt;let V=Xt;Yt([y()],V.prototype,"variant"),Yt([C()],V.prototype,"index"),Yt([C()],V.prototype,"imageFailed");var Cs=Object.defineProperty,xt=(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&&Cs(t,e,n),n};const Xe=s=>`${String(s.getFullYear()).padStart(4,"0")}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`,St=()=>Xe(new Date),Ze=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},q=s=>s.slice(0,7),Zt=class Zt extends z{constructor(){super(...arguments),this.toolType="ui_date_picker",this.variant="grid",this.month=q(St()),this.start="",this.end=""}earliest(t){return t.min_date&&t.min_date>St()?t.min_date:St()}willUpdate(t){t.has("interaction")&&(this.start="",this.end="",this.valid&&(this.month=q(this.earliest(this.interaction.presentation))))}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return u`<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 u`<p class="label">${e.label}</p>${e.description?u`<p class="description">${e.description}</p>`:m}${n?u`<p class="answer">${n}</p>`:m}`;const r=Ze(`${this.month}-01`),o=new Date(r);o.setMonth(o.getMonth()+1,0);const a=this.earliest(e),c=Array.from({length:o.getDate()},(h,d)=>`${this.month}-${String(d+1).padStart(2,"0")}`),l=e.selection_mode==="range"?this.start?this.end?`${this.start} – ${this.end}`:`Check-in: ${this.start}. Choose check-out.`:"Choose check-in, then check-out.":this.start,f=St();return u`<p class="label">${e.label}</p>${e.description?u`<p class="description">${e.description}</p>`:m}
|
|
100
|
+
<div class="calendar"><div class="navigation"><button type="button" class="round" aria-label="Previous month" ?disabled=${this.month<=q(a)} @click=${()=>this.moveMonth(-1,e)}>${Ge}</button>
|
|
41
101
|
<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>=
|
|
43
|
-
<div class="weekdays" aria-hidden="true">${["Su","Mo","Tu","We","Th","Fr","Sa"].map(
|
|
102
|
+
<button type="button" class="round" aria-label="Next month" ?disabled=${!!e.max_date&&this.month>=q(e.max_date)} @click=${()=>this.moveMonth(1,e)}>${Gt}</button></div>
|
|
103
|
+
<div class="weekdays" aria-hidden="true">${["Su","Mo","Tu","We","Th","Fr","Sa"].map(h=>u`<span>${h}</span>`)}</div>
|
|
44
104
|
<div class="days" role="group" aria-label="Choose date" @keydown=${this.onKey}>
|
|
45
105
|
${Array.from({length:r.getDay()},()=>u`<span></span>`)}
|
|
46
|
-
${c.map((d
|
|
47
|
-
</div><p aria-live="polite">${
|
|
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
|
|
106
|
+
${c.map((h,d)=>u`<button type="button" class=${[h===f?"today":"",h===this.start?"start":"",h===this.end?"end":"",this.start&&this.end&&h>this.start&&h<this.end?"in":""].filter(Boolean).join(" ")} aria-label=${h} aria-pressed=${h===this.start||h===this.end} ?disabled=${h<a||!!e.max_date&&h>e.max_date} @click=${()=>this.pick(h,e)}>${d+1}</button>`)}
|
|
107
|
+
</div><p class="hint" aria-live="polite">${l}</p>
|
|
108
|
+
<button type="button" class="primary" ?disabled=${!this.start||e.selection_mode==="range"&&(!this.end||this.start>=this.end)} @click=${()=>this.confirm(e)}>${e.confirm_label??"Confirm date"}</button></div>`}moveMonth(t,e){const i=Ze(`${this.month}-01`);i.setMonth(i.getMonth()+t);const n=q(Xe(i));n>=q(this.earliest(e))&&(!e.max_date||n<=q(e.max_date))&&(this.month=n)}pick(t,e){!this.live||!this.valid||!M(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){!M(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}):M(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()}};Zt.styles=Kt;let N=Zt;return xt([y()],N.prototype,"variant"),xt([C()],N.prototype,"month"),xt([C()],N.prototype,"start"),xt([C()],N.prototype,"end"),dt("osvi-chat",Je),dt("osvi-buttons",ut),dt("osvi-carousel",V),dt("osvi-date-picker",N),S.DEFAULT_STRINGS=qt,S.OsviButtons=ut,S.OsviCarousel=V,S.OsviChat=Je,S.OsviDatePicker=N,S.applyTheme=Vt,S.cssVar=Re,S.defineOnce=dt,S.explicitThemeVariables=Me,S.themeVariables=zt,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"}),S})({});
|
|
49
109
|
//# sourceMappingURL=ui.js.map
|