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