@runtypelabs/persona 3.24.0 → 3.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,68 +1,68 @@
1
- "use strict";var AgentWidget=(()=>{var ob=Object.create;var ya=Object.defineProperty;var sb=Object.getOwnPropertyDescriptor;var ab=Object.getOwnPropertyNames;var ib=Object.getPrototypeOf,lb=Object.prototype.hasOwnProperty;var Bg=e=>{throw TypeError(e)};var db=(e,t,r)=>t in e?ya(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Gn=(e,t)=>()=>(e&&(t=e(e=0)),t);var Dg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Og=(e,t)=>{for(var r in t)ya(e,r,{get:t[r],enumerable:!0})},_g=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ab(t))!lb.call(e,o)&&o!==r&&ya(e,o,{get:()=>t[o],enumerable:!(n=sb(t,o))||n.enumerable});return e};var ud=(e,t,r)=>(r=e!=null?ob(ib(e)):{},_g(t||!e||!e.__esModule?ya(r,"default",{value:e,enumerable:!0}):r,e)),cb=e=>_g(ya({},"__esModule",{value:!0}),e);var Dt=(e,t,r)=>db(e,typeof t!="symbol"?t+"":t,r),pb=(e,t,r)=>t.has(e)||Bg("Cannot "+r);var Ng=(e,t,r)=>t.has(e)?Bg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);var Mi=(e,t,r)=>(pb(e,t,"access private method"),r);function Is(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let o=0;o<n;o++)if(!Is(e[o],t[o]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(let a of n)if(!Is(e[a],t[a]))return!1;return!0}return e===t}var Id=Gn(()=>{"use strict"});function xn(e){return encodeURI(x0(e))}function x0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Bi=Gn(()=>{"use strict"});function uo(e,t=Object.create(null),r=C0,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let a=new URL(s,r.href);a.hash.length>1?t[a.href]=e:(a.hash="",n===""?r=a:uo(e,t,r))}}else if(e!==!0&&e!==!1)return t;let o=r.href+(n?"#"+n:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(w0[s])continue;let a=`${n}/${xn(s)}`,i=e[s];if(Array.isArray(i)){if(y0[s]){let d=i.length;for(let l=0;l<d;l++)uo(i[l],t,r,`${a}/${l}`)}}else if(b0[s])for(let d in i)uo(i[d],t,r,`${a}/${xn(d)}`);else uo(i,t,r,a)}return t}var y0,b0,w0,C0,Di=Gn(()=>{"use strict";Bi();y0={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},b0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},w0={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},C0=typeof self!="undefined"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Jn(e){return e.test.bind(e)}function O0(e){return e%4===0&&(e%100!==0||e%400===0)}function wh(e){let t=e.match(v0);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&O0(r)?29:S0[n])}function Ch(e,t){let r=t.match(A0);if(!r)return!1;let n=+r[1],o=+r[2],s=+r[3],a=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!e||a)}function N0(e){let t=e.split(_0);return t.length==2&&wh(t[0])&&Ch(!0,t[1])}function U0(e){return $0.test(e)&&F0.test(e)}function q0(e){if(z0.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var v0,S0,A0,T0,M0,k0,E0,L0,P0,I0,R0,W0,H0,B0,D0,Rd,_0,$0,F0,z0,Wd=Gn(()=>{"use strict";v0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S0=[0,31,28,31,30,31,30,31,31,30,31,30,31],A0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,T0=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,M0=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,k0=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,E0=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,L0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,P0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,I0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,R0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,W0=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},H0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,B0=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,D0=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));Rd={date:wh,time:Ch.bind(void 0,!1),"date-time":N0,duration:D0,uri:U0,"uri-reference":Jn(M0),"uri-template":Jn(k0),url:Jn(E0),email:W0,hostname:Jn(T0),ipv4:Jn(H0),ipv6:Jn(B0),regex:q0,uuid:Jn(L0),"json-pointer":Jn(P0),"json-pointer-uri-fragment":Jn(I0),"relative-json-pointer":Jn(R0)};_0=/t|\s/i;$0=/\/|:/,F0=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;z0=/[^\\]\\Z/});var vh,Sh=Gn(()=>{"use strict";(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(vh||(vh={}))});function Ah(e){let t=0,r=e.length,n=0,o;for(;n<r;)t++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=e.charCodeAt(n),(o&64512)==56320&&n++);return t}var Hd=Gn(()=>{"use strict"});function fr(e,t,r="2019-09",n=uo(t),o=!0,s=null,a="#",i="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let l=typeof e,p;switch(l){case"boolean":case"number":case"string":p=l;break;case"object":e===null?p="null":Array.isArray(e)?p="array":p="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:u,$recursiveRef:f,$recursiveAnchor:m,type:y,const:v,enum:E,required:T,not:A,anyOf:M,allOf:b,oneOf:w,if:h,then:k,else:B,format:H,properties:W,patternProperties:N,additionalProperties:q,unevaluatedProperties:se,minProperties:ve,maxProperties:Ue,propertyNames:je,dependentRequired:we,dependentSchemas:Te,dependencies:We,prefixItems:Oe,items:K,additionalItems:He,unevaluatedItems:j,contains:Ce,minContains:Z,maxContains:he,minItems:xe,maxItems:Ve,uniqueItems:G,minimum:ee,maximum:Ie,exclusiveMinimum:ye,exclusiveMaximum:pe,multipleOf:le,minLength:Ye,maxLength:Me,pattern:be,__absolute_ref__:J,__absolute_recursive_ref__:Ke}=t,ne=[];if(m===!0&&s===null&&(s=t),f==="#"){let Q=s===null?n[Ke]:s,Be=`${i}/$recursiveRef`,ke=fr(e,s===null?t:s,r,n,o,Q,a,Be,d);ke.valid||ne.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:Be,error:"A subschema had errors."},...ke.errors)}if(u!==void 0){let Be=n[J||u];if(Be===void 0){let ue=`Unresolved $ref "${u}".`;throw J&&J!==u&&(ue+=` Absolute URI "${J}".`),ue+=`
1
+ "use strict";var AgentWidget=(()=>{var Dy=Object.create;var gs=Object.defineProperty;var Oy=Object.getOwnPropertyDescriptor;var _y=Object.getOwnPropertyNames;var Ny=Object.getPrototypeOf,Fy=Object.prototype.hasOwnProperty;var Sg=t=>{throw TypeError(t)};var $y=(t,e,r)=>e in t?gs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Gn=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mg=(t,e)=>{for(var r in e)gs(t,r,{get:e[r],enumerable:!0})},kg=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _y(e))!Fy.call(t,o)&&o!==r&&gs(t,o,{get:()=>e[o],enumerable:!(n=Oy(e,o))||n.enumerable});return t};var od=(t,e,r)=>(r=t!=null?Dy(Ny(t)):{},kg(e||!t||!t.__esModule?gs(r,"default",{value:t,enumerable:!0}):r,t)),Uy=t=>kg(gs({},"__esModule",{value:!0}),t);var Ht=(t,e,r)=>$y(t,typeof e!="symbol"?e+"":e,r),zy=(t,e,r)=>e.has(t)||Sg("Cannot "+r);var Eg=(t,e,r)=>e.has(t)?Sg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Ai=(t,e,r)=>(zy(t,e,"access private method"),r);function Ea(t,e){let r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let n=t.length;if(n!==e.length)return!1;for(let o=0;o<n;o++)if(!Ea(t[o],e[o]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(let a of n)if(!Ea(t[a],e[a]))return!1;return!0}return t===e}var Ad=Gn(()=>{"use strict"});function xn(t){return encodeURI(Xb(t))}function Xb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Ri=Gn(()=>{"use strict"});function uo(t,e=Object.create(null),r=Zb,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t.$id||t.id;if(s){let a=new URL(s,r.href);a.hash.length>1?e[a.href]=t:(a.hash="",n===""?r=a:uo(t,e,r))}}else if(t!==!0&&t!==!1)return e;let o=r.href+(n?"#"+n:"");if(e[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(e[o]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),t.$ref&&t.__absolute_ref__===void 0){let s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){let s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(Yb[s])continue;let a=`${n}/${xn(s)}`,i=t[s];if(Array.isArray(i)){if(Jb[s]){let d=i.length;for(let l=0;l<d;l++)uo(i[l],e,r,`${a}/${l}`)}}else if(Qb[s])for(let d in i)uo(i[d],e,r,`${a}/${xn(d)}`);else uo(i,e,r,a)}return e}var Jb,Qb,Yb,Zb,Wi=Gn(()=>{"use strict";Ri();Jb={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Qb={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Yb={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Zb=typeof self!="undefined"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Xn(t){return t.test.bind(t)}function g0(t){return t%4===0&&(t%100!==0||t%400===0)}function dh(t){let e=t.match(e0);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&g0(r)?29:t0[n])}function ch(t,e){let r=e.match(r0);if(!r)return!1;let n=+r[1],o=+r[2],s=+r[3],a=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!t||a)}function x0(t){let e=t.split(h0);return e.length==2&&dh(e[0])&&ch(!0,e[1])}function w0(t){return y0.test(t)&&b0.test(t)}function C0(t){if(v0.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var e0,t0,r0,n0,o0,a0,s0,i0,l0,d0,c0,p0,u0,f0,m0,Sd,h0,y0,b0,v0,Td=Gn(()=>{"use strict";e0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,t0=[0,31,28,31,30,31,30,31,31,30,31,30,31],r0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,n0=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,o0=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,a0=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,s0=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,i0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,l0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,d0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,c0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,p0=t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},u0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,f0=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,m0=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));Sd={date:dh,time:ch.bind(void 0,!1),"date-time":x0,duration:m0,uri:w0,"uri-reference":Xn(o0),"uri-template":Xn(a0),url:Xn(s0),email:p0,hostname:Xn(n0),ipv4:Xn(u0),ipv6:Xn(f0),regex:C0,uuid:Xn(i0),"json-pointer":Xn(l0),"json-pointer-uri-fragment":Xn(d0),"relative-json-pointer":Xn(c0)};h0=/t|\s/i;y0=/\/|:/,b0=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;v0=/[^\\]\\Z/});var ph,uh=Gn(()=>{"use strict";(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(ph||(ph={}))});function fh(t){let e=0,r=t.length,n=0,o;for(;n<r;)e++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=t.charCodeAt(n),(o&64512)==56320&&n++);return e}var Md=Gn(()=>{"use strict"});function ur(t,e,r="2019-09",n=uo(e),o=!0,s=null,a="#",i="#",d=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let l=typeof t,p;switch(l){case"boolean":case"number":case"string":p=l;break;case"object":t===null?p="null":Array.isArray(t)?p="array":p="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:m,$recursiveRef:u,$recursiveAnchor:f,type:y,const:A,enum:E,required:T,not:S,anyOf:k,allOf:x,oneOf:b,if:h,then:M,else:W,format:R,properties:B,patternProperties:_,additionalProperties:V,unevaluatedProperties:oe,minProperties:be,maxProperties:Qe,propertyNames:je,dependentRequired:ve,dependentSchemas:Ee,dependencies:Ge,prefixItems:_e,items:X,additionalItems:Ue,unevaluatedItems:K,contains:Te,minContains:ae,maxContains:xe,minItems:Me,maxItems:Ke,uniqueItems:ce,minimum:re,maximum:le,exclusiveMinimum:ut,exclusiveMaximum:Ce,multipleOf:he,minLength:tt,maxLength:Ne,pattern:me,__absolute_ref__:J,__absolute_recursive_ref__:qe}=e,Z=[];if(f===!0&&s===null&&(s=e),u==="#"){let q=s===null?n[qe]:s,Re=`${i}/$recursiveRef`,Ae=ur(t,s===null?e:s,r,n,o,q,a,Re,d);Ae.valid||Z.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:Re,error:"A subschema had errors."},...Ae.errors)}if(m!==void 0){let Re=n[J||m];if(Re===void 0){let pe=`Unresolved $ref "${m}".`;throw J&&J!==m&&(pe+=` Absolute URI "${J}".`),pe+=`
2
2
  Known schemas:
3
3
  - ${Object.keys(n).join(`
4
- - `)}`,new Error(ue)}let ke=`${i}/$ref`,ge=fr(e,Be,r,n,o,s,a,ke,d);if(ge.valid||ne.push({instanceLocation:a,keyword:"$ref",keywordLocation:ke,error:"A subschema had errors."},...ge.errors),r==="4"||r==="7")return{valid:ne.length===0,errors:ne}}if(Array.isArray(y)){let Q=y.length,Be=!1;for(let ke=0;ke<Q;ke++)if(p===y[ke]||y[ke]==="integer"&&p==="number"&&e%1===0&&e===e){Be=!0;break}Be||ne.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y.join('", "')}".`})}else y==="integer"?(p!=="number"||e%1||e!==e)&&ne.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`}):y!==void 0&&p!==y&&ne.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`});if(v!==void 0&&(p==="object"||p==="array"?Is(e,v)||ne.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&ne.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),E!==void 0&&(p==="object"||p==="array"?E.some(Q=>Is(e,Q))||ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(E)}.`}):E.some(Q=>e===Q)||ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(E)}.`})),A!==void 0){let Q=`${i}/not`;fr(e,A,r,n,o,s,a,Q).valid&&ne.push({instanceLocation:a,keyword:"not",keywordLocation:Q,error:'Instance matched "not" schema.'})}let Y=[];if(M!==void 0){let Q=`${i}/anyOf`,Be=ne.length,ke=!1;for(let ge=0;ge<M.length;ge++){let ue=M[ge],_e=Object.create(d),I=fr(e,ue,r,n,o,m===!0?s:null,a,`${Q}/${ge}`,_e);ne.push(...I.errors),ke=ke||I.valid,I.valid&&Y.push(_e)}ke?ne.length=Be:ne.splice(Be,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Q,error:"Instance does not match any subschemas."})}if(b!==void 0){let Q=`${i}/allOf`,Be=ne.length,ke=!0;for(let ge=0;ge<b.length;ge++){let ue=b[ge],_e=Object.create(d),I=fr(e,ue,r,n,o,m===!0?s:null,a,`${Q}/${ge}`,_e);ne.push(...I.errors),ke=ke&&I.valid,I.valid&&Y.push(_e)}ke?ne.length=Be:ne.splice(Be,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Q,error:"Instance does not match every subschema."})}if(w!==void 0){let Q=`${i}/oneOf`,Be=ne.length,ke=w.filter((ge,ue)=>{let _e=Object.create(d),I=fr(e,ge,r,n,o,m===!0?s:null,a,`${Q}/${ue}`,_e);return ne.push(...I.errors),I.valid&&Y.push(_e),I.valid}).length;ke===1?ne.length=Be:ne.splice(Be,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Q,error:`Instance does not match exactly one subschema (${ke} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...Y),h!==void 0){let Q=`${i}/if`;if(fr(e,h,r,n,o,s,a,Q,d).valid){if(k!==void 0){let ke=fr(e,k,r,n,o,s,a,`${i}/then`,d);ke.valid||ne.push({instanceLocation:a,keyword:"if",keywordLocation:Q,error:'Instance does not match "then" schema.'},...ke.errors)}}else if(B!==void 0){let ke=fr(e,B,r,n,o,s,a,`${i}/else`,d);ke.valid||ne.push({instanceLocation:a,keyword:"if",keywordLocation:Q,error:'Instance does not match "else" schema.'},...ke.errors)}}if(p==="object"){if(T!==void 0)for(let ge of T)ge in e||ne.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${ge}".`});let Q=Object.keys(e);if(ve!==void 0&&Q.length<ve&&ne.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${ve} properties.`}),Ue!==void 0&&Q.length>Ue&&ne.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Ue} properties.`}),je!==void 0){let ge=`${i}/propertyNames`;for(let ue in e){let _e=`${a}/${xn(ue)}`,I=fr(ue,je,r,n,o,s,_e,ge);I.valid||ne.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ge,error:`Property name "${ue}" does not match schema.`},...I.errors)}}if(we!==void 0){let ge=`${i}/dependantRequired`;for(let ue in we)if(ue in e){let _e=we[ue];for(let I of _e)I in e||ne.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:ge,error:`Instance has "${ue}" but does not have "${I}".`})}}if(Te!==void 0)for(let ge in Te){let ue=`${i}/dependentSchemas`;if(ge in e){let _e=fr(e,Te[ge],r,n,o,s,a,`${ue}/${xn(ge)}`,d);_e.valid||ne.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:ue,error:`Instance has "${ge}" but does not match dependant schema.`},..._e.errors)}}if(We!==void 0){let ge=`${i}/dependencies`;for(let ue in We)if(ue in e){let _e=We[ue];if(Array.isArray(_e))for(let I of _e)I in e||ne.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ge,error:`Instance has "${ue}" but does not have "${I}".`});else{let I=fr(e,_e,r,n,o,s,a,`${ge}/${xn(ue)}`);I.valid||ne.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ge,error:`Instance has "${ue}" but does not match dependant schema.`},...I.errors)}}}let Be=Object.create(null),ke=!1;if(W!==void 0){let ge=`${i}/properties`;for(let ue in W){if(!(ue in e))continue;let _e=`${a}/${xn(ue)}`,I=fr(e[ue],W[ue],r,n,o,s,_e,`${ge}/${xn(ue)}`);if(I.valid)d[ue]=Be[ue]=!0;else if(ke=o,ne.push({instanceLocation:a,keyword:"properties",keywordLocation:ge,error:`Property "${ue}" does not match schema.`},...I.errors),ke)break}}if(!ke&&N!==void 0){let ge=`${i}/patternProperties`;for(let ue in N){let _e=new RegExp(ue,"u"),I=N[ue];for(let te in e){if(!_e.test(te))continue;let qe=`${a}/${xn(te)}`,tt=fr(e[te],I,r,n,o,s,qe,`${ge}/${xn(ue)}`);tt.valid?d[te]=Be[te]=!0:(ke=o,ne.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:ge,error:`Property "${te}" matches pattern "${ue}" but does not match associated schema.`},...tt.errors))}}}if(!ke&&q!==void 0){let ge=`${i}/additionalProperties`;for(let ue in e){if(Be[ue])continue;let _e=`${a}/${xn(ue)}`,I=fr(e[ue],q,r,n,o,s,_e,ge);I.valid?d[ue]=!0:(ke=o,ne.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:ge,error:`Property "${ue}" does not match additional properties schema.`},...I.errors))}}else if(!ke&&se!==void 0){let ge=`${i}/unevaluatedProperties`;for(let ue in e)if(!d[ue]){let _e=`${a}/${xn(ue)}`,I=fr(e[ue],se,r,n,o,s,_e,ge);I.valid?d[ue]=!0:ne.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:ge,error:`Property "${ue}" does not match unevaluated properties schema.`},...I.errors)}}}else if(p==="array"){Ve!==void 0&&e.length>Ve&&ne.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${Ve}).`}),xe!==void 0&&e.length<xe&&ne.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${xe}).`});let Q=e.length,Be=0,ke=!1;if(Oe!==void 0){let ge=`${i}/prefixItems`,ue=Math.min(Oe.length,Q);for(;Be<ue;Be++){let _e=fr(e[Be],Oe[Be],r,n,o,s,`${a}/${Be}`,`${ge}/${Be}`);if(d[Be]=!0,!_e.valid&&(ke=o,ne.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:ge,error:"Items did not match schema."},..._e.errors),ke))break}}if(K!==void 0){let ge=`${i}/items`;if(Array.isArray(K)){let ue=Math.min(K.length,Q);for(;Be<ue;Be++){let _e=fr(e[Be],K[Be],r,n,o,s,`${a}/${Be}`,`${ge}/${Be}`);if(d[Be]=!0,!_e.valid&&(ke=o,ne.push({instanceLocation:a,keyword:"items",keywordLocation:ge,error:"Items did not match schema."},..._e.errors),ke))break}}else for(;Be<Q;Be++){let ue=fr(e[Be],K,r,n,o,s,`${a}/${Be}`,ge);if(d[Be]=!0,!ue.valid&&(ke=o,ne.push({instanceLocation:a,keyword:"items",keywordLocation:ge,error:"Items did not match schema."},...ue.errors),ke))break}if(!ke&&He!==void 0){let ue=`${i}/additionalItems`;for(;Be<Q;Be++){let _e=fr(e[Be],He,r,n,o,s,`${a}/${Be}`,ue);d[Be]=!0,_e.valid||(ke=o,ne.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:ue,error:"Items did not match additional items schema."},..._e.errors))}}}if(Ce!==void 0)if(Q===0&&Z===void 0)ne.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Z!==void 0&&Q<Z)ne.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${Q}) than minContains (${Z}).`});else{let ge=`${i}/contains`,ue=ne.length,_e=0;for(let I=0;I<Q;I++){let te=fr(e[I],Ce,r,n,o,s,`${a}/${I}`,ge);te.valid?(d[I]=!0,_e++):ne.push(...te.errors)}_e>=(Z||0)&&(ne.length=ue),Z===void 0&&he===void 0&&_e===0?ne.splice(ue,0,{instanceLocation:a,keyword:"contains",keywordLocation:ge,error:"Array does not contain item matching schema."}):Z!==void 0&&_e<Z?ne.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${Z} items matching schema. Only ${_e} items were found.`}):he!==void 0&&_e>he&&ne.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${he} items matching schema. ${_e} items were found.`})}if(!ke&&j!==void 0){let ge=`${i}/unevaluatedItems`;for(Be;Be<Q;Be++){if(d[Be])continue;let ue=fr(e[Be],j,r,n,o,s,`${a}/${Be}`,ge);d[Be]=!0,ue.valid||ne.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:ge,error:"Items did not match unevaluated items schema."},...ue.errors)}}if(G)for(let ge=0;ge<Q;ge++){let ue=e[ge],_e=typeof ue=="object"&&ue!==null;for(let I=0;I<Q;I++){if(ge===I)continue;let te=e[I];(ue===te||_e&&(typeof te=="object"&&te!==null)&&Is(ue,te))&&(ne.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${ge} and ${I}.`}),ge=Number.MAX_SAFE_INTEGER,I=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(ee!==void 0&&(ye===!0&&e<=ee||e<ee)&&ne.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${ye?"or equal to ":""} ${ee}.`}),Ie!==void 0&&(pe===!0&&e>=Ie||e>Ie)&&ne.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${pe?"or equal to ":""} ${Ie}.`})):(ee!==void 0&&e<ee&&ne.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${ee}.`}),Ie!==void 0&&e>Ie&&ne.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${Ie}.`}),ye!==void 0&&e<=ye&&ne.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${ye}.`}),pe!==void 0&&e>=pe&&ne.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${pe}.`})),le!==void 0){let Q=e%le;Math.abs(0-Q)>=11920929e-14&&Math.abs(le-Q)>=11920929e-14&&ne.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${le}.`})}}else if(p==="string"){let Q=Ye===void 0&&Me===void 0?0:Ah(e);Ye!==void 0&&Q<Ye&&ne.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${Q} < ${Ye}).`}),Me!==void 0&&Q>Me&&ne.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${Q} > ${Me}).`}),be!==void 0&&!new RegExp(be,"u").test(e)&&ne.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),H!==void 0&&Rd[H]&&!Rd[H](e)&&ne.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${H}".`})}return{valid:ne.length===0,errors:ne}}var Bd=Gn(()=>{"use strict";Id();Di();Wd();Bi();Hd()});var Oi,Th=Gn(()=>{"use strict";Di();Bd();Oi=class{constructor(t,r="2019-09",n=!0){Dt(this,"schema");Dt(this,"draft");Dt(this,"shortCircuit");Dt(this,"lookup");this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=uo(t)}validate(t){return fr(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),uo(t,this.lookup)}}});var Mh=Gn(()=>{"use strict";Id();Di();Wd();Bi();Sh();Hd();Bd();Th()});var Oh={};Og(Oh,{cleanupWebMCPPolyfill:()=>Dh,initializeWebMCPPolyfill:()=>Bh,initializeWebModelContextPolyfill:()=>Bh,isPlainObject:()=>Dr,validateArgsWithSchema:()=>Rh});function Xn(e){try{return new DOMException(e,"UnknownError")}catch{let t=new Error(e);return t.name="UnknownError",t}}function J0(e){let t;try{t=JSON.parse(e)}catch{throw Xn(kh)}if(!t||typeof t!="object"||Array.isArray(t))throw Xn(kh);return t}function X0(e){if(typeof e=="string")return e;if(Dr(e)&&typeof e.name=="string")return e.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function Dr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ph(e){if(!Dr(e))return null;let t=e["~standard"];return Dr(t)?t:null}function Y0(e){let t=Ph(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function Q0(e){let t=Ph(e);return!t||t.version!==1||!Dr(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Ni(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!Dr(t))return{issues:[{message:"expected object arguments"}]};let r=Rh(t,e);return r?{issues:[r]}:{value:t}}}}}function Z0(e){for(let t of j0)try{let r=e["~standard"].jsonSchema.input({target:t});return Ih(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function ew(e){if(e===void 0){let r=_i;return{inputSchema:r,standardValidator:Ni(r)}}if(Q0(e)){let r=Z0(e);return{inputSchema:r,standardValidator:Ni(r)}}if(Y0(e))return{inputSchema:_i,standardValidator:e};if(Ih(e),Object.keys(e).length===0)return{inputSchema:_i,standardValidator:Ni(_i)};let t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:Ni(t)}}function Ih(e){if(!Dr(e))throw new Error("inputSchema must be a JSON Schema object");Rs(e,"$")}function Rs(e,t){let r=e.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let n=e.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let o=e.properties;if(o!==void 0){if(!Dr(o))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Dr(d))throw new Error(`Invalid JSON Schema at ${t}.properties.${i}: expected object schema`);Rs(d,`${t}.properties.${i}`)}}let s=e.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Dr(d))throw new Error(`Invalid JSON Schema at ${t}.items[${i}]: expected object schema`);Rs(d,`${t}.items[${i}]`)}else if(Dr(s))Rs(s,`${t}.items`);else throw new Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let i of["allOf","anyOf","oneOf"]){let d=e[i];if(d!==void 0){if(!Array.isArray(d))throw new Error(`Invalid JSON Schema at ${t}: "${i}" must be an array`);for(let[l,p]of d.entries()){if(!Dr(p))throw new Error(`Invalid JSON Schema at ${t}.${i}[${l}]: expected object schema`);Rs(p,`${t}.${i}[${l}]`)}}}let a=e.not;if(a!==void 0){if(!Dr(a))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);Rs(a,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function tw(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof e.name!="string"||e.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof e.description!="string"||e.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function');if(t.has(e.name))throw new Error(`Tool already registered: ${e.name}`);let r=ew(e.inputSchema),n=e.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...e,...o?{annotations:o}:{},inputSchema:r.inputSchema,[Lh]:r.standardValidator}}function Rh(e,t){let r=new Oi(t,"2020-12",!0).validate(e);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function rw(e){if(!e||e.length===0)return null;let t=e.map(r=>Dr(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return t.length===0?null:t.join(".")}async function nw(e,t){let r;try{r=await Promise.resolve(t["~standard"].validate(e))}catch(s){let a=s instanceof Error?`: ${s.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",s),`Input validation error: schema validation failed${a}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let o=rw(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function ow(e,t){return nw(e,t[Lh])}function sw(e){return Dr(e)&&Array.isArray(e.content)}function aw(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Od(e){return aw(e)?Number.isFinite(e)||typeof e!="number":Array.isArray(e)?e.every(t=>Od(t)):Dr(e)?Object.values(e).every(t=>Od(t)):!1}function iw(e){if(!(!Dr(e)||!Od(e)))return e}function lw(e){var t;if(typeof e=="string")return e;try{return(t=JSON.stringify(e))!=null?t:String(e)}catch{return String(e)}}function dw(e){if(sw(e))return e;let t=iw(e);return{content:[{type:"text",text:lw(e)}],...t?{structuredContent:t}:{},isError:!1}}function cw(e){var t;for(let r of(t=e.content)!=null?t:[])if(r.type==="text"&&"text"in r&&typeof r.text=="string")return r.text;return null}function pw(e){var r;if(e.isError)throw Xn(((r=cw(e))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||$i);let t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw Xn($i)}}function uw(e,t){return t?t.aborted?Promise.reject(Xn(Dd)):new Promise((r,n)=>{let o=()=>{s(),n(Xn(Dd))},s=()=>{t.removeEventListener("abort",o)};t.addEventListener("abort",o,{once:!0}),e.then(a=>{s(),r(a)},a=>{s(),n(a)})}):e}function Wh(){return typeof navigator!="undefined"?navigator:null}function Hh(){return typeof document!="undefined"?document:null}function fw(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:r})}function Eh(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}function mw(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get(){return Fi||(Fi=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),t}})}function Bh(e){var d;let t=Wh(),r=Hh();if(!t&&!r||(r==null?void 0:r.modelContext))return;let o=t==null?void 0:t.modelContext,s=!!o;if(dr.installed&&Dh(),r&&o){dr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),Eh(r,o),dr.installedDocumentModelContext=!0,dr.installed=!0;return}if(s)return;let a=new G0,i=a;if(i[V0]=!0,r&&(dr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),Eh(r,i),dr.installedDocumentModelContext=!0),t){dr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),dr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),Fi=!1,mw(t,i),dr.installedNavigatorModelContext=!0;let l=(d=e==null?void 0:e.installTestingShim)!=null?d:"if-missing",p=!!t.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!p)&&(fw(t,"modelContextTesting",a.getTestingShim()),dr.installedNavigatorModelContextTesting=!0)}dr.installed=!0}function Dh(){if(!dr.installed)return;let e=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},t=Wh(),r=Hh();r&&dr.installedDocumentModelContext&&e(r,"modelContext",dr.previousDocumentModelContextDescriptor),t&&dr.installedNavigatorModelContext&&e(t,"modelContext",dr.previousNavigatorModelContextDescriptor),t&&dr.installedNavigatorModelContextTesting&&e(t,"modelContextTesting",dr.previousNavigatorModelContextTestingDescriptor),dr.installed=!1,dr.previousDocumentModelContextDescriptor=void 0,dr.previousNavigatorModelContextDescriptor=void 0,dr.previousNavigatorModelContextTestingDescriptor=void 0,dr.installedDocumentModelContext=!1,dr.installedNavigatorModelContext=!1,dr.installedNavigatorModelContextTesting=!1,Fi=!1}var kh,$i,Dd,_i,j0,V0,Lh,dr,G0,K0,Fi,_h=Gn(()=>{"use strict";Mh();kh="Failed to parse input arguments",$i="Tool was executed but the invocation failed. For example, the script function threw an error",Dd="Tool was cancelled",_i={type:"object",properties:{}},j0=["draft-2020-12","draft-07"],V0="__isWebMCPPolyfill",Lh=Symbol("standardValidator"),dr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},G0=class extends EventTarget{constructor(){super(...arguments);Dt(this,"tools",new Map);Dt(this,"testingShim",null);Dt(this,"_ontoolchange",null);Dt(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerTool(t,r){var s;let n=r==null?void 0:r.signal;if(n!=null&&n.aborted){console.warn(`[WebMCPPolyfill] registerTool("${(s=t==null?void 0:t.name)!=null?s:"<unknown>"}") skipped: options.signal was already aborted.`);return}let o=tw(t,this.tools);this.tools.set(o.name,o),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(o.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();let r=X0(t);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,r,n){return this.executeToolByName(t.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new K0(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{var n;let r;try{r=JSON.stringify((n=t.inputSchema)!=null?n:{type:"object"})}catch{r='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{var n,o,s;let r=this.tools.get(t.name);return{...t,title:(n=r==null?void 0:r.title)!=null?n:"",origin:(s=(o=globalThis.location)==null?void 0:o.origin)!=null?s:"",window:globalThis.window}})}async executeToolForTesting(t,r,n){return this.executeToolByName(t,r,n,!0)}async executeToolByName(t,r,n,o){var p;if((p=n==null?void 0:n.signal)!=null&&p.aborted)throw Xn(Dd);let s=this.tools.get(t);if(!s)throw Xn(`Tool not found: ${t}`);let a=J0(r),i=await ow(a,s);if(i)throw Xn(i);let d=!0,l={requestUserInteraction:async u=>{if(!d)throw new Error(`ModelContextClient for tool "${t}" is no longer active after execute() resolved`);if(typeof u!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return u()}};try{let u=s.execute(a,l),f=await uw(Promise.resolve(u),n==null?void 0:n.signal);if(o)return pw(dw(f));let m=JSON.stringify(f);return m===void 0?null:m}catch(u){throw Xn(u instanceof Error?`${$i}: ${u.message}`:$i)}finally{d=!1}}notifyToolsChanged(){queueMicrotask(()=>{var r,n;let t=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,t)}catch(o){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",o)}this.dispatchEvent(t),(n=this.testingShim)==null||n.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},K0=class extends EventTarget{constructor(t){super();Dt(this,"context");Dt(this,"_ontoolchange",null);this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,r,n){return this.context.executeToolForTesting(t,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){var r;let t=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,t)}catch(n){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",n)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};Fi=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let e=window.__webMCPPolyfillOptions;if((e==null?void 0:e.autoInitialize)!==!1)try{Bh(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}});var Nd=Dg(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.Allow=Ze.ALL=Ze.COLLECTION=Ze.ATOM=Ze.SPECIAL=Ze.INF=Ze._INFINITY=Ze.INFINITY=Ze.NAN=Ze.BOOL=Ze.NULL=Ze.OBJ=Ze.ARR=Ze.NUM=Ze.STR=void 0;Ze.STR=1;Ze.NUM=2;Ze.ARR=4;Ze.OBJ=8;Ze.NULL=16;Ze.BOOL=32;Ze.NAN=64;Ze.INFINITY=128;Ze._INFINITY=256;Ze.INF=Ze.INFINITY|Ze._INFINITY;Ze.SPECIAL=Ze.NULL|Ze.BOOL|Ze.INF|Ze.NAN;Ze.ATOM=Ze.STR|Ze.NUM|Ze.SPECIAL;Ze.COLLECTION=Ze.ARR|Ze.OBJ;Ze.ALL=Ze.ATOM|Ze.COLLECTION;Ze.Allow={STR:Ze.STR,NUM:Ze.NUM,ARR:Ze.ARR,OBJ:Ze.OBJ,NULL:Ze.NULL,BOOL:Ze.BOOL,NAN:Ze.NAN,INFINITY:Ze.INFINITY,_INFINITY:Ze._INFINITY,INF:Ze.INF,SPECIAL:Ze.SPECIAL,ATOM:Ze.ATOM,COLLECTION:Ze.COLLECTION,ALL:Ze.ALL};Ze.default=Ze.Allow});var ji=Dg(Or=>{"use strict";var Sw=Or&&Or.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Aw=Or&&Or.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Sw(t,e,r)};Object.defineProperty(Or,"__esModule",{value:!0});Or.Allow=Or.MalformedJSON=Or.PartialJSON=Or.parseJSON=Or.parse=void 0;var Zr=Nd();Object.defineProperty(Or,"Allow",{enumerable:!0,get:function(){return Zr.Allow}});Aw(Nd(),Or);var zi=class extends Error{};Or.PartialJSON=zi;var qi=class extends Error{};Or.MalformedJSON=qi;function Fh(e,t=Zr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Tw(e.trim(),t)}Or.parseJSON=Fh;var Tw=(e,t)=>{let r=e.length,n=0,o=f=>{throw new zi(`${f} at position ${n}`)},s=f=>{throw new qi(`${f} at position ${n}`)},a=()=>(u(),n>=r&&o("Unexpected end of input"),e[n]==='"'?i():e[n]==="{"?d():e[n]==="["?l():e.substring(n,n+4)==="null"||Zr.Allow.NULL&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||Zr.Allow.BOOL&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||Zr.Allow.BOOL&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||Zr.Allow.INFINITY&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||Zr.Allow._INFINITY&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||Zr.Allow.NAN&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),i=()=>{let f=n,m=!1;for(n++;n<r&&(e[n]!=='"'||m&&e[n-1]==="\\");)m=e[n]==="\\"?!m:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(f,++n-Number(m)))}catch(y){s(String(y))}else if(Zr.Allow.STR&t)try{return JSON.parse(e.substring(f,n-Number(m))+'"')}catch{return JSON.parse(e.substring(f,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,u();let f={};try{for(;e[n]!=="}";){if(u(),n>=r&&Zr.Allow.OBJ&t)return f;let m=i();u(),n++;try{let y=a();f[m]=y}catch(y){if(Zr.Allow.OBJ&t)return f;throw y}u(),e[n]===","&&n++}}catch{if(Zr.Allow.OBJ&t)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;e[n]!=="]";)f.push(a()),u(),e[n]===","&&n++}catch{if(Zr.Allow.ARR&t)return f;o("Expected ']' at end of array")}return n++,f},p=()=>{if(n===0){e==="-"&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Zr.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}s(String(m))}}let f=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==r&&!(Zr.Allow.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(f,n))}catch{e.substring(f,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(e.substring(f,e.lastIndexOf("e")))}catch(y){s(String(y))}}},u=()=>{for(;n<r&&`
5
- \r `.includes(e[n]);)n++};return a()},Mw=Fh;Or.parse=Mw});var OS={};Og(OS,{ASK_USER_QUESTION_TOOL_NAME:()=>su,AgentWidgetClient:()=>as,AgentWidgetSession:()=>Ds,AttachmentManager:()=>cs,DEFAULT_COMPONENTS:()=>Np,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>yl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>yn,DEFAULT_PALETTE:()=>Op,DEFAULT_SEMANTIC:()=>_p,DEFAULT_WIDGET_CONFIG:()=>Zt,PRESETS:()=>Hu,PRESET_FULLSCREEN:()=>Wu,PRESET_MINIMAL:()=>Ru,PRESET_SHOP:()=>Iu,THEME_ZONES:()=>lx,VERSION:()=>xs,WEBMCP_TOOL_PREFIX:()=>Ia,WebMcpBridge:()=>Ws,accessibilityPlugin:()=>Fy,animationsPlugin:()=>Uy,applyThemeVariables:()=>Io,attachHeaderToContainer:()=>us,brandPlugin:()=>zy,buildComposer:()=>Fs,buildDefaultHeader:()=>Jp,buildHeader:()=>go,buildHeaderWithLayout:()=>$s,buildMinimalHeader:()=>Xp,collectEnrichedPageContext:()=>Ty,componentRegistry:()=>yo,createActionManager:()=>ni,createAgentExperience:()=>rd,createAskUserQuestionBubble:()=>Fx,createBestAvailableVoiceProvider:()=>al,createBubbleWithLayout:()=>Mx,createCSATFeedback:()=>Zl,createComboButton:()=>Hl,createComponentMiddleware:()=>sy,createComponentStreamParser:()=>Jl,createDefaultSanitizer:()=>Pd,createDemoCarousel:()=>$y,createDirectivePostprocessor:()=>sh,createDropdownMenu:()=>Bo,createFlexibleJsonStreamParser:()=>qh,createIconButton:()=>ir,createImagePart:()=>Yh,createJsonStreamParser:()=>Qi,createLabelButton:()=>Ja,createLocalStorageAdapter:()=>Kl,createMarkdownProcessor:()=>Ta,createMarkdownProcessorFromConfig:()=>ns,createMessageActions:()=>tu,createNPSFeedback:()=>ed,createPlainTextParser:()=>Xi,createPlugin:()=>Vy,createRegexJsonParser:()=>Yi,createStandardBubble:()=>Us,createTextPart:()=>Ba,createTheme:()=>_s,createThemeObserver:()=>vl,createToggleGroup:()=>Xa,createTypingIndicator:()=>fs,createVoiceProvider:()=>ds,createWidgetHostLayout:()=>oi,createXmlParser:()=>Zi,defaultActionHandlers:()=>hs,defaultJsonActionParser:()=>ri,defaultParseRules:()=>ku,detectColorScheme:()=>Na,directivePostprocessor:()=>ah,ensureAskUserQuestionSheet:()=>Gs,escapeHtml:()=>os,extractComponentDirectiveFromMessage:()=>Ql,fileToImagePart:()=>Qh,formatEnrichedContext:()=>My,generateAssistantMessageId:()=>is,generateCodeSnippet:()=>Wy,generateMessageId:()=>Vh,generateStableSelector:()=>Eu,generateUserMessageId:()=>Bs,getActiveTheme:()=>Ns,getColorScheme:()=>Fp,getDisplayText:()=>Kh,getHeaderLayout:()=>Yp,getImageParts:()=>Xh,getPreset:()=>Ky,hasComponentDirective:()=>Yl,hasImages:()=>Jh,headerLayouts:()=>Bl,highContrastPlugin:()=>jy,initAgentWidget:()=>my,isAskUserQuestionMessage:()=>ho,isComponentDirectiveType:()=>oy,isDockedMountMode:()=>Tr,isVoiceSupported:()=>Oa,isWebMcpToolName:()=>Ra,listRegisteredStreamAnimations:()=>jp,markdownPostprocessor:()=>Cd,mergeWithDefaults:()=>bl,normalizeContent:()=>Gh,parseAskUserQuestionPayload:()=>xo,pluginRegistry:()=>ti,reducedMotionPlugin:()=>qy,registerStreamAnimationPlugin:()=>ps,removeAskUserQuestionSheet:()=>_o,renderComponentDirective:()=>Xl,renderLoadingIndicatorWithFallback:()=>eu,renderLucideIcon:()=>Pe,resolveDockConfig:()=>kn,resolveSanitizer:()=>Ps,resolveTokens:()=>wl,stripWebMcpPrefix:()=>_d,themeToCssVariables:()=>Cl,unregisterStreamAnimationPlugin:()=>qp,validateImageFile:()=>Zh,validateTheme:()=>$p});function gd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var rs=gd();function jg(e){rs=e}var Vg=/[&<>"']/,ub=new RegExp(Vg.source,"g"),Gg=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,fb=new RegExp(Gg.source,"g"),mb={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},$g=e=>mb[e];function gn(e,t){if(t){if(Vg.test(e))return e.replace(ub,$g)}else if(Gg.test(e))return e.replace(fb,$g);return e}var gb=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function hb(e){return e.replace(gb,(t,r)=>(r=r.toLowerCase(),r==="colon"?":":r.charAt(0)==="#"?r.charAt(1)==="x"?String.fromCharCode(parseInt(r.substring(2),16)):String.fromCharCode(+r.substring(1)):""))}var xb=/(^|[^\[])\^/g;function nr(e,t){let r=typeof e=="string"?e:e.source;t=t||"";let n={replace:(o,s)=>{let a=typeof s=="string"?s:s.source;return a=a.replace(xb,"$1"),r=r.replace(o,a),n},getRegex:()=>new RegExp(r,t)};return n}function Fg(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}var wa={exec:()=>null};function Ug(e,t){let r=e.replace(/\|/g,(s,a,i)=>{let d=!1,l=a;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=r.split(/ \|/),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function ki(e,t,r){let n=e.length;if(n===0)return"";let o=0;for(;o<n;){let s=e.charAt(n-o-1);if(s===t&&!r)o++;else if(s!==t&&r)o++;else break}return e.slice(0,n-o)}function yb(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return-1}function zg(e,t,r,n){let o=t.href,s=t.title?gn(t.title):null,a=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:r,href:o,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,i}return{type:"image",raw:r,href:o,title:s,text:gn(a)}}function bb(e,t){let r=e.match(/^(\s+)(?:```)/);if(r===null)return t;let n=r[1];return t.split(`
4
+ - `)}`,new Error(pe)}let Ae=`${i}/$ref`,fe=ur(t,Re,r,n,o,s,a,Ae,d);if(fe.valid||Z.push({instanceLocation:a,keyword:"$ref",keywordLocation:Ae,error:"A subschema had errors."},...fe.errors),r==="4"||r==="7")return{valid:Z.length===0,errors:Z}}if(Array.isArray(y)){let q=y.length,Re=!1;for(let Ae=0;Ae<q;Ae++)if(p===y[Ae]||y[Ae]==="integer"&&p==="number"&&t%1===0&&t===t){Re=!0;break}Re||Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y.join('", "')}".`})}else y==="integer"?(p!=="number"||t%1||t!==t)&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`}):y!==void 0&&p!==y&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`});if(A!==void 0&&(p==="object"||p==="array"?Ea(t,A)||Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(A)}.`}):t!==A&&Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})),E!==void 0&&(p==="object"||p==="array"?E.some(q=>Ea(t,q))||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(E)}.`}):E.some(q=>t===q)||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(E)}.`})),S!==void 0){let q=`${i}/not`;ur(t,S,r,n,o,s,a,q).valid&&Z.push({instanceLocation:a,keyword:"not",keywordLocation:q,error:'Instance matched "not" schema.'})}let ge=[];if(k!==void 0){let q=`${i}/anyOf`,Re=Z.length,Ae=!1;for(let fe=0;fe<k.length;fe++){let pe=k[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${q}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae||Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:q,error:"Instance does not match any subschemas."})}if(x!==void 0){let q=`${i}/allOf`,Re=Z.length,Ae=!0;for(let fe=0;fe<x.length;fe++){let pe=x[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${q}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae&&Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"allOf",keywordLocation:q,error:"Instance does not match every subschema."})}if(b!==void 0){let q=`${i}/oneOf`,Re=Z.length,Ae=b.filter((fe,pe)=>{let Be=Object.create(d),Q=ur(t,fe,r,n,o,f===!0?s:null,a,`${q}/${pe}`,Be);return Z.push(...Q.errors),Q.valid&&ge.push(Be),Q.valid}).length;Ae===1?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:q,error:`Instance does not match exactly one subschema (${Ae} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...ge),h!==void 0){let q=`${i}/if`;if(ur(t,h,r,n,o,s,a,q,d).valid){if(M!==void 0){let Ae=ur(t,M,r,n,o,s,a,`${i}/then`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:q,error:'Instance does not match "then" schema.'},...Ae.errors)}}else if(W!==void 0){let Ae=ur(t,W,r,n,o,s,a,`${i}/else`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:q,error:'Instance does not match "else" schema.'},...Ae.errors)}}if(p==="object"){if(T!==void 0)for(let fe of T)fe in t||Z.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${fe}".`});let q=Object.keys(t);if(be!==void 0&&q.length<be&&Z.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${be} properties.`}),Qe!==void 0&&q.length>Qe&&Z.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Qe} properties.`}),je!==void 0){let fe=`${i}/propertyNames`;for(let pe in t){let Be=`${a}/${xn(pe)}`,Q=ur(pe,je,r,n,o,s,Be,fe);Q.valid||Z.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:fe,error:`Property name "${pe}" does not match schema.`},...Q.errors)}}if(ve!==void 0){let fe=`${i}/dependantRequired`;for(let pe in ve)if(pe in t){let Be=ve[pe];for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`})}}if(Ee!==void 0)for(let fe in Ee){let pe=`${i}/dependentSchemas`;if(fe in t){let Be=ur(t,Ee[fe],r,n,o,s,a,`${pe}/${xn(fe)}`,d);Be.valid||Z.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:pe,error:`Instance has "${fe}" but does not match dependant schema.`},...Be.errors)}}if(Ge!==void 0){let fe=`${i}/dependencies`;for(let pe in Ge)if(pe in t){let Be=Ge[pe];if(Array.isArray(Be))for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`});else{let Q=ur(t,Be,r,n,o,s,a,`${fe}/${xn(pe)}`);Q.valid||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not match dependant schema.`},...Q.errors)}}}let Re=Object.create(null),Ae=!1;if(B!==void 0){let fe=`${i}/properties`;for(let pe in B){if(!(pe in t))continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],B[pe],r,n,o,s,Be,`${fe}/${xn(pe)}`);if(Q.valid)d[pe]=Re[pe]=!0;else if(Ae=o,Z.push({instanceLocation:a,keyword:"properties",keywordLocation:fe,error:`Property "${pe}" does not match schema.`},...Q.errors),Ae)break}}if(!Ae&&_!==void 0){let fe=`${i}/patternProperties`;for(let pe in _){let Be=new RegExp(pe,"u"),Q=_[pe];for(let N in t){if(!Be.test(N))continue;let ke=`${a}/${xn(N)}`,He=ur(t[N],Q,r,n,o,s,ke,`${fe}/${xn(pe)}`);He.valid?d[N]=Re[N]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:fe,error:`Property "${N}" matches pattern "${pe}" but does not match associated schema.`},...He.errors))}}}if(!Ae&&V!==void 0){let fe=`${i}/additionalProperties`;for(let pe in t){if(Re[pe])continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],V,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:fe,error:`Property "${pe}" does not match additional properties schema.`},...Q.errors))}}else if(!Ae&&oe!==void 0){let fe=`${i}/unevaluatedProperties`;for(let pe in t)if(!d[pe]){let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],oe,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:Z.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:fe,error:`Property "${pe}" does not match unevaluated properties schema.`},...Q.errors)}}}else if(p==="array"){Ke!==void 0&&t.length>Ke&&Z.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${t.length} > ${Ke}).`}),Me!==void 0&&t.length<Me&&Z.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${t.length} < ${Me}).`});let q=t.length,Re=0,Ae=!1;if(_e!==void 0){let fe=`${i}/prefixItems`,pe=Math.min(_e.length,q);for(;Re<pe;Re++){let Be=ur(t[Re],_e[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}if(X!==void 0){let fe=`${i}/items`;if(Array.isArray(X)){let pe=Math.min(X.length,q);for(;Re<pe;Re++){let Be=ur(t[Re],X[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}else for(;Re<q;Re++){let pe=ur(t[Re],X,r,n,o,s,`${a}/${Re}`,fe);if(d[Re]=!0,!pe.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...pe.errors),Ae))break}if(!Ae&&Ue!==void 0){let pe=`${i}/additionalItems`;for(;Re<q;Re++){let Be=ur(t[Re],Ue,r,n,o,s,`${a}/${Re}`,pe);d[Re]=!0,Be.valid||(Ae=o,Z.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:pe,error:"Items did not match additional items schema."},...Be.errors))}}}if(Te!==void 0)if(q===0&&ae===void 0)Z.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ae!==void 0&&q<ae)Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${q}) than minContains (${ae}).`});else{let fe=`${i}/contains`,pe=Z.length,Be=0;for(let Q=0;Q<q;Q++){let N=ur(t[Q],Te,r,n,o,s,`${a}/${Q}`,fe);N.valid?(d[Q]=!0,Be++):Z.push(...N.errors)}Be>=(ae||0)&&(Z.length=pe),ae===void 0&&xe===void 0&&Be===0?Z.splice(pe,0,{instanceLocation:a,keyword:"contains",keywordLocation:fe,error:"Array does not contain item matching schema."}):ae!==void 0&&Be<ae?Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${ae} items matching schema. Only ${Be} items were found.`}):xe!==void 0&&Be>xe&&Z.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${xe} items matching schema. ${Be} items were found.`})}if(!Ae&&K!==void 0){let fe=`${i}/unevaluatedItems`;for(Re;Re<q;Re++){if(d[Re])continue;let pe=ur(t[Re],K,r,n,o,s,`${a}/${Re}`,fe);d[Re]=!0,pe.valid||Z.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:fe,error:"Items did not match unevaluated items schema."},...pe.errors)}}if(ce)for(let fe=0;fe<q;fe++){let pe=t[fe],Be=typeof pe=="object"&&pe!==null;for(let Q=0;Q<q;Q++){if(fe===Q)continue;let N=t[Q];(pe===N||Be&&(typeof N=="object"&&N!==null)&&Ea(pe,N))&&(Z.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${fe} and ${Q}.`}),fe=Number.MAX_SAFE_INTEGER,Q=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(re!==void 0&&(ut===!0&&t<=re||t<re)&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${ut?"or equal to ":""} ${re}.`}),le!==void 0&&(Ce===!0&&t>=le||t>le)&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${Ce?"or equal to ":""} ${le}.`})):(re!==void 0&&t<re&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${re}.`}),le!==void 0&&t>le&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${le}.`}),ut!==void 0&&t<=ut&&Z.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${t} is less than ${ut}.`}),Ce!==void 0&&t>=Ce&&Z.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ce}.`})),he!==void 0){let q=t%he;Math.abs(0-q)>=11920929e-14&&Math.abs(he-q)>=11920929e-14&&Z.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${t} is not a multiple of ${he}.`})}}else if(p==="string"){let q=tt===void 0&&Ne===void 0?0:fh(t);tt!==void 0&&q<tt&&Z.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${q} < ${tt}).`}),Ne!==void 0&&q>Ne&&Z.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${q} > ${Ne}).`}),me!==void 0&&!new RegExp(me,"u").test(t)&&Z.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),R!==void 0&&Sd[R]&&!Sd[R](t)&&Z.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${R}".`})}return{valid:Z.length===0,errors:Z}}var kd=Gn(()=>{"use strict";Ad();Wi();Td();Ri();Md()});var Bi,mh=Gn(()=>{"use strict";Wi();kd();Bi=class{constructor(e,r="2019-09",n=!0){Ht(this,"schema");Ht(this,"draft");Ht(this,"shortCircuit");Ht(this,"lookup");this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=uo(e)}validate(e){return ur(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),uo(e,this.lookup)}}});var gh=Gn(()=>{"use strict";Ad();Wi();Td();Ri();uh();Md();kd();mh()});var Mh={};Mg(Mh,{cleanupWebMCPPolyfill:()=>Th,initializeWebMCPPolyfill:()=>Sh,initializeWebModelContextPolyfill:()=>Sh,isPlainObject:()=>Hr,validateArgsWithSchema:()=>vh});function Jn(t){try{return new DOMException(t,"UnknownError")}catch{let e=new Error(t);return e.name="UnknownError",e}}function k0(t){let e;try{e=JSON.parse(t)}catch{throw Jn(hh)}if(!e||typeof e!="object"||Array.isArray(e))throw Jn(hh);return e}function E0(t){if(typeof t=="string")return t;if(Hr(t)&&typeof t.name=="string")return t.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function Hr(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function bh(t){if(!Hr(t))return null;let e=t["~standard"];return Hr(e)?e:null}function L0(t){let e=bh(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function P0(t){let e=bh(t);return!e||e.version!==1||!Hr(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function Di(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!Hr(e))return{issues:[{message:"expected object arguments"}]};let r=vh(e,t);return r?{issues:[r]}:{value:e}}}}}function I0(t){for(let e of A0)try{let r=t["~standard"].jsonSchema.input({target:e});return wh(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function R0(t){if(t===void 0){let r=Hi;return{inputSchema:r,standardValidator:Di(r)}}if(P0(t)){let r=I0(t);return{inputSchema:r,standardValidator:Di(r)}}if(L0(t))return{inputSchema:Hi,standardValidator:t};if(wh(t),Object.keys(t).length===0)return{inputSchema:Hi,standardValidator:Di(Hi)};let e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:Di(e)}}function wh(t){if(!Hr(t))throw new Error("inputSchema must be a JSON Schema object");La(t,"$")}function La(t,e){let r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);let n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);let o=t.properties;if(o!==void 0){if(!Hr(o))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.properties.${i}: expected object schema`);La(d,`${e}.properties.${i}`)}}let s=t.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.items[${i}]: expected object schema`);La(d,`${e}.items[${i}]`)}else if(Hr(s))La(s,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(let i of["allOf","anyOf","oneOf"]){let d=t[i];if(d!==void 0){if(!Array.isArray(d))throw new Error(`Invalid JSON Schema at ${e}: "${i}" must be an array`);for(let[l,p]of d.entries()){if(!Hr(p))throw new Error(`Invalid JSON Schema at ${e}.${i}[${l}]: expected object schema`);La(p,`${e}.${i}[${l}]`)}}}let a=t.not;if(a!==void 0){if(!Hr(a))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);La(a,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function W0(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);let r=R0(t.inputSchema),n=t.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...o?{annotations:o}:{},inputSchema:r.inputSchema,[yh]:r.standardValidator}}function vh(t,e){let r=new Bi(e,"2020-12",!0).validate(t);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function B0(t){if(!t||t.length===0)return null;let e=t.map(r=>Hr(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function H0(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(s){let a=s instanceof Error?`: ${s.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",s),`Input validation error: schema validation failed${a}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let o=B0(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function D0(t,e){return H0(t,e[yh])}function O0(t){return Hr(t)&&Array.isArray(t.content)}function _0(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Ld(t){return _0(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>Ld(e)):Hr(t)?Object.values(t).every(e=>Ld(e)):!1}function N0(t){if(!(!Hr(t)||!Ld(t)))return t}function F0(t){var e;if(typeof t=="string")return t;try{return(e=JSON.stringify(t))!=null?e:String(t)}catch{return String(t)}}function $0(t){if(O0(t))return t;let e=N0(t);return{content:[{type:"text",text:F0(t)}],...e?{structuredContent:e}:{},isError:!1}}function U0(t){var e;for(let r of(e=t.content)!=null?e:[])if(r.type==="text"&&"text"in r&&typeof r.text=="string")return r.text;return null}function z0(t){var r;if(t.isError)throw Jn(((r=U0(t))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||Oi);let e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw Jn(Oi)}}function q0(t,e){return e?e.aborted?Promise.reject(Jn(Ed)):new Promise((r,n)=>{let o=()=>{s(),n(Jn(Ed))},s=()=>{e.removeEventListener("abort",o)};e.addEventListener("abort",o,{once:!0}),t.then(a=>{s(),r(a)},a=>{s(),n(a)})}):t}function Ch(){return typeof navigator!="undefined"?navigator:null}function Ah(){return typeof document!="undefined"?document:null}function V0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function xh(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}function j0(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return _i||(_i=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),e}})}function Sh(t){var d;let e=Ch(),r=Ah();if(!e&&!r||(r==null?void 0:r.modelContext))return;let o=e==null?void 0:e.modelContext,s=!!o;if(lr.installed&&Th(),r&&o){lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),xh(r,o),lr.installedDocumentModelContext=!0,lr.installed=!0;return}if(s)return;let a=new T0,i=a;if(i[S0]=!0,r&&(lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),xh(r,i),lr.installedDocumentModelContext=!0),e){lr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),lr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),_i=!1,j0(e,i),lr.installedNavigatorModelContext=!0;let l=(d=t==null?void 0:t.installTestingShim)!=null?d:"if-missing",p=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!p)&&(V0(e,"modelContextTesting",a.getTestingShim()),lr.installedNavigatorModelContextTesting=!0)}lr.installed=!0}function Th(){if(!lr.installed)return;let t=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},e=Ch(),r=Ah();r&&lr.installedDocumentModelContext&&t(r,"modelContext",lr.previousDocumentModelContextDescriptor),e&&lr.installedNavigatorModelContext&&t(e,"modelContext",lr.previousNavigatorModelContextDescriptor),e&&lr.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",lr.previousNavigatorModelContextTestingDescriptor),lr.installed=!1,lr.previousDocumentModelContextDescriptor=void 0,lr.previousNavigatorModelContextDescriptor=void 0,lr.previousNavigatorModelContextTestingDescriptor=void 0,lr.installedDocumentModelContext=!1,lr.installedNavigatorModelContext=!1,lr.installedNavigatorModelContextTesting=!1,_i=!1}var hh,Oi,Ed,Hi,A0,S0,yh,lr,T0,M0,_i,kh=Gn(()=>{"use strict";gh();hh="Failed to parse input arguments",Oi="Tool was executed but the invocation failed. For example, the script function threw an error",Ed="Tool was cancelled",Hi={type:"object",properties:{}},A0=["draft-2020-12","draft-07"],S0="__isWebMCPPolyfill",yh=Symbol("standardValidator"),lr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},T0=class extends EventTarget{constructor(){super(...arguments);Ht(this,"tools",new Map);Ht(this,"testingShim",null);Ht(this,"_ontoolchange",null);Ht(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,r){var s;let n=r==null?void 0:r.signal;if(n!=null&&n.aborted){console.warn(`[WebMCPPolyfill] registerTool("${(s=e==null?void 0:e.name)!=null?s:"<unknown>"}") skipped: options.signal was already aborted.`);return}let o=W0(e,this.tools);this.tools.set(o.name,o),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(o.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let r=E0(e);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,r,n){return this.executeToolByName(e.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new M0(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{var n;let r;try{r=JSON.stringify((n=e.inputSchema)!=null?n:{type:"object"})}catch{r='{"type":"object"}'}return{name:e.name,description:e.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{var n,o,s;let r=this.tools.get(e.name);return{...e,title:(n=r==null?void 0:r.title)!=null?n:"",origin:(s=(o=globalThis.location)==null?void 0:o.origin)!=null?s:"",window:globalThis.window}})}async executeToolForTesting(e,r,n){return this.executeToolByName(e,r,n,!0)}async executeToolByName(e,r,n,o){var p;if((p=n==null?void 0:n.signal)!=null&&p.aborted)throw Jn(Ed);let s=this.tools.get(e);if(!s)throw Jn(`Tool not found: ${e}`);let a=k0(r),i=await D0(a,s);if(i)throw Jn(i);let d=!0,l={requestUserInteraction:async m=>{if(!d)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof m!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return m()}};try{let m=s.execute(a,l),u=await q0(Promise.resolve(m),n==null?void 0:n.signal);if(o)return z0($0(u));let f=JSON.stringify(u);return f===void 0?null:f}catch(m){throw Jn(m instanceof Error?`${Oi}: ${m.message}`:Oi)}finally{d=!1}}notifyToolsChanged(){queueMicrotask(()=>{var r,n;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(o){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",o)}this.dispatchEvent(e),(n=this.testingShim)==null||n.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},M0=class extends EventTarget{constructor(e){super();Ht(this,"context");Ht(this,"_ontoolchange",null);this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,r,n){return this.context.executeToolForTesting(e,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",e)}dispatchToolChange(){var r;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(n){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",n)}this.dispatchEvent(e),this.dispatchEvent(new Event("toolschanged"))}};_i=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let t=window.__webMCPPolyfillOptions;if((t==null?void 0:t.autoInitialize)!==!1)try{Sh(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}});var Id=Tg(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.Allow=Ze.ALL=Ze.COLLECTION=Ze.ATOM=Ze.SPECIAL=Ze.INF=Ze._INFINITY=Ze.INFINITY=Ze.NAN=Ze.BOOL=Ze.NULL=Ze.OBJ=Ze.ARR=Ze.NUM=Ze.STR=void 0;Ze.STR=1;Ze.NUM=2;Ze.ARR=4;Ze.OBJ=8;Ze.NULL=16;Ze.BOOL=32;Ze.NAN=64;Ze.INFINITY=128;Ze._INFINITY=256;Ze.INF=Ze.INFINITY|Ze._INFINITY;Ze.SPECIAL=Ze.NULL|Ze.BOOL|Ze.INF|Ze.NAN;Ze.ATOM=Ze.STR|Ze.NUM|Ze.SPECIAL;Ze.COLLECTION=Ze.ARR|Ze.OBJ;Ze.ALL=Ze.ATOM|Ze.COLLECTION;Ze.Allow={STR:Ze.STR,NUM:Ze.NUM,ARR:Ze.ARR,OBJ:Ze.OBJ,NULL:Ze.NULL,BOOL:Ze.BOOL,NAN:Ze.NAN,INFINITY:Ze.INFINITY,_INFINITY:Ze._INFINITY,INF:Ze.INF,SPECIAL:Ze.SPECIAL,ATOM:Ze.ATOM,COLLECTION:Ze.COLLECTION,ALL:Ze.ALL};Ze.default=Ze.Allow});var Ui=Tg(Dr=>{"use strict";var tw=Dr&&Dr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),rw=Dr&&Dr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&tw(e,t,r)};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.Allow=Dr.MalformedJSON=Dr.PartialJSON=Dr.parseJSON=Dr.parse=void 0;var Zr=Id();Object.defineProperty(Dr,"Allow",{enumerable:!0,get:function(){return Zr.Allow}});rw(Id(),Dr);var Fi=class extends Error{};Dr.PartialJSON=Fi;var $i=class extends Error{};Dr.MalformedJSON=$i;function Ph(t,e=Zr.Allow.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return nw(t.trim(),e)}Dr.parseJSON=Ph;var nw=(t,e)=>{let r=t.length,n=0,o=u=>{throw new Fi(`${u} at position ${n}`)},s=u=>{throw new $i(`${u} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?d():t[n]==="["?l():t.substring(n,n+4)==="null"||Zr.Allow.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||Zr.Allow.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||Zr.Allow.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||Zr.Allow.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||Zr.Allow._INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||Zr.Allow.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):p()),i=()=>{let u=n,f=!1;for(n++;n<r&&(t[n]!=='"'||f&&t[n-1]==="\\");)f=t[n]==="\\"?!f:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(u,++n-Number(f)))}catch(y){s(String(y))}else if(Zr.Allow.STR&e)try{return JSON.parse(t.substring(u,n-Number(f))+'"')}catch{return JSON.parse(t.substring(u,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,m();let u={};try{for(;t[n]!=="}";){if(m(),n>=r&&Zr.Allow.OBJ&e)return u;let f=i();m(),n++;try{let y=a();u[f]=y}catch(y){if(Zr.Allow.OBJ&e)return u;throw y}m(),t[n]===","&&n++}}catch{if(Zr.Allow.OBJ&e)return u;o("Expected '}' at end of object")}return n++,u},l=()=>{n++;let u=[];try{for(;t[n]!=="]";)u.push(a()),m(),t[n]===","&&n++}catch{if(Zr.Allow.ARR&e)return u;o("Expected ']' at end of array")}return n++,u},p=()=>{if(n===0){t==="-"&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(Zr.Allow.NUM&e)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(f))}}let u=n;for(t[n]==="-"&&n++;t[n]&&",]}".indexOf(t[n])===-1;)n++;n==r&&!(Zr.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(u,n))}catch{t.substring(u,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(t.substring(u,t.lastIndexOf("e")))}catch(y){s(String(y))}}},m=()=>{for(;n<r&&`
5
+ \r `.includes(t[n]);)n++};return a()},ow=Ph;Dr.parse=ow});var tA={};Mg(tA,{ASK_USER_QUESTION_TOOL_NAME:()=>Qp,AgentWidgetClient:()=>aa,AgentWidgetSession:()=>Wa,AttachmentManager:()=>da,DEFAULT_COMPONENTS:()=>Ip,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>gl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>yn,DEFAULT_PALETTE:()=>Lp,DEFAULT_SEMANTIC:()=>Pp,DEFAULT_WIDGET_CONFIG:()=>er,PRESETS:()=>Su,PRESET_FULLSCREEN:()=>Au,PRESET_MINIMAL:()=>Cu,PRESET_SHOP:()=>vu,THEME_ZONES:()=>Qh,VERSION:()=>yy,WEBMCP_TOOL_PREFIX:()=>Es,WebMcpBridge:()=>Pa,accessibilityPlugin:()=>by,animationsPlugin:()=>wy,applyThemeVariables:()=>Io,attachHeaderToContainer:()=>pa,brandPlugin:()=>vy,buildComposer:()=>_a,buildDefaultHeader:()=>$p,buildHeader:()=>go,buildHeaderWithLayout:()=>Oa,buildMinimalHeader:()=>Up,collectEnrichedPageContext:()=>gy,componentRegistry:()=>yo,createActionManager:()=>Zs,createAgentExperience:()=>Zl,createAskUserQuestionBubble:()=>Ix,createBestAvailableVoiceProvider:()=>nl,createBubbleWithLayout:()=>hx,createCSATFeedback:()=>Jl,createComboButton:()=>Il,createComponentMiddleware:()=>Xx,createComponentStreamParser:()=>jl,createDefaultSanitizer:()=>Cd,createDirectivePostprocessor:()=>Kg,createDropdownMenu:()=>Ho,createFlexibleJsonStreamParser:()=>Wh,createIconButton:()=>Er,createImagePart:()=>Fh,createJsonStreamParser:()=>Xi,createLabelButton:()=>js,createLocalStorageAdapter:()=>Vl,createMarkdownProcessor:()=>Cs,createMarkdownProcessorFromConfig:()=>ra,createMessageActions:()=>Gp,createNPSFeedback:()=>Ql,createPlainTextParser:()=>Gi,createPlugin:()=>Sy,createRegexJsonParser:()=>Ki,createStandardBubble:()=>Na,createTextPart:()=>Rs,createTheme:()=>Ha,createThemeObserver:()=>bl,createToggleGroup:()=>dx,createTypingIndicator:()=>ua,createVoiceProvider:()=>la,createWidgetHostLayout:()=>ei,createXmlParser:()=>Ji,defaultActionHandlers:()=>ga,defaultJsonActionParser:()=>Ys,defaultParseRules:()=>bu,detectColorScheme:()=>Ds,directivePostprocessor:()=>Xg,ensureAskUserQuestionSheet:()=>qa,escapeHtml:()=>na,extractComponentDirectiveFromMessage:()=>Xl,fileToImagePart:()=>$h,formatEnrichedContext:()=>hy,generateAssistantMessageId:()=>sa,generateMessageId:()=>Hh,generateStableSelector:()=>wu,generateUserMessageId:()=>Ra,getActiveTheme:()=>Da,getColorScheme:()=>Wp,getDisplayText:()=>Oh,getHeaderLayout:()=>zp,getImageParts:()=>Nh,getPreset:()=>My,hasComponentDirective:()=>Kl,hasImages:()=>_h,headerLayouts:()=>Rl,highContrastPlugin:()=>Ay,initAgentWidget:()=>oy,isAskUserQuestionMessage:()=>ho,isComponentDirectiveType:()=>Kx,isDockedMountMode:()=>Ar,isVoiceSupported:()=>Bs,isWebMcpToolName:()=>Ls,listRegisteredStreamAnimations:()=>Op,markdownPostprocessor:()=>fd,mergeWithDefaults:()=>hl,normalizeContent:()=>Dh,parseAskUserQuestionPayload:()=>xo,pluginRegistry:()=>Qs,reducedMotionPlugin:()=>Cy,registerStreamAnimationPlugin:()=>ca,removeAskUserQuestionSheet:()=>_o,renderComponentDirective:()=>Gl,renderLoadingIndicatorWithFallback:()=>jp,renderLucideIcon:()=>Ie,resolveDockConfig:()=>kn,resolveSanitizer:()=>ka,resolveTokens:()=>xl,stripWebMcpPrefix:()=>Pd,themeToCssVariables:()=>yl,unregisterStreamAnimationPlugin:()=>Dp,validateImageFile:()=>Uh,validateTheme:()=>Rp});function id(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ta=id();function Bg(t){ta=t}var Hg=/[&<>"']/,qy=new RegExp(Hg.source,"g"),Dg=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Vy=new RegExp(Dg.source,"g"),jy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Lg=t=>jy[t];function gn(t,e){if(e){if(Hg.test(t))return t.replace(qy,Lg)}else if(Dg.test(t))return t.replace(Vy,Lg);return t}var Gy=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Ky(t){return t.replace(Gy,(e,r)=>(r=r.toLowerCase(),r==="colon"?":":r.charAt(0)==="#"?r.charAt(1)==="x"?String.fromCharCode(parseInt(r.substring(2),16)):String.fromCharCode(+r.substring(1)):""))}var Xy=/(^|[^\[])\^/g;function or(t,e){let r=typeof t=="string"?t:t.source;e=e||"";let n={replace:(o,s)=>{let a=typeof s=="string"?s:s.source;return a=a.replace(Xy,"$1"),r=r.replace(o,a),n},getRegex:()=>new RegExp(r,e)};return n}function Pg(t){try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}var xs={exec:()=>null};function Ig(t,e){let r=t.replace(/\|/g,(s,a,i)=>{let d=!1,l=a;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=r.split(/ \|/),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function Si(t,e,r){let n=t.length;if(n===0)return"";let o=0;for(;o<n;){let s=t.charAt(n-o-1);if(s===e&&!r)o++;else if(s!==e&&r)o++;else break}return t.slice(0,n-o)}function Jy(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let n=0;n<t.length;n++)if(t[n]==="\\")n++;else if(t[n]===e[0])r++;else if(t[n]===e[1]&&(r--,r<0))return n;return-1}function Rg(t,e,r,n){let o=e.href,s=e.title?gn(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");if(t[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:r,href:o,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,i}return{type:"image",raw:r,href:o,title:s,text:gn(a)}}function Qy(t,e){let r=t.match(/^(\s+)(?:```)/);if(r===null)return e;let n=r[1];return e.split(`
6
6
  `).map(o=>{let s=o.match(/^\s+/);if(s===null)return o;let[a]=s;return a.length>=n.length?o.slice(n.length):o}).join(`
7
- `)}var Es=class{constructor(t){Dt(this,"options");Dt(this,"rules");Dt(this,"lexer");this.options=t||rs}space(t){let r=this.rules.block.newline.exec(t);if(r&&r[0].length>0)return{type:"space",raw:r[0]}}code(t){let r=this.rules.block.code.exec(t);if(r){let n=r[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:r[0],codeBlockStyle:"indented",text:this.options.pedantic?n:ki(n,`
8
- `)}}}fences(t){let r=this.rules.block.fences.exec(t);if(r){let n=r[0],o=bb(n,r[3]||"");return{type:"code",raw:n,lang:r[2]?r[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):r[2],text:o}}}heading(t){let r=this.rules.block.heading.exec(t);if(r){let n=r[2].trim();if(/#$/.test(n)){let o=ki(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:r[0],depth:r[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let r=this.rules.block.hr.exec(t);if(r)return{type:"hr",raw:r[0]}}blockquote(t){let r=this.rules.block.blockquote.exec(t);if(r){let n=r[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
9
- $1`);n=ki(n.replace(/^ *>[ \t]?/gm,""),`
10
- `);let o=this.lexer.state.top;this.lexer.state.top=!0;let s=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:r[0],tokens:s,text:n}}}list(t){let r=this.rules.block.list.exec(t);if(r){let n=r[1].trim(),o=n.length>1,s={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let a=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;t;){let p=!1;if(!(r=a.exec(t))||this.rules.block.hr.test(t))break;i=r[0],t=t.substring(i.length);let u=r[2].split(`
11
- `,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),f=t.split(`
12
- `,1)[0],m=0;this.options.pedantic?(m=2,d=u.trimStart()):(m=r[2].search(/[^ ]/),m=m>4?1:m,d=u.slice(m),m+=r[1].length);let y=!1;if(!u&&/^ *$/.test(f)&&(i+=f+`
13
- `,t=t.substring(f.length+1),p=!0),!p){let T=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),A=new RegExp(`^ {0,${Math.min(3,m-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),M=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:\`\`\`|~~~)`),b=new RegExp(`^ {0,${Math.min(3,m-1)}}#`);for(;t;){let w=t.split(`
14
- `,1)[0];if(f=w,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),M.test(f)||b.test(f)||T.test(f)||A.test(t))break;if(f.search(/[^ ]/)>=m||!f.trim())d+=`
15
- `+f.slice(m);else{if(y||u.search(/[^ ]/)>=4||M.test(u)||b.test(u)||A.test(u))break;d+=`
16
- `+f}!y&&!f.trim()&&(y=!0),i+=w+`
17
- `,t=t.substring(w.length+1),u=f.slice(m)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let v=null,E;this.options.gfm&&(v=/^\[[ xX]\] /.exec(d),v&&(E=v[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!v,checked:E,loose:!1,text:d,tokens:[]}),s.raw+=i}s.items[s.items.length-1].raw=i.trimEnd(),s.items[s.items.length-1].text=d.trimEnd(),s.raw=s.raw.trimEnd();for(let p=0;p<s.items.length;p++)if(this.lexer.state.top=!1,s.items[p].tokens=this.lexer.blockTokens(s.items[p].text,[]),!s.loose){let u=s.items[p].tokens.filter(m=>m.type==="space"),f=u.length>0&&u.some(m=>/\n.*\n/.test(m.raw));s.loose=f}if(s.loose)for(let p=0;p<s.items.length;p++)s.items[p].loose=!0;return s}}html(t){let r=this.rules.block.html.exec(t);if(r)return{type:"html",block:!0,raw:r[0],pre:r[1]==="pre"||r[1]==="script"||r[1]==="style",text:r[0]}}def(t){let r=this.rules.block.def.exec(t);if(r){let n=r[1].toLowerCase().replace(/\s+/g," "),o=r[2]?r[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=r[3]?r[3].substring(1,r[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):r[3];return{type:"def",tag:n,raw:r[0],href:o,title:s}}}table(t){let r=this.rules.block.table.exec(t);if(!r||!/[:|]/.test(r[2]))return;let n=Ug(r[1]),o=r[2].replace(/^\||\| *$/g,"").split("|"),s=r[3]&&r[3].trim()?r[3].replace(/\n[ \t]*$/,"").split(`
18
- `):[],a={type:"table",raw:r[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let i of o)/^ *-+: *$/.test(i)?a.align.push("right"):/^ *:-+: *$/.test(i)?a.align.push("center"):/^ *:-+ *$/.test(i)?a.align.push("left"):a.align.push(null);for(let i of n)a.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of s)a.rows.push(Ug(i,a.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return a}}lheading(t){let r=this.rules.block.lheading.exec(t);if(r)return{type:"heading",raw:r[0],depth:r[2].charAt(0)==="="?1:2,text:r[1],tokens:this.lexer.inline(r[1])}}paragraph(t){let r=this.rules.block.paragraph.exec(t);if(r){let n=r[1].charAt(r[1].length-1)===`
19
- `?r[1].slice(0,-1):r[1];return{type:"paragraph",raw:r[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let r=this.rules.block.text.exec(t);if(r)return{type:"text",raw:r[0],text:r[0],tokens:this.lexer.inline(r[0])}}escape(t){let r=this.rules.inline.escape.exec(t);if(r)return{type:"escape",raw:r[0],text:gn(r[1])}}tag(t){let r=this.rules.inline.tag.exec(t);if(r)return!this.lexer.state.inLink&&/^<a /i.test(r[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(r[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:r[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:r[0]}}link(t){let r=this.rules.inline.link.exec(t);if(r){let n=r[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let a=ki(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=yb(r[2],"()");if(a>-1){let d=(r[0].indexOf("!")===0?5:4)+r[1].length+a;r[2]=r[2].substring(0,a),r[0]=r[0].substring(0,d).trim(),r[3]=""}}let o=r[2],s="";if(this.options.pedantic){let a=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);a&&(o=a[1],s=a[3])}else s=r[3]?r[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(n)?o=o.slice(1):o=o.slice(1,-1)),zg(r,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},r[0],this.lexer)}}reflink(t,r){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let o=(n[2]||n[1]).replace(/\s+/g," "),s=r[o.toLowerCase()];if(!s){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return zg(n,s,n[0],this.lexer)}}emStrong(t,r,n=""){let o=this.rules.inline.emStrongLDelim.exec(t);if(!o||o[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(o[1]||o[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let a=[...o[0]].length-1,i,d,l=a,p=0,u=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,r=r.slice(-1*t.length+a);(o=u.exec(r))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&a%3&&!((a+d)%3)){p+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+p);let f=[...o[0]][0].length,m=t.slice(0,a+o.index+f+d);if(Math.min(a,d)%2){let v=m.slice(1,-1);return{type:"em",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}let y=m.slice(2,-2);return{type:"strong",raw:m,text:y,tokens:this.lexer.inlineTokens(y)}}}}codespan(t){let r=this.rules.inline.code.exec(t);if(r){let n=r[2].replace(/\n/g," "),o=/[^ ]/.test(n),s=/^ /.test(n)&&/ $/.test(n);return o&&s&&(n=n.substring(1,n.length-1)),n=gn(n,!0),{type:"codespan",raw:r[0],text:n}}}br(t){let r=this.rules.inline.br.exec(t);if(r)return{type:"br",raw:r[0]}}del(t){let r=this.rules.inline.del.exec(t);if(r)return{type:"del",raw:r[0],text:r[2],tokens:this.lexer.inlineTokens(r[2])}}autolink(t){let r=this.rules.inline.autolink.exec(t);if(r){let n,o;return r[2]==="@"?(n=gn(r[1]),o="mailto:"+n):(n=gn(r[1]),o=n),{type:"link",raw:r[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(t){var n,o;let r;if(r=this.rules.inline.url.exec(t)){let s,a;if(r[2]==="@")s=gn(r[0]),a="mailto:"+s;else{let i;do i=r[0],r[0]=(o=(n=this.rules.inline._backpedal.exec(r[0]))==null?void 0:n[0])!=null?o:"";while(i!==r[0]);s=gn(r[0]),r[1]==="www."?a="http://"+r[0]:a=r[0]}return{type:"link",raw:r[0],text:s,href:a,tokens:[{type:"text",raw:s,text:s}]}}}inlineText(t){let r=this.rules.inline.text.exec(t);if(r){let n;return this.lexer.state.inRawBlock?n=r[0]:n=gn(r[0]),{type:"text",raw:r[0],text:n}}}},wb=/^(?: *(?:\n|$))+/,Cb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,vb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Sa=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Sb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Kg=/(?:[*+-]|\d{1,9}[.)])/,Jg=nr(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Kg).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),hd=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ab=/^[^\n]+/,xd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Tb=nr(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",xd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Mb=nr(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Kg).getRegex(),Pi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",yd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,kb=nr("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",yd).replace("tag",Pi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Xg=nr(hd).replace("hr",Sa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Pi).getRegex(),Eb=nr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xg).getRegex(),bd={blockquote:Eb,code:Cb,def:Tb,fences:vb,heading:Sb,hr:Sa,html:kb,lheading:Jg,list:Mb,newline:wb,paragraph:Xg,table:wa,text:Ab},qg=nr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Sa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Pi).getRegex(),Lb={...bd,table:qg,paragraph:nr(hd).replace("hr",Sa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",qg).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Pi).getRegex()},Pb={...bd,html:nr(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",yd).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:wa,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:nr(hd).replace("hr",Sa).replace("heading",` *#{1,6} *[^
20
- ]`).replace("lheading",Jg).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Yg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ib=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Qg=/^( {2,}|\\)\n(?!\s*$)/,Rb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Aa="\\p{P}\\p{S}",Wb=nr(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Aa).getRegex(),Hb=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,Bb=nr(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Aa).getRegex(),Db=nr("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Aa).getRegex(),Ob=nr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Aa).getRegex(),_b=nr(/\\([punct])/,"gu").replace(/punct/g,Aa).getRegex(),Nb=nr(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),$b=nr(yd).replace("(?:-->|$)","-->").getRegex(),Fb=nr("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",$b).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Li=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ub=nr(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Li).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zg=nr(/^!?\[(label)\]\[(ref)\]/).replace("label",Li).replace("ref",xd).getRegex(),eh=nr(/^!?\[(ref)\](?:\[\])?/).replace("ref",xd).getRegex(),zb=nr("reflink|nolink(?!\\()","g").replace("reflink",Zg).replace("nolink",eh).getRegex(),wd={_backpedal:wa,anyPunctuation:_b,autolink:Nb,blockSkip:Hb,br:Qg,code:Ib,del:wa,emStrongLDelim:Bb,emStrongRDelimAst:Db,emStrongRDelimUnd:Ob,escape:Yg,link:Ub,nolink:eh,punctuation:Wb,reflink:Zg,reflinkSearch:zb,tag:Fb,text:Rb,url:wa},qb={...wd,link:nr(/^!?\[(label)\]\((.*?)\)/).replace("label",Li).getRegex(),reflink:nr(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Li).getRegex()},fd={...wd,escape:nr(Yg).replace("])","~|])").getRegex(),url:nr(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},jb={...fd,br:nr(Qg).replace("{2,}","*").getRegex(),text:nr(fd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ei={normal:bd,gfm:Lb,pedantic:Pb},ba={normal:wd,gfm:fd,breaks:jb,pedantic:qb},co=class e{constructor(t){Dt(this,"tokens");Dt(this,"options");Dt(this,"state");Dt(this,"tokenizer");Dt(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||rs,this.options.tokenizer=this.options.tokenizer||new Es,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={block:Ei.normal,inline:ba.normal};this.options.pedantic?(r.block=Ei.pedantic,r.inline=ba.pedantic):this.options.gfm&&(r.block=Ei.gfm,this.options.breaks?r.inline=ba.breaks:r.inline=ba.gfm),this.tokenizer.rules=r}static get rules(){return{block:Ei,inline:ba}}static lex(t,r){return new e(r).lex(t)}static lexInline(t,r){return new e(r).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
21
- `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[]){this.options.pedantic?t=t.replace(/\t/g," ").replace(/^ +$/gm,""):t=t.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,s,a;for(;t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},t,r))?(t=t.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(t)){t=t.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=`
22
- `:r.push(n);continue}if(n=this.tokenizer.code(t)){t=t.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
7
+ `)}var Ta=class{constructor(e){Ht(this,"options");Ht(this,"rules");Ht(this,"lexer");this.options=e||ta}space(e){let r=this.rules.block.newline.exec(e);if(r&&r[0].length>0)return{type:"space",raw:r[0]}}code(e){let r=this.rules.block.code.exec(e);if(r){let n=r[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:r[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Si(n,`
8
+ `)}}}fences(e){let r=this.rules.block.fences.exec(e);if(r){let n=r[0],o=Qy(n,r[3]||"");return{type:"code",raw:n,lang:r[2]?r[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):r[2],text:o}}}heading(e){let r=this.rules.block.heading.exec(e);if(r){let n=r[2].trim();if(/#$/.test(n)){let o=Si(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:r[0],depth:r[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let r=this.rules.block.hr.exec(e);if(r)return{type:"hr",raw:r[0]}}blockquote(e){let r=this.rules.block.blockquote.exec(e);if(r){let n=r[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
9
+ $1`);n=Si(n.replace(/^ *>[ \t]?/gm,""),`
10
+ `);let o=this.lexer.state.top;this.lexer.state.top=!0;let s=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:r[0],tokens:s,text:n}}}list(e){let r=this.rules.block.list.exec(e);if(r){let n=r[1].trim(),o=n.length>1,s={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let a=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let p=!1;if(!(r=a.exec(e))||this.rules.block.hr.test(e))break;i=r[0],e=e.substring(i.length);let m=r[2].split(`
11
+ `,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),u=e.split(`
12
+ `,1)[0],f=0;this.options.pedantic?(f=2,d=m.trimStart()):(f=r[2].search(/[^ ]/),f=f>4?1:f,d=m.slice(f),f+=r[1].length);let y=!1;if(!m&&/^ *$/.test(u)&&(i+=u+`
13
+ `,e=e.substring(u.length+1),p=!0),!p){let T=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),S=new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),k=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),x=new RegExp(`^ {0,${Math.min(3,f-1)}}#`);for(;e;){let b=e.split(`
14
+ `,1)[0];if(u=b,this.options.pedantic&&(u=u.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),k.test(u)||x.test(u)||T.test(u)||S.test(e))break;if(u.search(/[^ ]/)>=f||!u.trim())d+=`
15
+ `+u.slice(f);else{if(y||m.search(/[^ ]/)>=4||k.test(m)||x.test(m)||S.test(m))break;d+=`
16
+ `+u}!y&&!u.trim()&&(y=!0),i+=b+`
17
+ `,e=e.substring(b.length+1),m=u.slice(f)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let A=null,E;this.options.gfm&&(A=/^\[[ xX]\] /.exec(d),A&&(E=A[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!A,checked:E,loose:!1,text:d,tokens:[]}),s.raw+=i}s.items[s.items.length-1].raw=i.trimEnd(),s.items[s.items.length-1].text=d.trimEnd(),s.raw=s.raw.trimEnd();for(let p=0;p<s.items.length;p++)if(this.lexer.state.top=!1,s.items[p].tokens=this.lexer.blockTokens(s.items[p].text,[]),!s.loose){let m=s.items[p].tokens.filter(f=>f.type==="space"),u=m.length>0&&m.some(f=>/\n.*\n/.test(f.raw));s.loose=u}if(s.loose)for(let p=0;p<s.items.length;p++)s.items[p].loose=!0;return s}}html(e){let r=this.rules.block.html.exec(e);if(r)return{type:"html",block:!0,raw:r[0],pre:r[1]==="pre"||r[1]==="script"||r[1]==="style",text:r[0]}}def(e){let r=this.rules.block.def.exec(e);if(r){let n=r[1].toLowerCase().replace(/\s+/g," "),o=r[2]?r[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=r[3]?r[3].substring(1,r[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):r[3];return{type:"def",tag:n,raw:r[0],href:o,title:s}}}table(e){let r=this.rules.block.table.exec(e);if(!r||!/[:|]/.test(r[2]))return;let n=Ig(r[1]),o=r[2].replace(/^\||\| *$/g,"").split("|"),s=r[3]&&r[3].trim()?r[3].replace(/\n[ \t]*$/,"").split(`
18
+ `):[],a={type:"table",raw:r[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let i of o)/^ *-+: *$/.test(i)?a.align.push("right"):/^ *:-+: *$/.test(i)?a.align.push("center"):/^ *:-+ *$/.test(i)?a.align.push("left"):a.align.push(null);for(let i of n)a.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of s)a.rows.push(Ig(i,a.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return a}}lheading(e){let r=this.rules.block.lheading.exec(e);if(r)return{type:"heading",raw:r[0],depth:r[2].charAt(0)==="="?1:2,text:r[1],tokens:this.lexer.inline(r[1])}}paragraph(e){let r=this.rules.block.paragraph.exec(e);if(r){let n=r[1].charAt(r[1].length-1)===`
19
+ `?r[1].slice(0,-1):r[1];return{type:"paragraph",raw:r[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let r=this.rules.block.text.exec(e);if(r)return{type:"text",raw:r[0],text:r[0],tokens:this.lexer.inline(r[0])}}escape(e){let r=this.rules.inline.escape.exec(e);if(r)return{type:"escape",raw:r[0],text:gn(r[1])}}tag(e){let r=this.rules.inline.tag.exec(e);if(r)return!this.lexer.state.inLink&&/^<a /i.test(r[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(r[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:r[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:r[0]}}link(e){let r=this.rules.inline.link.exec(e);if(r){let n=r[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let a=Si(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=Jy(r[2],"()");if(a>-1){let d=(r[0].indexOf("!")===0?5:4)+r[1].length+a;r[2]=r[2].substring(0,a),r[0]=r[0].substring(0,d).trim(),r[3]=""}}let o=r[2],s="";if(this.options.pedantic){let a=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);a&&(o=a[1],s=a[3])}else s=r[3]?r[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(n)?o=o.slice(1):o=o.slice(1,-1)),Rg(r,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},r[0],this.lexer)}}reflink(e,r){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(/\s+/g," "),s=r[o.toLowerCase()];if(!s){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return Rg(n,s,n[0],this.lexer)}}emStrong(e,r,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o||o[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(o[1]||o[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let a=[...o[0]].length-1,i,d,l=a,p=0,m=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,r=r.slice(-1*e.length+a);(o=m.exec(r))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&a%3&&!((a+d)%3)){p+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+p);let u=[...o[0]][0].length,f=e.slice(0,a+o.index+u+d);if(Math.min(a,d)%2){let A=f.slice(1,-1);return{type:"em",raw:f,text:A,tokens:this.lexer.inlineTokens(A)}}let y=f.slice(2,-2);return{type:"strong",raw:f,text:y,tokens:this.lexer.inlineTokens(y)}}}}codespan(e){let r=this.rules.inline.code.exec(e);if(r){let n=r[2].replace(/\n/g," "),o=/[^ ]/.test(n),s=/^ /.test(n)&&/ $/.test(n);return o&&s&&(n=n.substring(1,n.length-1)),n=gn(n,!0),{type:"codespan",raw:r[0],text:n}}}br(e){let r=this.rules.inline.br.exec(e);if(r)return{type:"br",raw:r[0]}}del(e){let r=this.rules.inline.del.exec(e);if(r)return{type:"del",raw:r[0],text:r[2],tokens:this.lexer.inlineTokens(r[2])}}autolink(e){let r=this.rules.inline.autolink.exec(e);if(r){let n,o;return r[2]==="@"?(n=gn(r[1]),o="mailto:"+n):(n=gn(r[1]),o=n),{type:"link",raw:r[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,o;let r;if(r=this.rules.inline.url.exec(e)){let s,a;if(r[2]==="@")s=gn(r[0]),a="mailto:"+s;else{let i;do i=r[0],r[0]=(o=(n=this.rules.inline._backpedal.exec(r[0]))==null?void 0:n[0])!=null?o:"";while(i!==r[0]);s=gn(r[0]),r[1]==="www."?a="http://"+r[0]:a=r[0]}return{type:"link",raw:r[0],text:s,href:a,tokens:[{type:"text",raw:s,text:s}]}}}inlineText(e){let r=this.rules.inline.text.exec(e);if(r){let n;return this.lexer.state.inRawBlock?n=r[0]:n=gn(r[0]),{type:"text",raw:r[0],text:n}}}},Yy=/^(?: *(?:\n|$))+/,Zy=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,eb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ws=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,tb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Og=/(?:[*+-]|\d{1,9}[.)])/,_g=or(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Og).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),ld=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,rb=/^[^\n]+/,dd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,nb=or(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",dd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ob=or(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Og).getRegex(),ki="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",cd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ab=or("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",cd).replace("tag",ki).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ng=or(ld).replace("hr",ws).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ki).getRegex(),sb=or(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ng).getRegex(),pd={blockquote:sb,code:Zy,def:nb,fences:eb,heading:tb,hr:ws,html:ab,lheading:_g,list:ob,newline:Yy,paragraph:Ng,table:xs,text:rb},Wg=or("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ws).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ki).getRegex(),ib={...pd,table:Wg,paragraph:or(ld).replace("hr",ws).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Wg).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ki).getRegex()},lb={...pd,html:or(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",cd).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:xs,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:or(ld).replace("hr",ws).replace("heading",` *#{1,6} *[^
20
+ ]`).replace("lheading",_g).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Fg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,db=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,$g=/^( {2,}|\\)\n(?!\s*$)/,cb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vs="\\p{P}\\p{S}",pb=or(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,vs).getRegex(),ub=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,fb=or(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,vs).getRegex(),mb=or("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,vs).getRegex(),gb=or("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,vs).getRegex(),hb=or(/\\([punct])/,"gu").replace(/punct/g,vs).getRegex(),xb=or(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),yb=or(cd).replace("(?:-->|$)","-->").getRegex(),bb=or("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",yb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Mi=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,wb=or(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Mi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ug=or(/^!?\[(label)\]\[(ref)\]/).replace("label",Mi).replace("ref",dd).getRegex(),zg=or(/^!?\[(ref)\](?:\[\])?/).replace("ref",dd).getRegex(),vb=or("reflink|nolink(?!\\()","g").replace("reflink",Ug).replace("nolink",zg).getRegex(),ud={_backpedal:xs,anyPunctuation:hb,autolink:xb,blockSkip:ub,br:$g,code:db,del:xs,emStrongLDelim:fb,emStrongRDelimAst:mb,emStrongRDelimUnd:gb,escape:Fg,link:wb,nolink:zg,punctuation:pb,reflink:Ug,reflinkSearch:vb,tag:bb,text:cb,url:xs},Cb={...ud,link:or(/^!?\[(label)\]\((.*?)\)/).replace("label",Mi).getRegex(),reflink:or(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Mi).getRegex()},ad={...ud,escape:or(Fg).replace("])","~|])").getRegex(),url:or(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Ab={...ad,br:or($g).replace("{2,}","*").getRegex(),text:or(ad.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ti={normal:pd,gfm:ib,pedantic:lb},hs={normal:ud,gfm:ad,breaks:Ab,pedantic:Cb},co=class t{constructor(e){Ht(this,"tokens");Ht(this,"options");Ht(this,"state");Ht(this,"tokenizer");Ht(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ta,this.options.tokenizer=this.options.tokenizer||new Ta,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={block:Ti.normal,inline:hs.normal};this.options.pedantic?(r.block=Ti.pedantic,r.inline=hs.pedantic):this.options.gfm&&(r.block=Ti.gfm,this.options.breaks?r.inline=hs.breaks:r.inline=hs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Ti,inline:hs}}static lex(e,r){return new t(r).lex(e)}static lexInline(e,r){return new t(r).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
21
+ `),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,s,a;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=`
22
+ `:r.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
23
23
  `+n.raw,o.text+=`
24
- `+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(n=this.tokenizer.fences(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.heading(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.hr(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.blockquote(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.list(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.html(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.def(t)){t=t.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
24
+ `+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.list(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.html(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.def(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
25
25
  `+n.raw,o.text+=`
26
- `+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.lheading(t)){t=t.substring(n.raw.length),r.push(n);continue}if(s=t,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=t.slice(1),l;this.options.extensions.startBlock.forEach(p=>{l=p.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(s=t.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(s))){o=r[r.length-1],a&&o.type==="paragraph"?(o.raw+=`
26
+ `+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.lheading(e)){e=e.substring(n.raw.length),r.push(n);continue}if(s=e,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=e.slice(1),l;this.options.extensions.startBlock.forEach(p=>{l=p.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(s=e.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(s))){o=r[r.length-1],a&&o.type==="paragraph"?(o.raw+=`
27
27
  `+n.raw,o.text+=`
28
- `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n),a=s.length!==t.length,t=t.substring(n.raw.length);continue}if(n=this.tokenizer.text(t)){t=t.substring(n.raw.length),o=r[r.length-1],o&&o.type==="text"?(o.raw+=`
28
+ `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n),a=s.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&o.type==="text"?(o.raw+=`
29
29
  `+n.raw,o.text+=`
30
- `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(t){let i="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}inlineTokens(t,r=[]){let n,o,s,a=t,i,d,l;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;t;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(p=>(n=p.call({lexer:this},t,r))?(t=t.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.escape(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.tag(t)){t=t.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.link(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.emStrong(t,a,l)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.codespan(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.br(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.del(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.autolink(t)){t=t.substring(n.raw.length),r.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(t))){t=t.substring(n.raw.length),r.push(n);continue}if(s=t,this.options.extensions&&this.options.extensions.startInline){let p=1/0,u=t.slice(1),f;this.options.extensions.startInline.forEach(m=>{f=m.call({lexer:this},u),typeof f=="number"&&f>=0&&(p=Math.min(p,f))}),p<1/0&&p>=0&&(s=t.substring(0,p+1))}if(n=this.tokenizer.inlineText(s)){t=t.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=r[r.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(t){let p="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return r}},Ls=class{constructor(t){Dt(this,"options");this.options=t||rs}code(t,r,n){var s;let o=(s=(r||"").match(/^\S*/))==null?void 0:s[0];return t=t.replace(/\n$/,"")+`
31
- `,o?'<pre><code class="language-'+gn(o)+'">'+(n?t:gn(t,!0))+`</code></pre>
32
- `:"<pre><code>"+(n?t:gn(t,!0))+`</code></pre>
33
- `}blockquote(t){return`<blockquote>
34
- ${t}</blockquote>
35
- `}html(t,r){return t}heading(t,r,n){return`<h${r}>${t}</h${r}>
30
+ `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){let n,o,s,a=e,i,d,l;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(p=>(n=p.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.emStrong(e,a,l)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.del(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),r.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),r.push(n);continue}if(s=e,this.options.extensions&&this.options.extensions.startInline){let p=1/0,m=e.slice(1),u;this.options.extensions.startInline.forEach(f=>{u=f.call({lexer:this},m),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(s=e.substring(0,p+1))}if(n=this.tokenizer.inlineText(s)){e=e.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=r[r.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return r}},Ma=class{constructor(e){Ht(this,"options");this.options=e||ta}code(e,r,n){var s;let o=(s=(r||"").match(/^\S*/))==null?void 0:s[0];return e=e.replace(/\n$/,"")+`
31
+ `,o?'<pre><code class="language-'+gn(o)+'">'+(n?e:gn(e,!0))+`</code></pre>
32
+ `:"<pre><code>"+(n?e:gn(e,!0))+`</code></pre>
33
+ `}blockquote(e){return`<blockquote>
34
+ ${e}</blockquote>
35
+ `}html(e,r){return e}heading(e,r,n){return`<h${r}>${e}</h${r}>
36
36
  `}hr(){return`<hr>
37
- `}list(t,r,n){let o=r?"ol":"ul",s=r&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
38
- `+t+"</"+o+`>
39
- `}listitem(t,r,n){return`<li>${t}</li>
40
- `}checkbox(t){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(t){return`<p>${t}</p>
41
- `}table(t,r){return r&&(r=`<tbody>${r}</tbody>`),`<table>
37
+ `}list(e,r,n){let o=r?"ol":"ul",s=r&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
38
+ `+e+"</"+o+`>
39
+ `}listitem(e,r,n){return`<li>${e}</li>
40
+ `}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>
41
+ `}table(e,r){return r&&(r=`<tbody>${r}</tbody>`),`<table>
42
42
  <thead>
43
- `+t+`</thead>
43
+ `+e+`</thead>
44
44
  `+r+`</table>
45
- `}tablerow(t){return`<tr>
46
- ${t}</tr>
47
- `}tablecell(t,r){let n=r.header?"th":"td";return(r.align?`<${n} align="${r.align}">`:`<${n}>`)+t+`</${n}>
48
- `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return"<br>"}del(t){return`<del>${t}</del>`}link(t,r,n){let o=Fg(t);if(o===null)return n;t=o;let s='<a href="'+t+'"';return r&&(s+=' title="'+r+'"'),s+=">"+n+"</a>",s}image(t,r,n){let o=Fg(t);if(o===null)return n;t=o;let s=`<img src="${t}" alt="${n}"`;return r&&(s+=` title="${r}"`),s+=">",s}text(t){return t}},Ca=class{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,r,n){return""+n}image(t,r,n){return""+n}br(){return""}},po=class e{constructor(t){Dt(this,"options");Dt(this,"renderer");Dt(this,"textRenderer");this.options=t||rs,this.options.renderer=this.options.renderer||new Ls,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ca}static parse(t,r){return new e(r).parse(t)}static parseInline(t,r){return new e(r).parseInline(t)}parse(t,r=!0){let n="";for(let o=0;o<t.length;o++){let s=t[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=s,i=this.options.extensions.renderers[a.type].call({parser:this},a);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(a.type)){n+=i||"";continue}}switch(s.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let a=s;n+=this.renderer.heading(this.parseInline(a.tokens),a.depth,hb(this.parseInline(a.tokens,this.textRenderer)));continue}case"code":{let a=s;n+=this.renderer.code(a.text,a.lang,!!a.escaped);continue}case"table":{let a=s,i="",d="";for(let p=0;p<a.header.length;p++)d+=this.renderer.tablecell(this.parseInline(a.header[p].tokens),{header:!0,align:a.align[p]});i+=this.renderer.tablerow(d);let l="";for(let p=0;p<a.rows.length;p++){let u=a.rows[p];d="";for(let f=0;f<u.length;f++)d+=this.renderer.tablecell(this.parseInline(u[f].tokens),{header:!1,align:a.align[f]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let a=s,i=this.parse(a.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let a=s,i=a.ordered,d=a.start,l=a.loose,p="";for(let u=0;u<a.items.length;u++){let f=a.items[u],m=f.checked,y=f.task,v="";if(f.task){let E=this.renderer.checkbox(!!m);l?f.tokens.length>0&&f.tokens[0].type==="paragraph"?(f.tokens[0].text=E+" "+f.tokens[0].text,f.tokens[0].tokens&&f.tokens[0].tokens.length>0&&f.tokens[0].tokens[0].type==="text"&&(f.tokens[0].tokens[0].text=E+" "+f.tokens[0].tokens[0].text)):f.tokens.unshift({type:"text",text:E+" "}):v+=E+" "}v+=this.parse(f.tokens,l),p+=this.renderer.listitem(v,y,!!m)}n+=this.renderer.list(p,i,d);continue}case"html":{let a=s;n+=this.renderer.html(a.text,a.block);continue}case"paragraph":{let a=s;n+=this.renderer.paragraph(this.parseInline(a.tokens));continue}case"text":{let a=s,i=a.tokens?this.parseInline(a.tokens):a.text;for(;o+1<t.length&&t[o+1].type==="text";)a=t[++o],i+=`
49
- `+(a.tokens?this.parseInline(a.tokens):a.text);n+=r?this.renderer.paragraph(i):i;continue}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(t,r){r=r||this.renderer;let n="";for(let o=0;o<t.length;o++){let s=t[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){n+=a||"";continue}}switch(s.type){case"escape":{let a=s;n+=r.text(a.text);break}case"html":{let a=s;n+=r.html(a.text);break}case"link":{let a=s;n+=r.link(a.href,a.title,this.parseInline(a.tokens,r));break}case"image":{let a=s;n+=r.image(a.href,a.title,a.text);break}case"strong":{let a=s;n+=r.strong(this.parseInline(a.tokens,r));break}case"em":{let a=s;n+=r.em(this.parseInline(a.tokens,r));break}case"codespan":{let a=s;n+=r.codespan(a.text);break}case"br":{n+=r.br();break}case"del":{let a=s;n+=r.del(this.parseInline(a.tokens,r));break}case"text":{let a=s;n+=r.text(a.text);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}},Zo=class{constructor(t){Dt(this,"options");this.options=t||rs}preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}};Dt(Zo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var ts,md,th,va=class{constructor(...t){Ng(this,ts);Dt(this,"defaults",gd());Dt(this,"options",this.setOptions);Dt(this,"parse",Mi(this,ts,md).call(this,co.lex,po.parse));Dt(this,"parseInline",Mi(this,ts,md).call(this,co.lexInline,po.parseInline));Dt(this,"Parser",po);Dt(this,"Renderer",Ls);Dt(this,"TextRenderer",Ca);Dt(this,"Lexer",co);Dt(this,"Tokenizer",Es);Dt(this,"Hooks",Zo);this.use(...t)}walkTokens(t,r){var o,s;let n=[];for(let a of t)switch(n=n.concat(r.call(this,a)),a.type){case"table":{let i=a;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,r));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,r));break}case"list":{let i=a;n=n.concat(this.walkTokens(i.items,r));break}default:{let i=a;(s=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&s[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,r))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,r)))}}return n}use(...t){let r=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let a=r.renderers[s.name];a?r.renderers[s.name]=function(...i){let d=s.renderer.apply(this,i);return d===!1&&(d=a.apply(this,i)),d}:r.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=r[s.level];a?a.unshift(s.tokenizer):r[s.level]=[s.tokenizer],s.start&&(s.level==="block"?r.startBlock?r.startBlock.push(s.start):r.startBlock=[s.start]:s.level==="inline"&&(r.startInline?r.startInline.push(s.start):r.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(r.childTokens[s.name]=s.childTokens)}),o.extensions=r),n.renderer){let s=this.defaults.renderer||new Ls(this.defaults);for(let a in n.renderer){if(!(a in s))throw new Error(`renderer '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.renderer[i],l=s[i];s[i]=(...p)=>{let u=d.apply(s,p);return u===!1&&(u=l.apply(s,p)),u||""}}o.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Es(this.defaults);for(let a in n.tokenizer){if(!(a in s))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let i=a,d=n.tokenizer[i],l=s[i];s[i]=(...p)=>{let u=d.apply(s,p);return u===!1&&(u=l.apply(s,p)),u}}o.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new Zo;for(let a in n.hooks){if(!(a in s))throw new Error(`hook '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.hooks[i],l=s[i];Zo.passThroughHooks.has(a)?s[i]=p=>{if(this.defaults.async)return Promise.resolve(d.call(s,p)).then(f=>l.call(s,f));let u=d.call(s,p);return l.call(s,u)}:s[i]=(...p)=>{let u=d.apply(s,p);return u===!1&&(u=l.apply(s,p)),u}}o.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,a=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(a.call(this,i)),s&&(d=d.concat(s.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,r){return co.lex(t,r!=null?r:this.defaults)}parser(t,r){return po.parse(t,r!=null?r:this.defaults)}};ts=new WeakSet,md=function(t,r){return(n,o)=>{let s={...o},a={...this.defaults,...s};this.defaults.async===!0&&s.async===!1&&(a.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),a.async=!0);let i=Mi(this,ts,th).call(this,!!a.silent,!!a.async);if(typeof n=="undefined"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(a.hooks&&(a.hooks.options=a),a.async)return Promise.resolve(a.hooks?a.hooks.preprocess(n):n).then(d=>t(d,a)).then(d=>a.hooks?a.hooks.processAllTokens(d):d).then(d=>a.walkTokens?Promise.all(this.walkTokens(d,a.walkTokens)).then(()=>d):d).then(d=>r(d,a)).then(d=>a.hooks?a.hooks.postprocess(d):d).catch(i);try{a.hooks&&(n=a.hooks.preprocess(n));let d=t(n,a);a.hooks&&(d=a.hooks.processAllTokens(d)),a.walkTokens&&this.walkTokens(d,a.walkTokens);let l=r(d,a);return a.hooks&&(l=a.hooks.postprocess(l)),l}catch(d){return i(d)}}},th=function(t,r){return n=>{if(n.message+=`
50
- Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error occurred:</p><pre>"+gn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var es=new va;function rr(e,t){return es.parse(e,t)}rr.options=rr.setOptions=function(e){return es.setOptions(e),rr.defaults=es.defaults,jg(rr.defaults),rr};rr.getDefaults=gd;rr.defaults=rs;rr.use=function(...e){return es.use(...e),rr.defaults=es.defaults,jg(rr.defaults),rr};rr.walkTokens=function(e,t){return es.walkTokens(e,t)};rr.parseInline=es.parseInline;rr.Parser=po;rr.parser=po.parse;rr.Renderer=Ls;rr.TextRenderer=Ca;rr.Lexer=co;rr.lexer=co.lex;rr.Tokenizer=Es;rr.Hooks=Zo;rr.parse=rr;var $S=rr.options,FS=rr.setOptions,US=rr.use,zS=rr.walkTokens,qS=rr.parseInline;var jS=po.parse,VS=co.lex;var Vb=e=>{if(e)return e},Ta=e=>{var o,s;let t=e==null?void 0:e.markedOptions,r=new va({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),n=Vb(e==null?void 0:e.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},ns=e=>e?Ta({markedOptions:e.options,renderer:e.renderer}):Ta(),Gb=Ta(),Cd=e=>Gb(e),os=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),nh=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),rh=e=>`%%FORM_PLACEHOLDER_${e}%%`,oh=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=rh(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return n}return n}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let s=rh(t.length);return t.push({token:s,type:o}),s}),r},sh=e=>{let t=ns(e);return r=>{let n=[],o=oh(r,n),s=t(o);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${nh(i)}"></div>`;s=s.replace(d,p)}),s}},ah=e=>{let t=[],r=oh(e,t),n=Cd(r);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${nh(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:gh,setPrototypeOf:ih,isFrozen:Kb,getPrototypeOf:Jb,getOwnPropertyDescriptor:Xb}=Object,{freeze:Yr,seal:Mn,create:Wi}=Object,{apply:Ed,construct:Ld}=typeof Reflect!="undefined"&&Reflect;Yr||(Yr=function(t){return t});Mn||(Mn=function(t){return t});Ed||(Ed=function(t,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return t.apply(r,o)});Ld||(Ld=function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return new t(...n)});var Ii=Qr(Array.prototype.forEach),Yb=Qr(Array.prototype.lastIndexOf),lh=Qr(Array.prototype.pop),Ma=Qr(Array.prototype.push),Qb=Qr(Array.prototype.splice),Hi=Qr(String.prototype.toLowerCase),vd=Qr(String.prototype.toString),Sd=Qr(String.prototype.match),ka=Qr(String.prototype.replace),Zb=Qr(String.prototype.indexOf),e0=Qr(String.prototype.trim),hn=Qr(Object.prototype.hasOwnProperty),Xr=Qr(RegExp.prototype.test),Ea=t0(TypeError);function Qr(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return Ed(e,t,n)}}function t0(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return Ld(e,r)}}function Rt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hi;ih&&ih(e,null);let n=t.length;for(;n--;){let o=t[n];if(typeof o=="string"){let s=r(o);s!==o&&(Kb(t)||(t[n]=s),o=s)}e[o]=!0}return e}function r0(e){for(let t=0;t<e.length;t++)hn(e,t)||(e[t]=null);return e}function Kn(e){let t=Wi(null);for(let[r,n]of gh(e))hn(e,r)&&(Array.isArray(n)?t[r]=r0(n):n&&typeof n=="object"&&n.constructor===Object?t[r]=Kn(n):t[r]=n);return t}function La(e,t){for(;e!==null;){let n=Xb(e,t);if(n){if(n.get)return Qr(n.get);if(typeof n.value=="function")return Qr(n.value)}e=Jb(e)}function r(){return null}return r}var dh=Yr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ad=Yr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Td=Yr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),n0=Yr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Md=Yr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),o0=Yr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ch=Yr(["#text"]),ph=Yr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),kd=Yr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),uh=Yr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ri=Yr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),s0=Mn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),a0=Mn(/<%[\w\W]*|[\w\W]*%>/gm),i0=Mn(/\$\{[\w\W]*/gm),l0=Mn(/^data-[\-\w.\u00B7-\uFFFF]+$/),d0=Mn(/^aria-[\-\w]+$/),hh=Mn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),c0=Mn(/^(?:\w+script|data):/i),p0=Mn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xh=Mn(/^html$/i),u0=Mn(/^[a-z][.\w]*(-[.\w]+)+$/i),fh=Object.freeze({__proto__:null,ARIA_ATTR:d0,ATTR_WHITESPACE:p0,CUSTOM_ELEMENT:u0,DATA_ATTR:l0,DOCTYPE_NAME:xh,ERB_EXPR:a0,IS_ALLOWED_URI:hh,IS_SCRIPT_OR_DATA:c0,MUSTACHE_EXPR:s0,TMPLIT_EXPR:i0}),Pa={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},f0=function(){return typeof window=="undefined"?null:window},m0=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(n=r.getAttribute(o));let s="dompurify"+(n?"#"+n:"");try{return t.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},mh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function yh(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:f0(),t=me=>yh(me);if(t.version="3.3.3",t.removed=[],!e||!e.document||e.document.nodeType!==Pa.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e,n=r,o=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:f,trustedTypes:m}=e,y=d.prototype,v=La(y,"cloneNode"),E=La(y,"remove"),T=La(y,"nextSibling"),A=La(y,"childNodes"),M=La(y,"parentNode");if(typeof a=="function"){let me=r.createElement("template");me.content&&me.content.ownerDocument&&(r=me.content.ownerDocument)}let b,w="",{implementation:h,createNodeIterator:k,createDocumentFragment:B,getElementsByTagName:H}=r,{importNode:W}=n,N=mh();t.isSupported=typeof gh=="function"&&typeof M=="function"&&h&&h.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:q,ERB_EXPR:se,TMPLIT_EXPR:ve,DATA_ATTR:Ue,ARIA_ATTR:je,IS_SCRIPT_OR_DATA:we,ATTR_WHITESPACE:Te,CUSTOM_ELEMENT:We}=fh,{IS_ALLOWED_URI:Oe}=fh,K=null,He=Rt({},[...dh,...Ad,...Td,...Md,...ch]),j=null,Ce=Rt({},[...ph,...kd,...uh,...Ri]),Z=Object.seal(Wi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),he=null,xe=null,Ve=Object.seal(Wi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),G=!0,ee=!0,Ie=!1,ye=!0,pe=!1,le=!0,Ye=!1,Me=!1,be=!1,J=!1,Ke=!1,ne=!1,Y=!0,Q=!1,Be="user-content-",ke=!0,ge=!1,ue={},_e=null,I=Rt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),te=null,qe=Rt({},["audio","video","img","source","image","track"]),tt=null,Xe=Rt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Je="http://www.w3.org/1998/Math/MathML",pt="http://www.w3.org/2000/svg",ht="http://www.w3.org/1999/xhtml",zt=ht,or=!1,X=null,kt=Rt({},[Je,pt,ht],vd),ct=Rt({},["mi","mo","mn","ms","mtext"]),Jt=Rt({},["annotation-xml"]),fe=Rt({},["title","style","font","a","script"]),Se=null,Wt=["application/xhtml+xml","text/html"],sr="text/html",Et=null,gr=null,_t=r.createElement("form"),Ht=function(P){return P instanceof RegExp||P instanceof Function},Tt=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(gr&&gr===P)){if((!P||typeof P!="object")&&(P={}),P=Kn(P),Se=Wt.indexOf(P.PARSER_MEDIA_TYPE)===-1?sr:P.PARSER_MEDIA_TYPE,Et=Se==="application/xhtml+xml"?vd:Hi,K=hn(P,"ALLOWED_TAGS")?Rt({},P.ALLOWED_TAGS,Et):He,j=hn(P,"ALLOWED_ATTR")?Rt({},P.ALLOWED_ATTR,Et):Ce,X=hn(P,"ALLOWED_NAMESPACES")?Rt({},P.ALLOWED_NAMESPACES,vd):kt,tt=hn(P,"ADD_URI_SAFE_ATTR")?Rt(Kn(Xe),P.ADD_URI_SAFE_ATTR,Et):Xe,te=hn(P,"ADD_DATA_URI_TAGS")?Rt(Kn(qe),P.ADD_DATA_URI_TAGS,Et):qe,_e=hn(P,"FORBID_CONTENTS")?Rt({},P.FORBID_CONTENTS,Et):I,he=hn(P,"FORBID_TAGS")?Rt({},P.FORBID_TAGS,Et):Kn({}),xe=hn(P,"FORBID_ATTR")?Rt({},P.FORBID_ATTR,Et):Kn({}),ue=hn(P,"USE_PROFILES")?P.USE_PROFILES:!1,G=P.ALLOW_ARIA_ATTR!==!1,ee=P.ALLOW_DATA_ATTR!==!1,Ie=P.ALLOW_UNKNOWN_PROTOCOLS||!1,ye=P.ALLOW_SELF_CLOSE_IN_ATTR!==!1,pe=P.SAFE_FOR_TEMPLATES||!1,le=P.SAFE_FOR_XML!==!1,Ye=P.WHOLE_DOCUMENT||!1,J=P.RETURN_DOM||!1,Ke=P.RETURN_DOM_FRAGMENT||!1,ne=P.RETURN_TRUSTED_TYPE||!1,be=P.FORCE_BODY||!1,Y=P.SANITIZE_DOM!==!1,Q=P.SANITIZE_NAMED_PROPS||!1,ke=P.KEEP_CONTENT!==!1,ge=P.IN_PLACE||!1,Oe=P.ALLOWED_URI_REGEXP||hh,zt=P.NAMESPACE||ht,ct=P.MATHML_TEXT_INTEGRATION_POINTS||ct,Jt=P.HTML_INTEGRATION_POINTS||Jt,Z=P.CUSTOM_ELEMENT_HANDLING||{},P.CUSTOM_ELEMENT_HANDLING&&Ht(P.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=P.CUSTOM_ELEMENT_HANDLING.tagNameCheck),P.CUSTOM_ELEMENT_HANDLING&&Ht(P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),P.CUSTOM_ELEMENT_HANDLING&&typeof P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),pe&&(ee=!1),Ke&&(J=!0),ue&&(K=Rt({},ch),j=Wi(null),ue.html===!0&&(Rt(K,dh),Rt(j,ph)),ue.svg===!0&&(Rt(K,Ad),Rt(j,kd),Rt(j,Ri)),ue.svgFilters===!0&&(Rt(K,Td),Rt(j,kd),Rt(j,Ri)),ue.mathMl===!0&&(Rt(K,Md),Rt(j,uh),Rt(j,Ri))),hn(P,"ADD_TAGS")||(Ve.tagCheck=null),hn(P,"ADD_ATTR")||(Ve.attributeCheck=null),P.ADD_TAGS&&(typeof P.ADD_TAGS=="function"?Ve.tagCheck=P.ADD_TAGS:(K===He&&(K=Kn(K)),Rt(K,P.ADD_TAGS,Et))),P.ADD_ATTR&&(typeof P.ADD_ATTR=="function"?Ve.attributeCheck=P.ADD_ATTR:(j===Ce&&(j=Kn(j)),Rt(j,P.ADD_ATTR,Et))),P.ADD_URI_SAFE_ATTR&&Rt(tt,P.ADD_URI_SAFE_ATTR,Et),P.FORBID_CONTENTS&&(_e===I&&(_e=Kn(_e)),Rt(_e,P.FORBID_CONTENTS,Et)),P.ADD_FORBID_CONTENTS&&(_e===I&&(_e=Kn(_e)),Rt(_e,P.ADD_FORBID_CONTENTS,Et)),ke&&(K["#text"]=!0),Ye&&Rt(K,["html","head","body"]),K.table&&(Rt(K,["tbody"]),delete he.tbody),P.TRUSTED_TYPES_POLICY){if(typeof P.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ea('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof P.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ea('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=P.TRUSTED_TYPES_POLICY,w=b.createHTML("")}else b===void 0&&(b=m0(m,o)),b!==null&&typeof w=="string"&&(w=b.createHTML(""));Yr&&Yr(P),gr=P}},Lt=Rt({},[...Ad,...Td,...n0]),ar=Rt({},[...Md,...o0]),mt=function(P){let oe=M(P);(!oe||!oe.tagName)&&(oe={namespaceURI:zt,tagName:"template"});let Ee=Hi(P.tagName),rt=Hi(oe.tagName);return X[P.namespaceURI]?P.namespaceURI===pt?oe.namespaceURI===ht?Ee==="svg":oe.namespaceURI===Je?Ee==="svg"&&(rt==="annotation-xml"||ct[rt]):!!Lt[Ee]:P.namespaceURI===Je?oe.namespaceURI===ht?Ee==="math":oe.namespaceURI===pt?Ee==="math"&&Jt[rt]:!!ar[Ee]:P.namespaceURI===ht?oe.namespaceURI===pt&&!Jt[rt]||oe.namespaceURI===Je&&!ct[rt]?!1:!ar[Ee]&&(fe[Ee]||!Lt[Ee]):!!(Se==="application/xhtml+xml"&&X[P.namespaceURI]):!1},cr=function(P){Ma(t.removed,{element:P});try{M(P).removeChild(P)}catch{E(P)}},Cr=function(P,oe){try{Ma(t.removed,{attribute:oe.getAttributeNode(P),from:oe})}catch{Ma(t.removed,{attribute:null,from:oe})}if(oe.removeAttribute(P),P==="is")if(J||Ke)try{cr(oe)}catch{}else try{oe.setAttribute(P,"")}catch{}},Lr=function(P){let oe=null,Ee=null;if(be)P="<remove></remove>"+P;else{let $t=Sd(P,/^[\r\n\t ]+/);Ee=$t&&$t[0]}Se==="application/xhtml+xml"&&zt===ht&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");let rt=b?b.createHTML(P):P;if(zt===ht)try{oe=new f().parseFromString(rt,Se)}catch{}if(!oe||!oe.documentElement){oe=h.createDocument(zt,"template",null);try{oe.documentElement.innerHTML=or?w:rt}catch{}}let Xt=oe.body||oe.documentElement;return P&&Ee&&Xt.insertBefore(r.createTextNode(Ee),Xt.childNodes[0]||null),zt===ht?H.call(oe,Ye?"html":"body")[0]:Ye?oe.documentElement:Xt},_r=function(P){return k.call(P.ownerDocument||P,P,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},xt=function(P){return P instanceof u&&(typeof P.nodeName!="string"||typeof P.textContent!="string"||typeof P.removeChild!="function"||!(P.attributes instanceof p)||typeof P.removeAttribute!="function"||typeof P.setAttribute!="function"||typeof P.namespaceURI!="string"||typeof P.insertBefore!="function"||typeof P.hasChildNodes!="function")},an=function(P){return typeof i=="function"&&P instanceof i};function mr(me,P,oe){Ii(me,Ee=>{Ee.call(t,P,oe,gr)})}let Un=function(P){let oe=null;if(mr(N.beforeSanitizeElements,P,null),xt(P))return cr(P),!0;let Ee=Et(P.nodeName);if(mr(N.uponSanitizeElement,P,{tagName:Ee,allowedTags:K}),le&&P.hasChildNodes()&&!an(P.firstElementChild)&&Xr(/<[/\w!]/g,P.innerHTML)&&Xr(/<[/\w!]/g,P.textContent)||P.nodeType===Pa.progressingInstruction||le&&P.nodeType===Pa.comment&&Xr(/<[/\w]/g,P.data))return cr(P),!0;if(!(Ve.tagCheck instanceof Function&&Ve.tagCheck(Ee))&&(!K[Ee]||he[Ee])){if(!he[Ee]&&Zn(Ee)&&(Z.tagNameCheck instanceof RegExp&&Xr(Z.tagNameCheck,Ee)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Ee)))return!1;if(ke&&!_e[Ee]){let rt=M(P)||P.parentNode,Xt=A(P)||P.childNodes;if(Xt&&rt){let $t=Xt.length;for(let er=$t-1;er>=0;--er){let Pr=v(Xt[er],!0);Pr.__removalCount=(P.__removalCount||0)+1,rt.insertBefore(Pr,T(P))}}}return cr(P),!0}return P instanceof d&&!mt(P)||(Ee==="noscript"||Ee==="noembed"||Ee==="noframes")&&Xr(/<\/no(script|embed|frames)/i,P.innerHTML)?(cr(P),!0):(pe&&P.nodeType===Pa.text&&(oe=P.textContent,Ii([q,se,ve],rt=>{oe=ka(oe,rt," ")}),P.textContent!==oe&&(Ma(t.removed,{element:P.cloneNode()}),P.textContent=oe)),mr(N.afterSanitizeElements,P,null),!1)},Rr=function(P,oe,Ee){if(xe[oe]||Y&&(oe==="id"||oe==="name")&&(Ee in r||Ee in _t))return!1;if(!(ee&&!xe[oe]&&Xr(Ue,oe))){if(!(G&&Xr(je,oe))){if(!(Ve.attributeCheck instanceof Function&&Ve.attributeCheck(oe,P))){if(!j[oe]||xe[oe]){if(!(Zn(P)&&(Z.tagNameCheck instanceof RegExp&&Xr(Z.tagNameCheck,P)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(P))&&(Z.attributeNameCheck instanceof RegExp&&Xr(Z.attributeNameCheck,oe)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(oe,P))||oe==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&Xr(Z.tagNameCheck,Ee)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Ee))))return!1}else if(!tt[oe]){if(!Xr(Oe,ka(Ee,Te,""))){if(!((oe==="src"||oe==="xlink:href"||oe==="href")&&P!=="script"&&Zb(Ee,"data:")===0&&te[P])){if(!(Ie&&!Xr(we,ka(Ee,Te,"")))){if(Ee)return!1}}}}}}}return!0},Zn=function(P){return P!=="annotation-xml"&&Sd(P,We)},Pn=function(P){mr(N.beforeSanitizeAttributes,P,null);let{attributes:oe}=P;if(!oe||xt(P))return;let Ee={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:j,forceKeepAttr:void 0},rt=oe.length;for(;rt--;){let Xt=oe[rt],{name:$t,namespaceURI:er,value:Pr}=Xt,Nr=Et($t),wn=Pr,Vt=$t==="value"?wn:e0(wn);if(Ee.attrName=Nr,Ee.attrValue=Vt,Ee.keepAttr=!0,Ee.forceKeepAttr=void 0,mr(N.uponSanitizeAttribute,P,Ee),Vt=Ee.attrValue,Q&&(Nr==="id"||Nr==="name")&&(Cr($t,P),Vt=Be+Vt),le&&Xr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){Cr($t,P);continue}if(Nr==="attributename"&&Sd(Vt,"href")){Cr($t,P);continue}if(Ee.forceKeepAttr)continue;if(!Ee.keepAttr){Cr($t,P);continue}if(!ye&&Xr(/\/>/i,Vt)){Cr($t,P);continue}pe&&Ii([q,se,ve],Ir=>{Vt=ka(Vt,Ir," ")});let Ft=Et(P.nodeName);if(!Rr(Ft,Nr,Vt)){Cr($t,P);continue}if(b&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!er)switch(m.getAttributeType(Ft,Nr)){case"TrustedHTML":{Vt=b.createHTML(Vt);break}case"TrustedScriptURL":{Vt=b.createScriptURL(Vt);break}}if(Vt!==wn)try{er?P.setAttributeNS(er,$t,Vt):P.setAttribute($t,Vt),xt(P)?cr(P):lh(t.removed)}catch{Cr($t,P)}}mr(N.afterSanitizeAttributes,P,null)},In=function me(P){let oe=null,Ee=_r(P);for(mr(N.beforeSanitizeShadowDOM,P,null);oe=Ee.nextNode();)mr(N.uponSanitizeShadowNode,oe,null),Un(oe),Pn(oe),oe.content instanceof s&&me(oe.content);mr(N.afterSanitizeShadowDOM,P,null)};return t.sanitize=function(me){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=null,Ee=null,rt=null,Xt=null;if(or=!me,or&&(me="<!-->"),typeof me!="string"&&!an(me))if(typeof me.toString=="function"){if(me=me.toString(),typeof me!="string")throw Ea("dirty is not a string, aborting")}else throw Ea("toString is not a function");if(!t.isSupported)return me;if(Me||Tt(P),t.removed=[],typeof me=="string"&&(ge=!1),ge){if(me.nodeName){let Pr=Et(me.nodeName);if(!K[Pr]||he[Pr])throw Ea("root node is forbidden and cannot be sanitized in-place")}}else if(me instanceof i)oe=Lr("<!---->"),Ee=oe.ownerDocument.importNode(me,!0),Ee.nodeType===Pa.element&&Ee.nodeName==="BODY"||Ee.nodeName==="HTML"?oe=Ee:oe.appendChild(Ee);else{if(!J&&!pe&&!Ye&&me.indexOf("<")===-1)return b&&ne?b.createHTML(me):me;if(oe=Lr(me),!oe)return J?null:ne?w:""}oe&&be&&cr(oe.firstChild);let $t=_r(ge?me:oe);for(;rt=$t.nextNode();)Un(rt),Pn(rt),rt.content instanceof s&&In(rt.content);if(ge)return me;if(J){if(Ke)for(Xt=B.call(oe.ownerDocument);oe.firstChild;)Xt.appendChild(oe.firstChild);else Xt=oe;return(j.shadowroot||j.shadowrootmode)&&(Xt=W.call(n,Xt,!0)),Xt}let er=Ye?oe.outerHTML:oe.innerHTML;return Ye&&K["!doctype"]&&oe.ownerDocument&&oe.ownerDocument.doctype&&oe.ownerDocument.doctype.name&&Xr(xh,oe.ownerDocument.doctype.name)&&(er="<!DOCTYPE "+oe.ownerDocument.doctype.name+`>
51
- `+er),pe&&Ii([q,se,ve],Pr=>{er=ka(er,Pr," ")}),b&&ne?b.createHTML(er):er},t.setConfig=function(){let me=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Tt(me),Me=!0},t.clearConfig=function(){gr=null,Me=!1},t.isValidAttribute=function(me,P,oe){gr||Tt({});let Ee=Et(me),rt=Et(P);return Rr(Ee,rt,oe)},t.addHook=function(me,P){typeof P=="function"&&Ma(N[me],P)},t.removeHook=function(me,P){if(P!==void 0){let oe=Yb(N[me],P);return oe===-1?void 0:Qb(N[me],oe,1)[0]}return lh(N[me])},t.removeHooks=function(me){N[me]=[]},t.removeAllHooks=function(){N=mh()},t}var bh=yh();var g0={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},h0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pd=()=>{let e=bh(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,r)=>{if(r.attrName==="src"||r.attrName==="href"){let n=r.attrValue;n.toLowerCase().startsWith("data:")&&!h0.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),t=>e.sanitize(t,g0)},Ps=e=>e===!1?null:typeof e=="function"?e:Pd();var Ia="webmcp:",Ui={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function $h(e){if(e.length===0)return"0:empty";let t=e.map(r=>{var n,o;return[r.name,(n=r.description)!=null?n:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(o=r.origin)!=null?o:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${e.length}:${gw(t.join(""))}`}function Nh(e,t){let r=3735928559^t,n=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);r=Math.imul(r^s,2654435761),n=Math.imul(n^s,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}function gw(e){let t=Nh(e,0).toString(36),r=Nh(e,2654435761).toString(36);return`${t}.${r}`}var Ws=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let r;try{r=await t.getTools()}catch(o){return Ui.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}let n=typeof location!="undefined"?location.origin:"";return r.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...n?{pageOrigin:n}:{}},a=xw(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,r,n){if(await this.ensureReady(),this.config.enabled!==!0)return $n("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let m=typeof document!="undefined"&&!!document.modelContext;return $n(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=_d(t),a;try{a=await o.getTools()}catch(m){let y=m instanceof Error?m.message:String(m);return $n(`Failed to read WebMCP registry: ${y}`)}let i=a.find(m=>m.name===s);if(!i)return $n(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return $n(`WebMCP tool not allowed by client allowlist: ${s}`);if(n!=null&&n.aborted)return $n("Aborted by cancel()");let d={toolName:s,args:r,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return $n("User declined the tool call.");if(n!=null&&n.aborted)return $n("Aborted by cancel()");let l=new AbortController,p=!1,u=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),f=()=>l.abort();n&&(n.aborted?l.abort():n.addEventListener("abort",f,{once:!0}));try{let m=await o.executeTool(i,Cw(r),{signal:l.signal});return yw(m)}catch(m){if(p)return $n(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return $n("Aborted by cancel()");let y=m instanceof Error?m.message:String(m);return $n(y)}finally{clearTimeout(u),n&&n.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await Promise.resolve().then(()=>(_h(),Oh))).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ui.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let r=t;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ui.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var n;let r=(n=this.confirmHandler)!=null?n:bw;try{return await r(t)}catch(o){return Ui.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(n=>hw(t,n))}},_d=e=>e.startsWith(Ia)?e.slice(Ia.length):e,Ra=e=>e.startsWith(Ia),hw=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},xw=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},yw=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:vw(t)}]}},$n=e=>({isError:!0,content:[{type:"text",text:e}]}),bw=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=ww(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
45
+ `}tablerow(e){return`<tr>
46
+ ${e}</tr>
47
+ `}tablecell(e,r){let n=r.header?"th":"td";return(r.align?`<${n} align="${r.align}">`:`<${n}>`)+e+`</${n}>
48
+ `}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,r,n){let o=Pg(e);if(o===null)return n;e=o;let s='<a href="'+e+'"';return r&&(s+=' title="'+r+'"'),s+=">"+n+"</a>",s}image(e,r,n){let o=Pg(e);if(o===null)return n;e=o;let s=`<img src="${e}" alt="${n}"`;return r&&(s+=` title="${r}"`),s+=">",s}text(e){return e}},ys=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,r,n){return""+n}image(e,r,n){return""+n}br(){return""}},po=class t{constructor(e){Ht(this,"options");Ht(this,"renderer");Ht(this,"textRenderer");this.options=e||ta,this.options.renderer=this.options.renderer||new Ma,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ys}static parse(e,r){return new t(r).parse(e)}static parseInline(e,r){return new t(r).parseInline(e)}parse(e,r=!0){let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=s,i=this.options.extensions.renderers[a.type].call({parser:this},a);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(a.type)){n+=i||"";continue}}switch(s.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let a=s;n+=this.renderer.heading(this.parseInline(a.tokens),a.depth,Ky(this.parseInline(a.tokens,this.textRenderer)));continue}case"code":{let a=s;n+=this.renderer.code(a.text,a.lang,!!a.escaped);continue}case"table":{let a=s,i="",d="";for(let p=0;p<a.header.length;p++)d+=this.renderer.tablecell(this.parseInline(a.header[p].tokens),{header:!0,align:a.align[p]});i+=this.renderer.tablerow(d);let l="";for(let p=0;p<a.rows.length;p++){let m=a.rows[p];d="";for(let u=0;u<m.length;u++)d+=this.renderer.tablecell(this.parseInline(m[u].tokens),{header:!1,align:a.align[u]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let a=s,i=this.parse(a.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let a=s,i=a.ordered,d=a.start,l=a.loose,p="";for(let m=0;m<a.items.length;m++){let u=a.items[m],f=u.checked,y=u.task,A="";if(u.task){let E=this.renderer.checkbox(!!f);l?u.tokens.length>0&&u.tokens[0].type==="paragraph"?(u.tokens[0].text=E+" "+u.tokens[0].text,u.tokens[0].tokens&&u.tokens[0].tokens.length>0&&u.tokens[0].tokens[0].type==="text"&&(u.tokens[0].tokens[0].text=E+" "+u.tokens[0].tokens[0].text)):u.tokens.unshift({type:"text",text:E+" "}):A+=E+" "}A+=this.parse(u.tokens,l),p+=this.renderer.listitem(A,y,!!f)}n+=this.renderer.list(p,i,d);continue}case"html":{let a=s;n+=this.renderer.html(a.text,a.block);continue}case"paragraph":{let a=s;n+=this.renderer.paragraph(this.parseInline(a.tokens));continue}case"text":{let a=s,i=a.tokens?this.parseInline(a.tokens):a.text;for(;o+1<e.length&&e[o+1].type==="text";)a=e[++o],i+=`
49
+ `+(a.tokens?this.parseInline(a.tokens):a.text);n+=r?this.renderer.paragraph(i):i;continue}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,r){r=r||this.renderer;let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){n+=a||"";continue}}switch(s.type){case"escape":{let a=s;n+=r.text(a.text);break}case"html":{let a=s;n+=r.html(a.text);break}case"link":{let a=s;n+=r.link(a.href,a.title,this.parseInline(a.tokens,r));break}case"image":{let a=s;n+=r.image(a.href,a.title,a.text);break}case"strong":{let a=s;n+=r.strong(this.parseInline(a.tokens,r));break}case"em":{let a=s;n+=r.em(this.parseInline(a.tokens,r));break}case"codespan":{let a=s;n+=r.codespan(a.text);break}case"br":{n+=r.br();break}case"del":{let a=s;n+=r.del(this.parseInline(a.tokens,r));break}case"text":{let a=s;n+=r.text(a.text);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}},Yo=class{constructor(e){Ht(this,"options");this.options=e||ta}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};Ht(Yo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var ea,sd,qg,bs=class{constructor(...e){Eg(this,ea);Ht(this,"defaults",id());Ht(this,"options",this.setOptions);Ht(this,"parse",Ai(this,ea,sd).call(this,co.lex,po.parse));Ht(this,"parseInline",Ai(this,ea,sd).call(this,co.lexInline,po.parseInline));Ht(this,"Parser",po);Ht(this,"Renderer",Ma);Ht(this,"TextRenderer",ys);Ht(this,"Lexer",co);Ht(this,"Tokenizer",Ta);Ht(this,"Hooks",Yo);this.use(...e)}walkTokens(e,r){var o,s;let n=[];for(let a of e)switch(n=n.concat(r.call(this,a)),a.type){case"table":{let i=a;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,r));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,r));break}case"list":{let i=a;n=n.concat(this.walkTokens(i.items,r));break}default:{let i=a;(s=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&s[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,r))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,r)))}}return n}use(...e){let r=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let a=r.renderers[s.name];a?r.renderers[s.name]=function(...i){let d=s.renderer.apply(this,i);return d===!1&&(d=a.apply(this,i)),d}:r.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=r[s.level];a?a.unshift(s.tokenizer):r[s.level]=[s.tokenizer],s.start&&(s.level==="block"?r.startBlock?r.startBlock.push(s.start):r.startBlock=[s.start]:s.level==="inline"&&(r.startInline?r.startInline.push(s.start):r.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(r.childTokens[s.name]=s.childTokens)}),o.extensions=r),n.renderer){let s=this.defaults.renderer||new Ma(this.defaults);for(let a in n.renderer){if(!(a in s))throw new Error(`renderer '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.renderer[i],l=s[i];s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m||""}}o.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Ta(this.defaults);for(let a in n.tokenizer){if(!(a in s))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let i=a,d=n.tokenizer[i],l=s[i];s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m}}o.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new Yo;for(let a in n.hooks){if(!(a in s))throw new Error(`hook '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.hooks[i],l=s[i];Yo.passThroughHooks.has(a)?s[i]=p=>{if(this.defaults.async)return Promise.resolve(d.call(s,p)).then(u=>l.call(s,u));let m=d.call(s,p);return l.call(s,m)}:s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m}}o.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,a=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(a.call(this,i)),s&&(d=d.concat(s.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,r){return co.lex(e,r!=null?r:this.defaults)}parser(e,r){return po.parse(e,r!=null?r:this.defaults)}};ea=new WeakSet,sd=function(e,r){return(n,o)=>{let s={...o},a={...this.defaults,...s};this.defaults.async===!0&&s.async===!1&&(a.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),a.async=!0);let i=Ai(this,ea,qg).call(this,!!a.silent,!!a.async);if(typeof n=="undefined"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(a.hooks&&(a.hooks.options=a),a.async)return Promise.resolve(a.hooks?a.hooks.preprocess(n):n).then(d=>e(d,a)).then(d=>a.hooks?a.hooks.processAllTokens(d):d).then(d=>a.walkTokens?Promise.all(this.walkTokens(d,a.walkTokens)).then(()=>d):d).then(d=>r(d,a)).then(d=>a.hooks?a.hooks.postprocess(d):d).catch(i);try{a.hooks&&(n=a.hooks.preprocess(n));let d=e(n,a);a.hooks&&(d=a.hooks.processAllTokens(d)),a.walkTokens&&this.walkTokens(d,a.walkTokens);let l=r(d,a);return a.hooks&&(l=a.hooks.postprocess(l)),l}catch(d){return i(d)}}},qg=function(e,r){return n=>{if(n.message+=`
50
+ Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+gn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var Zo=new bs;function nr(t,e){return Zo.parse(t,e)}nr.options=nr.setOptions=function(t){return Zo.setOptions(t),nr.defaults=Zo.defaults,Bg(nr.defaults),nr};nr.getDefaults=id;nr.defaults=ta;nr.use=function(...t){return Zo.use(...t),nr.defaults=Zo.defaults,Bg(nr.defaults),nr};nr.walkTokens=function(t,e){return Zo.walkTokens(t,e)};nr.parseInline=Zo.parseInline;nr.Parser=po;nr.parser=po.parse;nr.Renderer=Ma;nr.TextRenderer=ys;nr.Lexer=co;nr.lexer=co.lex;nr.Tokenizer=Ta;nr.Hooks=Yo;nr.parse=nr;var oA=nr.options,aA=nr.setOptions,sA=nr.use,iA=nr.walkTokens,lA=nr.parseInline;var dA=po.parse,cA=co.lex;var Sb=t=>{if(t)return t},Cs=t=>{var o,s;let e=t==null?void 0:t.markedOptions,r=new bs({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=Sb(t==null?void 0:t.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},ra=t=>t?Cs({markedOptions:t.options,renderer:t.renderer}):Cs(),Tb=Cs(),fd=t=>Tb(t),na=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),jg=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Vg=t=>`%%FORM_PLACEHOLDER_${t}%%`,Gg=(t,e)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Vg(e.length);return e.push({token:a,type:String(s.type)}),a}}catch{return n}return n}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let s=Vg(e.length);return e.push({token:s,type:o}),s}),r},Kg=t=>{let e=ra(t);return r=>{let n=[],o=Gg(r,n),s=e(o);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${jg(i)}"></div>`;s=s.replace(d,p)}),s}},Xg=t=>{let e=[],r=Gg(t,e),n=fd(r);return e.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${jg(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:oh,setPrototypeOf:Jg,isFrozen:Mb,getPrototypeOf:kb,getOwnPropertyDescriptor:Eb}=Object,{freeze:Qr,seal:Mn,create:Pi}=Object,{apply:wd,construct:vd}=typeof Reflect!="undefined"&&Reflect;Qr||(Qr=function(e){return e});Mn||(Mn=function(e){return e});wd||(wd=function(e,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return e.apply(r,o)});vd||(vd=function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return new e(...n)});var Ei=Yr(Array.prototype.forEach),Lb=Yr(Array.prototype.lastIndexOf),Qg=Yr(Array.prototype.pop),As=Yr(Array.prototype.push),Pb=Yr(Array.prototype.splice),Ii=Yr(String.prototype.toLowerCase),md=Yr(String.prototype.toString),gd=Yr(String.prototype.match),Ss=Yr(String.prototype.replace),Ib=Yr(String.prototype.indexOf),Rb=Yr(String.prototype.trim),hn=Yr(Object.prototype.hasOwnProperty),Jr=Yr(RegExp.prototype.test),Ts=Wb(TypeError);function Yr(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return wd(t,e,n)}}function Wb(t){return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return vd(t,r)}}function It(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ii;Jg&&Jg(t,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let s=r(o);s!==o&&(Mb(e)||(e[n]=s),o=s)}t[o]=!0}return t}function Bb(t){for(let e=0;e<t.length;e++)hn(t,e)||(t[e]=null);return t}function Kn(t){let e=Pi(null);for(let[r,n]of oh(t))hn(t,r)&&(Array.isArray(n)?e[r]=Bb(n):n&&typeof n=="object"&&n.constructor===Object?e[r]=Kn(n):e[r]=n);return e}function Ms(t,e){for(;t!==null;){let n=Eb(t,e);if(n){if(n.get)return Yr(n.get);if(typeof n.value=="function")return Yr(n.value)}t=kb(t)}function r(){return null}return r}var Yg=Qr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),hd=Qr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),xd=Qr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Hb=Qr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),yd=Qr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Db=Qr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Zg=Qr(["#text"]),eh=Qr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),bd=Qr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),th=Qr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Li=Qr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Ob=Mn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),_b=Mn(/<%[\w\W]*|[\w\W]*%>/gm),Nb=Mn(/\$\{[\w\W]*/gm),Fb=Mn(/^data-[\-\w.\u00B7-\uFFFF]+$/),$b=Mn(/^aria-[\-\w]+$/),ah=Mn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ub=Mn(/^(?:\w+script|data):/i),zb=Mn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),sh=Mn(/^html$/i),qb=Mn(/^[a-z][.\w]*(-[.\w]+)+$/i),rh=Object.freeze({__proto__:null,ARIA_ATTR:$b,ATTR_WHITESPACE:zb,CUSTOM_ELEMENT:qb,DATA_ATTR:Fb,DOCTYPE_NAME:sh,ERB_EXPR:_b,IS_ALLOWED_URI:ah,IS_SCRIPT_OR_DATA:Ub,MUSTACHE_EXPR:Ob,TMPLIT_EXPR:Nb}),ks={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Vb=function(){return typeof window=="undefined"?null:window},jb=function(e,r){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(n=r.getAttribute(o));let s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},nh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ih(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Vb(),e=ue=>ih(ue);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==ks.document||!t.Element)return e.isSupported=!1,e;let{document:r}=t,n=r,o=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:u,trustedTypes:f}=t,y=d.prototype,A=Ms(y,"cloneNode"),E=Ms(y,"remove"),T=Ms(y,"nextSibling"),S=Ms(y,"childNodes"),k=Ms(y,"parentNode");if(typeof a=="function"){let ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let x,b="",{implementation:h,createNodeIterator:M,createDocumentFragment:W,getElementsByTagName:R}=r,{importNode:B}=n,_=nh();e.isSupported=typeof oh=="function"&&typeof k=="function"&&h&&h.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:oe,TMPLIT_EXPR:be,DATA_ATTR:Qe,ARIA_ATTR:je,IS_SCRIPT_OR_DATA:ve,ATTR_WHITESPACE:Ee,CUSTOM_ELEMENT:Ge}=rh,{IS_ALLOWED_URI:_e}=rh,X=null,Ue=It({},[...Yg,...hd,...xd,...yd,...Zg]),K=null,Te=It({},[...eh,...bd,...th,...Li]),ae=Object.seal(Pi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),xe=null,Me=null,Ke=Object.seal(Pi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ce=!0,re=!0,le=!1,ut=!0,Ce=!1,he=!0,tt=!1,Ne=!1,me=!1,J=!1,qe=!1,Z=!1,ge=!0,q=!1,Re="user-content-",Ae=!0,fe=!1,pe={},Be=null,Q=It({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),N=null,ke=It({},["audio","video","img","source","image","track"]),He=null,Ve=It({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Xe="http://www.w3.org/1998/Math/MathML",gt="http://www.w3.org/2000/svg",ot="http://www.w3.org/1999/xhtml",Mt=ot,Xt=!1,G=null,Jt=It({},[Xe,gt,ot],md),at=It({},["mi","mo","mn","ms","mtext"]),Nt=It({},["annotation-xml"]),de=It({},["title","style","font","a","script"]),ye=null,Rt=["application/xhtml+xml","text/html"],ar="text/html",kt=null,mr=null,Ot=r.createElement("form"),Wt=function(P){return P instanceof RegExp||P instanceof Function},St=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(mr&&mr===P)){if((!P||typeof P!="object")&&(P={}),P=Kn(P),ye=Rt.indexOf(P.PARSER_MEDIA_TYPE)===-1?ar:P.PARSER_MEDIA_TYPE,kt=ye==="application/xhtml+xml"?md:Ii,X=hn(P,"ALLOWED_TAGS")?It({},P.ALLOWED_TAGS,kt):Ue,K=hn(P,"ALLOWED_ATTR")?It({},P.ALLOWED_ATTR,kt):Te,G=hn(P,"ALLOWED_NAMESPACES")?It({},P.ALLOWED_NAMESPACES,md):Jt,He=hn(P,"ADD_URI_SAFE_ATTR")?It(Kn(Ve),P.ADD_URI_SAFE_ATTR,kt):Ve,N=hn(P,"ADD_DATA_URI_TAGS")?It(Kn(ke),P.ADD_DATA_URI_TAGS,kt):ke,Be=hn(P,"FORBID_CONTENTS")?It({},P.FORBID_CONTENTS,kt):Q,xe=hn(P,"FORBID_TAGS")?It({},P.FORBID_TAGS,kt):Kn({}),Me=hn(P,"FORBID_ATTR")?It({},P.FORBID_ATTR,kt):Kn({}),pe=hn(P,"USE_PROFILES")?P.USE_PROFILES:!1,ce=P.ALLOW_ARIA_ATTR!==!1,re=P.ALLOW_DATA_ATTR!==!1,le=P.ALLOW_UNKNOWN_PROTOCOLS||!1,ut=P.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ce=P.SAFE_FOR_TEMPLATES||!1,he=P.SAFE_FOR_XML!==!1,tt=P.WHOLE_DOCUMENT||!1,J=P.RETURN_DOM||!1,qe=P.RETURN_DOM_FRAGMENT||!1,Z=P.RETURN_TRUSTED_TYPE||!1,me=P.FORCE_BODY||!1,ge=P.SANITIZE_DOM!==!1,q=P.SANITIZE_NAMED_PROPS||!1,Ae=P.KEEP_CONTENT!==!1,fe=P.IN_PLACE||!1,_e=P.ALLOWED_URI_REGEXP||ah,Mt=P.NAMESPACE||ot,at=P.MATHML_TEXT_INTEGRATION_POINTS||at,Nt=P.HTML_INTEGRATION_POINTS||Nt,ae=P.CUSTOM_ELEMENT_HANDLING||{},P.CUSTOM_ELEMENT_HANDLING&&Wt(P.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ae.tagNameCheck=P.CUSTOM_ELEMENT_HANDLING.tagNameCheck),P.CUSTOM_ELEMENT_HANDLING&&Wt(P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ae.attributeNameCheck=P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),P.CUSTOM_ELEMENT_HANDLING&&typeof P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(ae.allowCustomizedBuiltInElements=P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ce&&(re=!1),qe&&(J=!0),pe&&(X=It({},Zg),K=Pi(null),pe.html===!0&&(It(X,Yg),It(K,eh)),pe.svg===!0&&(It(X,hd),It(K,bd),It(K,Li)),pe.svgFilters===!0&&(It(X,xd),It(K,bd),It(K,Li)),pe.mathMl===!0&&(It(X,yd),It(K,th),It(K,Li))),hn(P,"ADD_TAGS")||(Ke.tagCheck=null),hn(P,"ADD_ATTR")||(Ke.attributeCheck=null),P.ADD_TAGS&&(typeof P.ADD_TAGS=="function"?Ke.tagCheck=P.ADD_TAGS:(X===Ue&&(X=Kn(X)),It(X,P.ADD_TAGS,kt))),P.ADD_ATTR&&(typeof P.ADD_ATTR=="function"?Ke.attributeCheck=P.ADD_ATTR:(K===Te&&(K=Kn(K)),It(K,P.ADD_ATTR,kt))),P.ADD_URI_SAFE_ATTR&&It(He,P.ADD_URI_SAFE_ATTR,kt),P.FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,P.FORBID_CONTENTS,kt)),P.ADD_FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,P.ADD_FORBID_CONTENTS,kt)),Ae&&(X["#text"]=!0),tt&&It(X,["html","head","body"]),X.table&&(It(X,["tbody"]),delete xe.tbody),P.TRUSTED_TYPES_POLICY){if(typeof P.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ts('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof P.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ts('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=P.TRUSTED_TYPES_POLICY,b=x.createHTML("")}else x===void 0&&(x=jb(f,o)),x!==null&&typeof b=="string"&&(b=x.createHTML(""));Qr&&Qr(P),mr=P}},Et=It({},[...hd,...xd,...Hb]),sr=It({},[...yd,...Db]),ft=function(P){let ee=k(P);(!ee||!ee.tagName)&&(ee={namespaceURI:Mt,tagName:"template"});let Se=Ii(P.tagName),rt=Ii(ee.tagName);return G[P.namespaceURI]?P.namespaceURI===gt?ee.namespaceURI===ot?Se==="svg":ee.namespaceURI===Xe?Se==="svg"&&(rt==="annotation-xml"||at[rt]):!!Et[Se]:P.namespaceURI===Xe?ee.namespaceURI===ot?Se==="math":ee.namespaceURI===gt?Se==="math"&&Nt[rt]:!!sr[Se]:P.namespaceURI===ot?ee.namespaceURI===gt&&!Nt[rt]||ee.namespaceURI===Xe&&!at[rt]?!1:!sr[Se]&&(de[Se]||!Et[Se]):!!(ye==="application/xhtml+xml"&&G[P.namespaceURI]):!1},dr=function(P){As(e.removed,{element:P});try{k(P).removeChild(P)}catch{E(P)}},wr=function(P,ee){try{As(e.removed,{attribute:ee.getAttributeNode(P),from:ee})}catch{As(e.removed,{attribute:null,from:ee})}if(ee.removeAttribute(P),P==="is")if(J||qe)try{dr(ee)}catch{}else try{ee.setAttribute(P,"")}catch{}},Lr=function(P){let ee=null,Se=null;if(me)P="<remove></remove>"+P;else{let Ft=gd(P,/^[\r\n\t ]+/);Se=Ft&&Ft[0]}ye==="application/xhtml+xml"&&Mt===ot&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");let rt=x?x.createHTML(P):P;if(Mt===ot)try{ee=new u().parseFromString(rt,ye)}catch{}if(!ee||!ee.documentElement){ee=h.createDocument(Mt,"template",null);try{ee.documentElement.innerHTML=Xt?b:rt}catch{}}let Qt=ee.body||ee.documentElement;return P&&Se&&Qt.insertBefore(r.createTextNode(Se),Qt.childNodes[0]||null),Mt===ot?R.call(ee,tt?"html":"body")[0]:tt?ee.documentElement:Qt},Or=function(P){return M.call(P.ownerDocument||P,P,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},xt=function(P){return P instanceof m&&(typeof P.nodeName!="string"||typeof P.textContent!="string"||typeof P.removeChild!="function"||!(P.attributes instanceof p)||typeof P.removeAttribute!="function"||typeof P.setAttribute!="function"||typeof P.namespaceURI!="string"||typeof P.insertBefore!="function"||typeof P.hasChildNodes!="function")},sn=function(P){return typeof i=="function"&&P instanceof i};function fr(ue,P,ee){Ei(ue,Se=>{Se.call(e,P,ee,mr)})}let Un=function(P){let ee=null;if(fr(_.beforeSanitizeElements,P,null),xt(P))return dr(P),!0;let Se=kt(P.nodeName);if(fr(_.uponSanitizeElement,P,{tagName:Se,allowedTags:X}),he&&P.hasChildNodes()&&!sn(P.firstElementChild)&&Jr(/<[/\w!]/g,P.innerHTML)&&Jr(/<[/\w!]/g,P.textContent)||P.nodeType===ks.progressingInstruction||he&&P.nodeType===ks.comment&&Jr(/<[/\w]/g,P.data))return dr(P),!0;if(!(Ke.tagCheck instanceof Function&&Ke.tagCheck(Se))&&(!X[Se]||xe[Se])){if(!xe[Se]&&Zn(Se)&&(ae.tagNameCheck instanceof RegExp&&Jr(ae.tagNameCheck,Se)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(Se)))return!1;if(Ae&&!Be[Se]){let rt=k(P)||P.parentNode,Qt=S(P)||P.childNodes;if(Qt&&rt){let Ft=Qt.length;for(let tr=Ft-1;tr>=0;--tr){let Pr=A(Qt[tr],!0);Pr.__removalCount=(P.__removalCount||0)+1,rt.insertBefore(Pr,T(P))}}}return dr(P),!0}return P instanceof d&&!ft(P)||(Se==="noscript"||Se==="noembed"||Se==="noframes")&&Jr(/<\/no(script|embed|frames)/i,P.innerHTML)?(dr(P),!0):(Ce&&P.nodeType===ks.text&&(ee=P.textContent,Ei([V,oe,be],rt=>{ee=Ss(ee,rt," ")}),P.textContent!==ee&&(As(e.removed,{element:P.cloneNode()}),P.textContent=ee)),fr(_.afterSanitizeElements,P,null),!1)},Rr=function(P,ee,Se){if(Me[ee]||ge&&(ee==="id"||ee==="name")&&(Se in r||Se in Ot))return!1;if(!(re&&!Me[ee]&&Jr(Qe,ee))){if(!(ce&&Jr(je,ee))){if(!(Ke.attributeCheck instanceof Function&&Ke.attributeCheck(ee,P))){if(!K[ee]||Me[ee]){if(!(Zn(P)&&(ae.tagNameCheck instanceof RegExp&&Jr(ae.tagNameCheck,P)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(P))&&(ae.attributeNameCheck instanceof RegExp&&Jr(ae.attributeNameCheck,ee)||ae.attributeNameCheck instanceof Function&&ae.attributeNameCheck(ee,P))||ee==="is"&&ae.allowCustomizedBuiltInElements&&(ae.tagNameCheck instanceof RegExp&&Jr(ae.tagNameCheck,Se)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(Se))))return!1}else if(!He[ee]){if(!Jr(_e,Ss(Se,Ee,""))){if(!((ee==="src"||ee==="xlink:href"||ee==="href")&&P!=="script"&&Ib(Se,"data:")===0&&N[P])){if(!(le&&!Jr(ve,Ss(Se,Ee,"")))){if(Se)return!1}}}}}}}return!0},Zn=function(P){return P!=="annotation-xml"&&gd(P,Ge)},Pn=function(P){fr(_.beforeSanitizeAttributes,P,null);let{attributes:ee}=P;if(!ee||xt(P))return;let Se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0},rt=ee.length;for(;rt--;){let Qt=ee[rt],{name:Ft,namespaceURI:tr,value:Pr}=Qt,_r=kt(Ft),wn=Pr,Vt=Ft==="value"?wn:Rb(wn);if(Se.attrName=_r,Se.attrValue=Vt,Se.keepAttr=!0,Se.forceKeepAttr=void 0,fr(_.uponSanitizeAttribute,P,Se),Vt=Se.attrValue,q&&(_r==="id"||_r==="name")&&(wr(Ft,P),Vt=Re+Vt),he&&Jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){wr(Ft,P);continue}if(_r==="attributename"&&gd(Vt,"href")){wr(Ft,P);continue}if(Se.forceKeepAttr)continue;if(!Se.keepAttr){wr(Ft,P);continue}if(!ut&&Jr(/\/>/i,Vt)){wr(Ft,P);continue}Ce&&Ei([V,oe,be],Ir=>{Vt=Ss(Vt,Ir," ")});let $t=kt(P.nodeName);if(!Rr($t,_r,Vt)){wr(Ft,P);continue}if(x&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!tr)switch(f.getAttributeType($t,_r)){case"TrustedHTML":{Vt=x.createHTML(Vt);break}case"TrustedScriptURL":{Vt=x.createScriptURL(Vt);break}}if(Vt!==wn)try{tr?P.setAttributeNS(tr,Ft,Vt):P.setAttribute(Ft,Vt),xt(P)?dr(P):Qg(e.removed)}catch{wr(Ft,P)}}fr(_.afterSanitizeAttributes,P,null)},In=function ue(P){let ee=null,Se=Or(P);for(fr(_.beforeSanitizeShadowDOM,P,null);ee=Se.nextNode();)fr(_.uponSanitizeShadowNode,ee,null),Un(ee),Pn(ee),ee.content instanceof s&&ue(ee.content);fr(_.afterSanitizeShadowDOM,P,null)};return e.sanitize=function(ue){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ee=null,Se=null,rt=null,Qt=null;if(Xt=!ue,Xt&&(ue="<!-->"),typeof ue!="string"&&!sn(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw Ts("dirty is not a string, aborting")}else throw Ts("toString is not a function");if(!e.isSupported)return ue;if(Ne||St(P),e.removed=[],typeof ue=="string"&&(fe=!1),fe){if(ue.nodeName){let Pr=kt(ue.nodeName);if(!X[Pr]||xe[Pr])throw Ts("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof i)ee=Lr("<!---->"),Se=ee.ownerDocument.importNode(ue,!0),Se.nodeType===ks.element&&Se.nodeName==="BODY"||Se.nodeName==="HTML"?ee=Se:ee.appendChild(Se);else{if(!J&&!Ce&&!tt&&ue.indexOf("<")===-1)return x&&Z?x.createHTML(ue):ue;if(ee=Lr(ue),!ee)return J?null:Z?b:""}ee&&me&&dr(ee.firstChild);let Ft=Or(fe?ue:ee);for(;rt=Ft.nextNode();)Un(rt),Pn(rt),rt.content instanceof s&&In(rt.content);if(fe)return ue;if(J){if(qe)for(Qt=W.call(ee.ownerDocument);ee.firstChild;)Qt.appendChild(ee.firstChild);else Qt=ee;return(K.shadowroot||K.shadowrootmode)&&(Qt=B.call(n,Qt,!0)),Qt}let tr=tt?ee.outerHTML:ee.innerHTML;return tt&&X["!doctype"]&&ee.ownerDocument&&ee.ownerDocument.doctype&&ee.ownerDocument.doctype.name&&Jr(sh,ee.ownerDocument.doctype.name)&&(tr="<!DOCTYPE "+ee.ownerDocument.doctype.name+`>
51
+ `+tr),Ce&&Ei([V,oe,be],Pr=>{tr=Ss(tr,Pr," ")}),x&&Z?x.createHTML(tr):tr},e.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};St(ue),Ne=!0},e.clearConfig=function(){mr=null,Ne=!1},e.isValidAttribute=function(ue,P,ee){mr||St({});let Se=kt(ue),rt=kt(P);return Rr(Se,rt,ee)},e.addHook=function(ue,P){typeof P=="function"&&As(_[ue],P)},e.removeHook=function(ue,P){if(P!==void 0){let ee=Lb(_[ue],P);return ee===-1?void 0:Pb(_[ue],ee,1)[0]}return Qg(_[ue])},e.removeHooks=function(ue){_[ue]=[]},e.removeAllHooks=function(){_=nh()},e}var lh=ih();var Gb={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Kb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Cd=()=>{let t=lh(typeof window!="undefined"?window:void 0);return t.addHook("uponSanitizeAttribute",(e,r)=>{if(r.attrName==="src"||r.attrName==="href"){let n=r.attrValue;n.toLowerCase().startsWith("data:")&&!Kb.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),e=>t.sanitize(e,Gb)},ka=t=>t===!1?null:typeof t=="function"?t:Cd();var Es="webmcp:",Ni={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}};function Lh(t){if(t.length===0)return"0:empty";let e=t.map(r=>{var n,o;return[r.name,(n=r.description)!=null?n:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(o=r.origin)!=null?o:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${t.length}:${G0(e.join(""))}`}function Eh(t,e){let r=3735928559^e,n=1103547991^e;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);r=Math.imul(r^s,2654435761),n=Math.imul(n^s,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}function G0(t){let e=Eh(t,0).toString(36),r=Eh(t,2654435761).toString(36);return`${e}.${r}`}var Pa=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=e.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let r;try{r=await e.getTools()}catch(o){return Ni.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}let n=typeof location!="undefined"?location.origin:"";return r.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...n?{pageOrigin:n}:{}},a=X0(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,r,n){if(await this.ensureReady(),this.config.enabled!==!0)return Fn("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let f=typeof document!="undefined"&&!!document.modelContext;return Fn(f?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Pd(e),a;try{a=await o.getTools()}catch(f){let y=f instanceof Error?f.message:String(f);return Fn(`Failed to read WebMCP registry: ${y}`)}let i=a.find(f=>f.name===s);if(!i)return Fn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Fn(`WebMCP tool not allowed by client allowlist: ${s}`);if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let d={toolName:s,args:r,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return Fn("User declined the tool call.");if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),u=()=>l.abort();n&&(n.aborted?l.abort():n.addEventListener("abort",u,{once:!0}));try{let f=await o.executeTool(i,Z0(r),{signal:l.signal});return J0(f)}catch(f){if(p)return Fn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let y=f instanceof Error?f.message:String(f);return Fn(y)}finally{clearTimeout(m),n&&n.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await Promise.resolve().then(()=>(kh(),Mh))).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Ni.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let r=e;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ni.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var n;let r=(n=this.confirmHandler)!=null?n:Q0;try{return await r(e)}catch(o){return Ni.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(n=>K0(e,n))}},Pd=t=>t.startsWith(Es)?t.slice(Es.length):t,Ls=t=>t.startsWith(Es),K0=(t,e)=>{if(e==="*")return!0;let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(t)},X0=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},J0=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:ew(e)}]}},Fn=t=>({isError:!0,content:[{type:"text",text:t}]}),Q0=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Y0(t.args),r=`Allow the AI to call ${t.toolName}`+(e?`
52
52
 
53
53
  Arguments:
54
- ${t}`:"")+(e.description?`
54
+ ${e}`:"")+(t.description?`
55
55
 
56
- ${e.description}`:"");return window.confirm(r)},ww=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Cw=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},vw=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var fo=ud(ji(),1),Vi=e=>e.replace(/\\n/g,`
57
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Hs=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},kw=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),r=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Uh=e=>e.status==="complete"?kw(e):e.status==="pending"?"Waiting":"",Ew=e=>{var o,s,a;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var zh=e=>e.status==="complete"?Ew(e):"Using tool...",Gi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ha=e=>{var r,n,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((o=(n=e.startedAt)!=null?n:e.completedAt)!=null?o:Date.now()));return Gi(t)},Ki=e=>{var r,n,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((o=(n=e.startedAt)!=null?n:e.completedAt)!=null?o:Date.now()));return Gi(t)},$d=(e,t,r)=>{var s;if(!t)return r;let n=((s=e.name)==null?void 0:s.trim())||"tool",o=Ha(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Ji=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(r))!==null;)a.index>s&&Wa(n,r.slice(s,a.index),[]),a[1]!==void 0?Wa(n,a[1],["bold"]):a[2]!==void 0?Wa(n,a[2],["italic"]):a[3]!==void 0&&Wa(n,a[3],["dim"]),s=a.index+a[0].length;return s<r.length&&Wa(n,r.slice(s),[]),n},Wa=(e,t,r)=>{let n=t.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&e.push({text:n[o],styles:r}),o<n.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Lw=()=>{let e=null,t=0,r=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=n.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
56
+ ${t.description}`:"");return window.confirm(r)},Y0=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Z0=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},ew=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var fo=od(Ui(),1),zi=t=>t.replace(/\\n/g,`
57
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ia=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},aw=t=>{var a,i;let e=(a=t.completedAt)!=null?a:Date.now(),r=(i=t.startedAt)!=null?i:e,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ih=t=>t.status==="complete"?aw(t):t.status==="pending"?"Waiting":"",sw=t=>{var o,s,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Rh=t=>t.status==="complete"?sw(t):"Using tool...",qi=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Is=t=>{var r,n,o;let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((r=t.completedAt)!=null?r:Date.now())-((o=(n=t.startedAt)!=null?n:t.completedAt)!=null?o:Date.now()));return qi(e)},Vi=t=>{var r,n,o;let e=t.durationMs!==void 0?t.durationMs:Math.max(0,((r=t.completedAt)!=null?r:Date.now())-((o=(n=t.startedAt)!=null?n:t.completedAt)!=null?o:Date.now()));return qi(e)},Rd=(t,e,r)=>{var s;if(!e)return r;let n=((s=t.name)==null?void 0:s.trim())||"tool",o=Is(t);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},ji=(t,e)=>{let r=t.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(r))!==null;)a.index>s&&Ps(n,r.slice(s,a.index),[]),a[1]!==void 0?Ps(n,a[1],["bold"]):a[2]!==void 0?Ps(n,a[2],["italic"]):a[3]!==void 0&&Ps(n,a[3],["dim"]),s=a.index+a[0].length;return s<r.length&&Ps(n,r.slice(s),[]),n},Ps=(t,e,r)=>{let n=e.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&t.push({text:n[o],styles:r}),o<n.length-1&&t.push({text:"{duration}",styles:r,isDuration:!0})},iw=()=>{let t=null,e=0,r=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=n.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
58
58
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
59
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(n);return s!==null&&(e=s),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},ss=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Yi=()=>{var t;let e=Lw();return{processChunk:async r=>{let n=r.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Qi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=(0,fo.parse)(r,fo.STR|fo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Vi(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Vi(o.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},qh=e=>{let t=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Vi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Vi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return t!==null?{text:t,raw:s}:null;try{let i=(0,fo.parse)(s,fo.STR|fo.OBJ),d=o(i);d!==null&&(t=d)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var el=class{constructor(t,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=r}push(t,r){var s,a,i;let n=(i=(s=r==null?void 0:r.seq)!=null?s:r==null?void 0:r.sequenceIndex)!=null?i:(a=r==null?void 0:r.agentContext)==null?void 0:a.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(t,r),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(t,r);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:t,payload:r,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((r,n)=>r[0]-n[0]);for(let[r,n]of t)this.buffer.delete(r),this.emitter(n.payloadType,n.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Pw="https://api.runtype.com/v1/dispatch",tl="https://api.runtype.com";function Iw(e){var s,a;let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Fd=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Rw(e){switch(e){case"json":return Qi;case"regex-json":return Yi;case"xml":return Zi;default:return Xi}}var jh=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Ww(e,t){if(!e)return t;let r=e.trim(),n=t.trim();if(r.length===0)return t;if(n.length===0)return e;let o=jh(r);if(!jh(n))return e;if(!o||n===r||n.startsWith(r))return t;let a=ss(e);return ss(t)!==null&&a===null?t:e}var as=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,n,o,s;this.apiUrl=(r=t.apiUrl)!=null?r:Pw,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(n=t.streamParser)!=null?n:Rw(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ws(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,n):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||tl}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||tl}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,s,a,i;let n=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([b])=>b!=="sessionId"&&b!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Fd).map(b=>{var w,h,k;return{id:b.id,role:b.role,content:(k=(h=(w=b.contentParts)!=null?w:b.llmContent)!=null?h:b.rawContent)!=null?k:b.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),y=m?$h(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===y,T=!1,A=null,M;for(let b=0;;b++){let h={...u,...m&&(T||!E)&&f?{clientTools:f}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",h),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),signal:n.signal}),M.status===409&&b===0&&m){let k=await M.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}A=k!=null?k:{error:"Chat request failed"}}break}if(!M.ok){let b=A!=null?A:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}if(M.status===429){let h=new Error(b.hint||"Message limit reached for this session.");throw r({type:"error",error:h}),h}let w=new Error(b.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!M.body){let b=new Error("No response body received");throw r({type:"error",error:b}),b}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(M.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let n=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let n=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,n){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||tl}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,n){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||tl}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:r,streamResponse:(p=n==null?void 0:n.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Fd).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),n={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}return n}async buildPayload(t){var s;let n={messages:t.slice().filter(Fd).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...n},config:this.config});if(a&&typeof a=="object"){let i=a;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return n}async handleCustomSSEEvent(t,r,n,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return n.current=u,o(u),u},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),a.current=null,r({type:"status",status:"idle"})),i.error&&(a.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,n){var ke,ge,ue,_e;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=I=>{let te=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,qe=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,tt=I.tools?I.tools.map(Xe=>({...Xe,chunks:Xe.chunks?[...Xe.chunks]:void 0})):void 0;return{...I,reasoning:te,toolCall:qe,tools:tt}},u=I=>{r({type:"message",message:p(I)})},f=null,m=null,y={current:null},v={current:null},E=!1,T=new Map,A=new Map,M=new Map,b=new Map,w={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},k=(I,te,qe="")=>`${I}::${te}::${qe}`,B=(I,te)=>`${I}::${te}::`,H=(I,te,qe,tt)=>{let Xe=k(I,te,qe),Je=M.get(Xe);if(Je)return Je;let pt=qe?`-${qe}`:"",ht={id:`nested-${I}-${te}${pt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...qe?{partId:qe}:{},agentMetadata:{executionId:tt,parentToolId:I,parentStepId:te}};return M.set(Xe,ht),u(ht),ht},W=I=>{if(I==null)return null;try{return String(I)}catch{return null}},N=I=>{var te,qe,tt,Xe,Je;return W((Je=(Xe=(tt=(qe=(te=I.stepId)!=null?te:I.step_id)!=null?qe:I.step)!=null?tt:I.parentId)!=null?Xe:I.flowStepId)!=null?Je:I.flow_step_id)},q=I=>{var te,qe,tt,Xe,Je,pt,ht;return W((ht=(pt=(Je=(Xe=(tt=(qe=(te=I.callId)!=null?te:I.call_id)!=null?qe:I.requestId)!=null?tt:I.request_id)!=null?Xe:I.toolCallId)!=null?Je:I.tool_call_id)!=null?pt:I.stepId)!=null?ht:I.step_id)},se=n,ve=!1,Ue=()=>{if(f)return f;let I;return!ve&&se?(I=se,ve=!0):se&&v.current?I=`${se}_${v.current}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:I,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(f),f},je=(I,te)=>{w.lastId=te,I&&w.byStep.set(I,te)},we=(I,te)=>{var Je;let qe=(Je=I.reasoningId)!=null?Je:I.id,tt=N(I);if(qe){let pt=String(qe);return je(tt,pt),pt}if(tt){let pt=w.byStep.get(tt);if(pt)return w.lastId=pt,pt}if(w.lastId&&!te)return w.lastId;if(!te)return null;let Xe=`reason-${l()}`;return je(tt,Xe),Xe},Te=I=>{let te=T.get(I);if(te)return te;let qe={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:I,status:"streaming",chunks:[]}};return T.set(I,qe),u(qe),qe},We=(I,te)=>{h.lastId=te,I&&h.byCall.set(I,te)},Oe=new Set,K=new Map,He=new Set,j=new Map,Ce=I=>{if(!I)return!1;let te=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Z=(I,te)=>{var Je;let qe=(Je=I.toolId)!=null?Je:I.id,tt=q(I);if(qe){let pt=String(qe);return We(tt,pt),pt}if(tt){let pt=h.byCall.get(tt);if(pt)return h.lastId=pt,pt}if(h.lastId&&!te)return h.lastId;if(!te)return null;let Xe=`tool-${l()}`;return We(tt,Xe),Xe},he=I=>{let te=A.get(I);if(te)return te;let qe={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:I,status:"pending"}};return A.set(I,qe),u(qe),qe},xe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let te=Number(I);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let qe=Date.parse(I);if(!Number.isNaN(qe))return qe}return Date.now()},Ve=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},G=new Map,ee=new Map,Ie=new Map,ye=new Map,pe=null,le=(I,te,qe)=>{var ht;let tt=Ie.get(I);tt||(tt=[],Ie.set(I,tt));let Xe=0,Je=tt.length;for(;Xe<Je;){let zt=Xe+Je>>>1;tt[zt].seq<te?Xe=zt+1:Je=zt}((ht=tt[Xe])==null?void 0:ht.seq)===te?tt[Xe]={seq:te,text:qe}:tt.splice(Xe,0,{seq:te,text:qe});let pt="";for(let zt=0;zt<tt.length;zt++)pt+=tt[zt].text;return pt},Ye=(I,te)=>{let qe=Ve(te),tt=ee.get(I.id),Xe=Ww(tt,qe);I.rawContent=Xe;let Je=G.get(I.id),pt=kt=>{var Jt;let ct=(Jt=I.content)!=null?Jt:"";kt.trim()!==""&&(ct.trim().length===0||kt.startsWith(ct)||kt.trimStart().startsWith(ct.trim()))&&(I.content=kt)},ht=()=>{var kt;if(Je){let ct=(kt=Je.close)==null?void 0:kt.call(Je);ct instanceof Promise&&ct.catch(()=>{})}G.delete(I.id),ee.delete(I.id),I.streaming=!1,u(I)};if(!Je){pt(qe),ht();return}let zt=ss(Xe);if(zt!==null&&zt.trim()!==""){pt(zt),ht();return}let or=kt=>{var fe;let ct=typeof kt=="string"?kt:(fe=kt==null?void 0:kt.text)!=null?fe:null;if(ct!==null&&ct.trim()!=="")return ct;let Jt=Je.getExtractedText();return Jt!==null&&Jt.trim()!==""?Jt:qe},X;try{X=Je.processChunk(Xe)}catch{pt(qe),ht();return}if(X instanceof Promise){X.then(kt=>{pt(or(kt)),ht()}).catch(()=>{pt(qe),ht()});return}pt(or(X)),ht()},Me=[],be=!1,J,Ke=()=>{be||(be=!0,queueMicrotask(()=>{be=!1,J()}))},ne=new el((I,te)=>{Me.push({payloadType:I,payload:te}),Ke()}),Y=null,Q=new Map,Be=(ke=this.config.iterationDisplay)!=null?ke:"separate";for(J=()=>{var I,te,qe,tt,Xe,Je,pt,ht,zt,or,X,kt,ct,Jt,fe,Se,Wt,sr,Et,gr,_t,Ht,Tt,Lt,ar,mt,cr,Cr,Lr,_r,xt,an,mr,Un,Rr,Zn,Pn,In,me,P,oe,Ee,rt,Xt,$t,er,Pr,Nr,wn,Vt,Ft,Ir,Cn,wo,eo,Co,zn,ln,Rn,It,hr,xr,dn,vo,vn,Wn,cn,R,pn,Hn,to,qn,Qs,Bn,Dn,On,ro,Fo,ai,Zs,ii,ys,Pt,ea,Sn,tn,li,di,bs,no,ci,Uo,ta,oo,ra,So,Ao,pi,ui,cd,zo,To,fi,na,Mo,mi,oa,ko,sa,gi,so,hi,Eo,Kt,ws,Cs,aa,jn,xi,ia,la,yi,vs,Ss,qo,bi,wi,da,ca,pa,ua,jr,un,ao,yt,fa,jo,_n;for(let As=0;As<Me.length;As++){let ot=Me[As].payloadType,L=Me[As].payload;if(ot==="reason_start"){let z=(I=we(L,!0))!=null?I:`reason-${l()}`,O=Te(z);O.reasoning=(te=O.reasoning)!=null?te:{id:z,status:"streaming",chunks:[]},O.reasoning.startedAt=(tt=O.reasoning.startedAt)!=null?tt:xe((qe=L.startedAt)!=null?qe:L.timestamp),O.reasoning.completedAt=void 0,O.reasoning.durationMs=void 0,O.streaming=!0,O.reasoning.status="streaming",u(O)}else if(ot==="reason_delta"||ot==="reason_chunk"){let z=(Je=(Xe=we(L,!1))!=null?Xe:we(L,!0))!=null?Je:`reason-${l()}`,O=Te(z);O.reasoning=(pt=O.reasoning)!=null?pt:{id:z,status:"streaming",chunks:[]},O.reasoning.startedAt=(zt=O.reasoning.startedAt)!=null?zt:xe((ht=L.startedAt)!=null?ht:L.timestamp);let ie=(kt=(X=(or=L.reasoningText)!=null?or:L.text)!=null?X:L.delta)!=null?kt:"";if(ie&&L.hidden!==!0){let de=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(de!==void 0){let re=le(z,de,String(ie));O.reasoning.chunks=[re]}else O.reasoning.chunks.push(String(ie))}if(O.reasoning.status=L.done?"complete":"streaming",L.done){O.reasoning.completedAt=xe((ct=L.completedAt)!=null?ct:L.timestamp);let de=(Jt=O.reasoning.startedAt)!=null?Jt:Date.now();O.reasoning.durationMs=Math.max(0,((fe=O.reasoning.completedAt)!=null?fe:Date.now())-de)}O.streaming=O.reasoning.status!=="complete",u(O)}else if(ot==="reason_complete"){let z=(Wt=(Se=we(L,!1))!=null?Se:we(L,!0))!=null?Wt:`reason-${l()}`,O=T.get(z);if(O!=null&&O.reasoning){O.reasoning.status="complete",O.reasoning.completedAt=xe((sr=L.completedAt)!=null?sr:L.timestamp);let de=(Et=O.reasoning.startedAt)!=null?Et:Date.now();O.reasoning.durationMs=Math.max(0,((gr=O.reasoning.completedAt)!=null?gr:Date.now())-de),O.streaming=!1,u(O)}let ie=N(L);ie&&w.byStep.delete(ie)}else if(ot==="tool_start"){let z=(_t=Z(L,!0))!=null?_t:`tool-${l()}`,O=(Ht=L.toolName)!=null?Ht:L.name;if(Ce(O)){Oe.add(z);continue}let ie=he(z),de=(Tt=ie.toolCall)!=null?Tt:{id:z,status:"pending"};de.name=O!=null?O:de.name,de.status="running",L.args!==void 0?de.args=L.args:L.parameters!==void 0&&(de.args=L.parameters),de.startedAt=(ar=de.startedAt)!=null?ar:xe((Lt=L.startedAt)!=null?Lt:L.timestamp),de.completedAt=void 0,de.durationMs=void 0,ie.toolCall=de,ie.streaming=!0;let re=L.agentContext;(re||L.executionId)&&(ie.agentMetadata={executionId:(mt=re==null?void 0:re.executionId)!=null?mt:L.executionId,iteration:(cr=re==null?void 0:re.iteration)!=null?cr:L.iteration}),u(ie)}else if(ot==="tool_chunk"||ot==="tool_delta"){let z=(Lr=(Cr=Z(L,!1))!=null?Cr:Z(L,!0))!=null?Lr:`tool-${l()}`;if(Oe.has(z))continue;let O=he(z),ie=(_r=O.toolCall)!=null?_r:{id:z,status:"running"};ie.startedAt=(an=ie.startedAt)!=null?an:xe((xt=L.startedAt)!=null?xt:L.timestamp);let de=(Rr=(Un=(mr=L.text)!=null?mr:L.delta)!=null?Un:L.message)!=null?Rr:"";de&&(ie.chunks=(Zn=ie.chunks)!=null?Zn:[],ie.chunks.push(String(de))),ie.status="running",O.toolCall=ie,O.streaming=!0;let re=L.agentContext;(re||L.executionId)&&(O.agentMetadata=(me=O.agentMetadata)!=null?me:{executionId:(Pn=re==null?void 0:re.executionId)!=null?Pn:L.executionId,iteration:(In=re==null?void 0:re.iteration)!=null?In:L.iteration}),u(O)}else if(ot==="tool_complete"){let z=(oe=(P=Z(L,!1))!=null?P:Z(L,!0))!=null?oe:`tool-${l()}`;if(Oe.has(z)){Oe.delete(z);continue}let O=he(z),ie=(Ee=O.toolCall)!=null?Ee:{id:z,status:"running"};ie.status="complete",L.result!==void 0&&(ie.result=L.result),typeof L.duration=="number"&&(ie.duration=L.duration),ie.completedAt=xe((rt=L.completedAt)!=null?rt:L.timestamp);let de=(Xt=L.duration)!=null?Xt:L.executionTime;if(typeof de=="number")ie.durationMs=de;else{let et=($t=ie.startedAt)!=null?$t:Date.now();ie.durationMs=Math.max(0,((er=ie.completedAt)!=null?er:Date.now())-et)}O.toolCall=ie,O.streaming=!1;let re=L.agentContext;(re||L.executionId)&&(O.agentMetadata=(wn=O.agentMetadata)!=null?wn:{executionId:(Pr=re==null?void 0:re.executionId)!=null?Pr:L.executionId,iteration:(Nr=re==null?void 0:re.iteration)!=null?Nr:L.iteration}),u(O);let st=q(L);st&&h.byCall.delete(st)}else if(ot==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let z=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,O=(Vt=z!=null?z:L.toolId)!=null?Vt:`local-${l()}`,ie=he(O),de=(Ft=ie.toolCall)!=null?Ft:{id:O,status:"pending"};de.name=L.toolName,de.args=L.parameters,de.status="complete",de.chunks=(Ir=de.chunks)!=null?Ir:[],de.startedAt=(wo=de.startedAt)!=null?wo:xe((Cn=L.startedAt)!=null?Cn:L.timestamp),de.completedAt=(eo=de.completedAt)!=null?eo:de.startedAt,ie.toolCall=de,ie.streaming=!1,ie.agentMetadata={...ie.agentMetadata,executionId:(zn=L.executionId)!=null?zn:(Co=ie.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},u(ie)}else if(ot==="text_start"){if((ln=L.toolContext)!=null&&ln.toolId)continue;let z=L.partId;if(z!==void 0&&v.current!==null&&z!==v.current){let O=f;O&&(O.streaming=!1,u(O),pe=O,f=null,E=!0)}z!==void 0&&(v.current=z)}else if(ot==="text_end"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let z=f;z&&(z.streaming=!1,u(z),pe=z,f=null,E=!0)}else if(ot==="step_chunk"||ot==="step_delta"){let z=L.stepType,O=L.executionType;if(z==="tool"||O==="context")continue;let ie=L.toolContext;if(ie!=null&&ie.toolId){let et=String((hr=(It=L.id)!=null?It:ie.stepId)!=null?hr:`step-${l()}`),wt=L.partId!==void 0&&L.partId!==null?String(L.partId):"",it=`${ie.toolId}::${et}`,lt=b.get(it);if(wt!==""&&lt!==void 0&&lt!==""&&lt!==wt){let Nt=M.get(k(ie.toolId,et,lt));Nt&&Nt.streaming!==!1&&(Nt.streaming=!1,u(Nt))}wt!==""&&b.set(it,wt);let ut=H(ie.toolId,et,wt,ie.executionId),yr=(vn=(vo=(dn=(xr=L.text)!=null?xr:L.delta)!=null?dn:L.content)!=null?vo:L.chunk)!=null?vn:"";yr&&(ut.content+=String(yr),ut.streaming=!0,u(ut)),L.isComplete&&(ut.streaming=!1,u(ut));continue}let de=L.partId;if(de!==void 0&&v.current!==null&&de!==v.current){let et=f;et&&(et.streaming=!1,u(et),pe=et,f=null,E=!0)}de!==void 0&&(v.current=de);let re=de!==void 0&&(Wn=ye.get(de))!=null?Wn:Ue();de!==void 0&&(re.partId||(re.partId=de),ye.set(de,re));let st=(Hn=(pn=(R=(cn=L.text)!=null?cn:L.delta)!=null?R:L.content)!=null?pn:L.chunk)!=null?Hn:"";if(st){let et=typeof L.seq=="number"?L.seq:void 0,wt=de!=null?de:re.id,it=et!==void 0?le(wt,et,String(st)):((to=ee.get(re.id))!=null?to:"")+st;re.rawContent=it,G.has(re.id)||G.set(re.id,this.createStreamParser());let lt=G.get(re.id),ut=it.trim().startsWith("{")||it.trim().startsWith("[");if(ut&&ee.set(re.id,it),lt.__isPlainTextParser===!0){re.content=et!==void 0?it:re.content+st,ee.delete(re.id),G.delete(re.id),re.rawContent=void 0,u(re);continue}let Nt=lt.processChunk(it);if(Nt instanceof Promise)Nt.then(qt=>{var $r;let Mr=typeof qt=="string"?qt:($r=qt==null?void 0:qt.text)!=null?$r:null;if(Mr!==null&&Mr.trim()!=="")re.content=Mr,u(re);else if(!ut&&!it.trim().startsWith("<")){let Wr=f,vr=Wr&&Wr.id===re.id?Wr:re;vr.id===re.id&&(vr.content=et!==void 0?it:vr.content+st,ee.delete(vr.id),G.delete(vr.id),vr.rawContent=void 0,u(vr))}}).catch(()=>{re.content=et!==void 0?it:re.content+st,ee.delete(re.id),G.delete(re.id),re.rawContent=void 0,u(re)});else{let qt=typeof Nt=="string"?Nt:(qn=Nt==null?void 0:Nt.text)!=null?qn:null;qt!==null&&qt.trim()!==""?(re.content=qt,u(re)):!ut&&!it.trim().startsWith("<")&&(re.content=et!==void 0?it:re.content+st,ee.delete(re.id),G.delete(re.id),re.rawContent=void 0,u(re))}}if(L.isComplete){let et=(Bn=(Qs=L.result)==null?void 0:Qs.response)!=null?Bn:re.content;if(et){let wt=ee.get(re.id),it=wt!=null?wt:Ve(et);re.rawContent=it;let lt=G.get(re.id),ut=null,yr=!1;if(lt&&(ut=lt.getExtractedText(),ut===null&&(ut=ss(it)),ut===null)){let Nt=lt.processChunk(it);Nt instanceof Promise?(yr=!0,Nt.then(qt=>{var $r;let Mr=typeof qt=="string"?qt:($r=qt==null?void 0:qt.text)!=null?$r:null;if(Mr!==null){let Wr=f;Wr&&Wr.id===re.id&&(Wr.content=Mr,Wr.streaming=!1,G.delete(Wr.id),ee.delete(Wr.id),u(Wr))}})):ut=typeof Nt=="string"?Nt:(Dn=Nt==null?void 0:Nt.text)!=null?Dn:null}if(!yr){ut!==null&&ut.trim()!==""?re.content=ut:ee.has(re.id)||(re.content=Ve(et));let Nt=G.get(re.id);if(Nt){let qt=(On=Nt.close)==null?void 0:On.call(Nt);qt instanceof Promise&&qt.catch(()=>{}),G.delete(re.id)}ee.delete(re.id),re.streaming=!1,u(re)}}}}else if(ot==="step_complete"){let z=L.stepType,O=L.executionType;if(z==="tool"||O==="context")continue;let ie=L.toolContext;if(ie!=null&&ie.toolId){let et=String((Fo=(ro=L.id)!=null?ro:ie.stepId)!=null?Fo:"");if(et){let wt=B(ie.toolId,et);for(let[it,lt]of M)it.startsWith(wt)&&lt.streaming!==!1&&(lt.streaming=!1,u(lt));b.delete(`${ie.toolId}::${et}`)}continue}let de=L.stopReason;if(E){if(f!==null){let it=f;de&&(it.stopReason=de),G.delete(it.id),ee.delete(it.id),it.streaming!==!1&&(it.streaming=!1,u(it))}let et=(ai=L.result)==null?void 0:ai.response,wt=pe;wt&&(de&&(wt.stopReason=de),et!=null?Ye(wt,et):(G.delete(wt.id),ee.delete(wt.id))),pe=null;continue}let re=(Zs=L.result)==null?void 0:Zs.response,st=Ue();if(de&&(st.stopReason=de),re!=null){let et=G.get(st.id),wt=!1,it=!1;if(et){let lt=et.getExtractedText(),ut=ee.get(st.id),yr=ut!=null?ut:Ve(re);if(st.rawContent=yr,lt!==null&&lt.trim()!=="")st.content=lt,wt=!0;else{let Nt=ss(yr);if(Nt!==null)st.content=Nt,wt=!0;else{let qt=et.processChunk(yr);if(qt instanceof Promise)it=!0,qt.then(Mr=>{var Wr;let $r=typeof Mr=="string"?Mr:(Wr=Mr==null?void 0:Mr.text)!=null?Wr:null;if($r!==null&&$r.trim()!==""){let vr=f;vr&&vr.id===st.id&&(vr.content=$r,vr.streaming=!1,G.delete(vr.id),ee.delete(vr.id),u(vr))}else{let vr=et.getExtractedText(),An=f;An&&An.id===st.id&&(vr!==null&&vr.trim()!==""?An.content=vr:ee.has(An.id)||(An.content=Ve(re)),An.streaming=!1,G.delete(An.id),ee.delete(An.id),u(An))}});else{let Mr=typeof qt=="string"?qt:(ii=qt==null?void 0:qt.text)!=null?ii:null;if(Mr!==null&&Mr.trim()!=="")st.content=Mr,wt=!0;else{let $r=et.getExtractedText();$r!==null&&$r.trim()!==""&&(st.content=$r,wt=!0)}}}}}if(!it){if(!st.rawContent){let lt=ee.get(st.id);st.rawContent=lt!=null?lt:Ve(re)}if(!wt&&!ee.has(st.id)&&(st.content=Ve(re)),et){let lt=(ys=et.close)==null?void 0:ys.call(et);lt instanceof Promise&&lt.catch(()=>{})}G.delete(st.id),ee.delete(st.id),st.streaming=!1,u(st)}}else G.delete(st.id),ee.delete(st.id),st.streaming=!1,u(st)}else if(ot==="flow_complete"){let z=(Pt=L.result)==null?void 0:Pt.response;if(E){if(f!==null){let O=f;G.delete(O.id),ee.delete(O.id),O.streaming!==!1&&(O.streaming=!1,u(O))}}else if(z!=null){let O=Ue(),ie=ee.get(O.id),de=ie!=null?ie:Ve(z);O.rawContent=de;let re=Ve(z),st=G.get(O.id);if(st){let it=ss(de);if(it!==null)re=it;else{let lt=st.processChunk(de);lt instanceof Promise&&lt.then(yr=>{var qt;let Nt=typeof yr=="string"?yr:(qt=yr==null?void 0:yr.text)!=null?qt:null;Nt!==null&&(O.content=Nt,O.streaming=!1,u(O))});let ut=st.getExtractedText();ut!==null&&(re=ut)}}G.delete(O.id),ee.delete(O.id);let et=re!==O.content,wt=O.streaming!==!1;et&&(O.content=re),O.streaming=!1,(et||wt)&&u(O)}else if(f!==null){let O=f;G.delete(O.id),ee.delete(O.id),O.streaming!==!1&&(O.streaming=!1,u(O))}r({type:"status",status:"idle"})}else if(ot==="agent_start")Y={executionId:L.executionId,agentId:(ea=L.agentId)!=null?ea:"virtual",agentName:(Sn=L.agentName)!=null?Sn:"",status:"running",currentIteration:0,maxTurns:(tn=L.maxTurns)!=null?tn:1,startedAt:xe(L.startedAt)};else if(ot==="agent_iteration_start"){if(Y&&(Y.currentIteration=L.iteration),Be==="separate"&&L.iteration>1){let z=f;z&&(z.streaming=!1,u(z),Q.set(L.iteration-1,z),f=null)}}else if(ot==="agent_turn_start")m=null;else if(ot==="agent_turn_delta"){if(L.contentType==="text"){let z=Ue();z.content+=(li=L.delta)!=null?li:"",z.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:Y==null?void 0:Y.agentName},m=z,u(z)}else if(L.contentType==="thinking"){let z=(di=L.turnId)!=null?di:`agent-think-${L.iteration}`,O=Te(z);O.reasoning=(bs=O.reasoning)!=null?bs:{id:z,status:"streaming",chunks:[]},O.reasoning.chunks.push((no=L.delta)!=null?no:""),O.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(O)}else if(L.contentType==="tool_input"){let z=(ci=L.toolCallId)!=null?ci:h.lastId;if(z){let O=A.get(z);O!=null&&O.toolCall&&(O.toolCall.chunks=(Uo=O.toolCall.chunks)!=null?Uo:[],O.toolCall.chunks.push((ta=L.delta)!=null?ta:""),u(O))}}}else if(ot==="agent_turn_complete"){let z=L.turnId;if(z){let de=T.get(z);if(de!=null&&de.reasoning){de.reasoning.status="complete",de.reasoning.completedAt=xe(L.completedAt);let re=(oo=de.reasoning.startedAt)!=null?oo:Date.now();de.reasoning.durationMs=Math.max(0,((ra=de.reasoning.completedAt)!=null?ra:Date.now())-re),de.streaming=!1,u(de)}}let O=L.stopReason,ie=f!=null?f:m;if(O&&ie!==null){let de=L.turnId;(!de||((So=ie.agentMetadata)==null?void 0:So.turnId)===de)&&(ie.stopReason=O,u(ie))}}else if(ot==="agent_tool_start"){f&&(f.streaming=!1,u(f),f=null);let z=(Ao=L.toolCallId)!=null?Ao:`agent-tool-${l()}`;We(q(L),z);let O=he(z),ie=(pi=O.toolCall)!=null?pi:{id:z,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};ie.name=(cd=(ui=L.toolName)!=null?ui:L.name)!=null?cd:ie.name,ie.status="running",L.parameters!==void 0&&(ie.args=L.parameters),ie.startedAt=xe((zo=L.startedAt)!=null?zo:L.timestamp),O.toolCall=ie,O.streaming=!0,O.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(O)}else if(ot==="agent_tool_delta"){let z=(To=L.toolCallId)!=null?To:h.lastId;if(z){let O=(fi=A.get(z))!=null?fi:he(z);O.toolCall&&(O.toolCall.chunks=(na=O.toolCall.chunks)!=null?na:[],O.toolCall.chunks.push((Mo=L.delta)!=null?Mo:""),O.toolCall.status="running",O.streaming=!0,u(O))}}else if(ot==="agent_tool_complete"){let z=(mi=L.toolCallId)!=null?mi:h.lastId;if(z){let O=(oa=A.get(z))!=null?oa:he(z);if(O.toolCall){O.toolCall.status="complete",L.result!==void 0&&(O.toolCall.result=L.result),typeof L.executionTime=="number"&&(O.toolCall.durationMs=L.executionTime),O.toolCall.completedAt=xe((ko=L.completedAt)!=null?ko:L.timestamp),O.streaming=!1,u(O);let ie=q(L);ie&&h.byCall.delete(ie)}}}else if(ot==="agent_media"){let z=Array.isArray(L.media)?L.media:[],O=[];for(let ie of z){if(!ie||typeof ie!="object")continue;let de=ie,re=typeof de.type=="string"?de.type:void 0,st=typeof de.mediaType=="string"?de.mediaType.toLowerCase():"",et=null,wt="";if(re==="media"){let it=typeof de.data=="string"?de.data:void 0;if(!it)continue;wt=st.length>0?st:"application/octet-stream",et=`data:${wt};base64,${it}`}else if(re==="image-url"){let it=typeof de.url=="string"?de.url:void 0;if(!it)continue;wt=st,et=it}else if(re==="file-url"){let it=typeof de.url=="string"?de.url:void 0;if(!it)continue;wt=st,et=it}else continue;if(et)if(re==="image-url"||wt.startsWith("image/"))O.push({type:"image",image:et,...wt?{mimeType:wt}:{}});else if(wt.startsWith("audio/"))O.push({type:"audio",audio:et,mimeType:wt});else if(wt.startsWith("video/"))O.push({type:"video",video:et,mimeType:wt});else{let it=wt||"application/octet-stream";O.push({type:"file",data:et,mimeType:it,filename:Iw(it)})}}if(O.length>0){let ie=l(),de=L.toolCallId,st={id:`agent-media-${typeof de=="string"&&de.length>0?`${de}-${ie}`:String(ie)}`,role:"assistant",content:"",contentParts:O,createdAt:new Date().toISOString(),streaming:!1,sequence:ie,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(st);let et=f;et&&(et.streaming=!1,u(et)),f=null,y.current=null}}else if(ot!=="agent_iteration_complete"){if(ot==="agent_reflection"||ot==="agent_reflect"){let z=`agent-reflection-${L.executionId}-${L.iteration}`,O={id:z,role:"assistant",content:(sa=L.reflection)!=null?sa:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(gi=L.reflection)!=null?gi:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(O)}else if(ot==="agent_complete"){Y&&(Y.status=L.success?"complete":"error",Y.completedAt=xe(L.completedAt),Y.stopReason=L.stopReason);let z=f;z&&(z.streaming=!1,u(z)),r({type:"status",status:"idle"})}else if(ot==="agent_error"){let z=typeof L.error=="string"?L.error:(hi=(so=L.error)==null?void 0:so.message)!=null?hi:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):r({type:"error",error:new Error(z)})}else if(ot!=="agent_ping"){if(ot==="agent_approval_start"){let z=(Eo=L.approvalId)!=null?Eo:`approval-${l()}`,O={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Kt=Y==null?void 0:Y.agentId)!=null?Kt:"virtual",executionId:(Cs=(ws=L.executionId)!=null?ws:Y==null?void 0:Y.executionId)!=null?Cs:"",toolName:(aa=L.toolName)!=null?aa:"",toolType:L.toolType,description:(xi=L.description)!=null?xi:`Execute ${(jn=L.toolName)!=null?jn:"tool"}`,parameters:L.parameters}};u(O)}else if(ot==="step_await"&&L.awaitReason==="approval_required"){let z=(ia=L.approvalId)!=null?ia:`approval-${l()}`,O={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(la=Y==null?void 0:Y.agentId)!=null?la:"virtual",executionId:(vs=(yi=L.executionId)!=null?yi:Y==null?void 0:Y.executionId)!=null?vs:"",toolName:(Ss=L.toolName)!=null?Ss:"",toolType:L.toolType,description:(bi=L.description)!=null?bi:`Execute ${(qo=L.toolName)!=null?qo:"tool"}`,parameters:L.parameters}};u(O)}else if(ot==="agent_approval_complete"){let z=L.approvalId;if(z){let ie={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(wi=L.decision)!=null?wi:"approved",agentId:(da=Y==null?void 0:Y.agentId)!=null?da:"virtual",executionId:(pa=(ca=L.executionId)!=null?ca:Y==null?void 0:Y.executionId)!=null?pa:"",toolName:(ua=L.toolName)!=null?ua:"",description:(jr=L.description)!=null?jr:"",resolvedAt:Date.now()}};u(ie)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=L.artifactType,O=String(L.id),ie=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:O,artifactType:z,title:ie,component:typeof L.component=="string"?L.component:void 0}),j.set(O,{markdown:"",title:ie}),!He.has(O)){He.add(O);let de={id:`artifact-ref-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:O,title:ie,artifactType:z,status:"streaming"}})};K.set(O,de),u(de)}}else if(ot==="artifact_delta"){let z=String(L.id),O=typeof L.delta=="string"?L.delta:String((un=L.delta)!=null?un:"");r({type:"artifact_delta",id:z,artDelta:O});let ie=j.get(z);ie&&(ie.markdown+=O)}else if(ot==="artifact_update"){let z=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:z,component:typeof L.component=="string"?L.component:void 0})}else if(ot==="artifact_complete"){let z=String(L.id);r({type:"artifact_complete",id:z});let O=K.get(z);if(O){O.streaming=!1;try{let ie=JSON.parse((ao=O.rawContent)!=null?ao:"{}");if(ie.props){ie.props.status="complete";let de=j.get(z);de!=null&&de.markdown&&(ie.props.markdown=de.markdown)}O.rawContent=JSON.stringify(ie)}catch{}j.delete(z),u(O),K.delete(z)}}}else if(ot==="transcript_insert"){let z=L.message;if(!z||typeof z!="object")continue;let O=String((yt=z.id)!=null?yt:`msg-${l()}`),ie=z.role,re={id:O,role:ie==="user"?"user":ie==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(u(re),re.rawContent)try{let st=JSON.parse(re.rawContent),et=(fa=st==null?void 0:st.props)==null?void 0:fa.artifactId;typeof et=="string"&&He.add(et)}catch{}f=null,y.current=null,G.delete(O),ee.delete(O)}else if(ot==="error"||ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(L.error instanceof Error)z=L.error;else if(ot==="dispatch_error"){let O=(jo=L.message)!=null?jo:L.error;O!=null&&O!==""&&(z=new Error(String(O)))}else if(ot==="step_error"||ot==="flow_error"){let O=L.error;typeof O=="string"&&O!==""?z=new Error(O):O!=null&&typeof O=="object"&&"message"in O&&(z=new Error(String((_n=O.message)!=null?_n:O)))}else ot==="error"&&L.error!=null&&L.error!==""&&(z=new Error(String(L.error)));if(z){r({type:"error",error:z});let O=f;O&&O.streaming&&(O.streaming=!1,u(O)),r({type:"status",status:"idle"})}}}}}Me.length=0};;){let{done:I,value:te}=await o.read();if(I)break;a+=s.decode(te,{stream:!0});let qe=a.split(`
59
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async n=>{if(n.length<=e)return t!==null?{text:t,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(n);return s!==null&&(t=s),e=n.length,t!==null?{text:t,raw:n}:null},close:async()=>{}}},oa=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Gi=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Ki=()=>{var e;let t=iw();return{processChunk:async r=>{let n=r.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},Xi=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,fo.parse)(r,fo.STR|fo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?zi(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=zi(o.text)))}catch{}return e=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Wh=t=>{let e=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?zi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let i=(0,fo.parse)(s,fo.STR|fo.OBJ),d=o(i);d!==null&&(e=d)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Ji=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let n=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(t=n[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Qi=class{constructor(e,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=r}push(e,r){var s,a,i;let n=(i=(s=r==null?void 0:r.seq)!=null?s:r==null?void 0:r.sequenceIndex)!=null?i:(a=r==null?void 0:r.agentContext)==null?void 0:a.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(e,r),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(e,r);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:e,payload:r,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((r,n)=>r[0]-n[0]);for(let[r,n]of e)this.buffer.delete(r),this.emitter(n.payloadType,n.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var lw="https://api.runtype.com/v1/dispatch",Yi="https://api.runtype.com";function dw(t){var s,a;let e=t.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(n)return`attachment.${n}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Wd=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function cw(t){switch(t){case"json":return Xi;case"regex-json":return Ki;case"xml":return Ji;default:return Gi}}var Bh=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function pw(t,e){if(!t)return e;let r=t.trim(),n=e.trim();if(r.length===0)return e;if(n.length===0)return t;let o=Bh(r);if(!Bh(n))return t;if(!o||n===r||n.startsWith(r))return e;let a=oa(t);return oa(e)!==null&&a===null?e:t}var aa=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,n,o,s;this.apiUrl=(r=e.apiUrl)!=null?r:lw,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:cw(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Pa(e.webmcp):null}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,r,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,r,n):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Yi}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,this.resetClientToolsFingerprint(),(r=(e=this.config).onSessionInit)==null||r.call(e,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Yi}/v1/client/feedback`}async sendFeedback(e){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:r})}async submitCSATFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:e,comment:r})}async submitNPSFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:e,comment:r})}async dispatch(e,r){return this.isAgentMode()?this.dispatchAgent(e,r):this.isClientTokenMode()?this.dispatchClientToken(e,r):this.dispatchProxy(e,r)}async dispatchClientToken(e,r){var o,s,a,i;let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let x=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:x}),x}let l=await this.buildPayload(e.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Wd).map(x=>{var b,h,M;return{id:x.id,role:x.role,content:(M=(h=(b=x.contentParts)!=null?b:x.llmContent)!=null?h:x.rawContent)!=null?M:x.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,f=!!(u&&u.length>0),y=f?Lh(u):void 0,A=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&A&&this.lastSentClientToolsFingerprint===y,T=!1,S=null,k;for(let x=0;;x++){let h={...m,...f&&(T||!E)&&u?{clientTools:u}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",h),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h),signal:n.signal}),k.status===409&&x===0&&f){let M=await k.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}S=M!=null?M:{error:"Chat request failed"}}break}if(!k.ok){let x=S!=null?S:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}if(k.status===429){let h=new Error(x.hint||"Message limit reached for this session.");throw r({type:"error",error:h}),h}let b=new Error(x.error||"Failed to send message");throw r({type:"error",error:b}),b}if(!k.body){let x=new Error("No response body received");throw r({type:"error",error:x}),x}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(k.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(e,r,n){r({type:"status",status:"connected"});try{await this.streamResponse(e,r,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(e,r){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Yi}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(e,r,n){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Yi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:r,streamResponse:(p=n==null?void 0:n.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(e){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Wd).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),n={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}return n}async buildPayload(e){var s;let n={messages:e.slice().filter(Wd).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...n},config:this.config});if(a&&typeof a=="object"){let i=a;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return n}async handleCustomSSEEvent(e,r,n,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return n.current=m,o(m),m},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),a.current=null,r({type:"status",status:"idle"})),i.error&&(a.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r,n){var fe,pe,Be,Q;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=N=>{let ke=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,He=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,Ve=N.tools?N.tools.map(Xe=>({...Xe,chunks:Xe.chunks?[...Xe.chunks]:void 0})):void 0;return{...N,reasoning:ke,toolCall:He,tools:Ve}},m=N=>{if(N.role!=="assistant"||N.variant)return!0;let ke=Array.isArray(N.contentParts)&&N.contentParts.length>0,He=typeof N.rawContent=="string"&&N.rawContent.trim()!=="";return typeof N.content=="string"&&N.content.trim()!==""||ke||He||!!N.stopReason},u=N=>{m(N)&&r({type:"message",message:p(N)})},f=null,y=null,A={current:null},E={current:null},T=!1,S=new Map,k=new Map,x=new Map,b=new Map,h={lastId:null,byStep:new Map},M={lastId:null,byCall:new Map},W=(N,ke,He="")=>`${N}::${ke}::${He}`,R=(N,ke)=>`${N}::${ke}::`,B=(N,ke,He,Ve)=>{let Xe=W(N,ke,He),gt=x.get(Xe);if(gt)return gt;let ot=He?`-${He}`:"",Mt={id:`nested-${N}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Ve,parentToolId:N,parentStepId:ke}};return x.set(Xe,Mt),u(Mt),Mt},_=N=>{if(N==null)return null;try{return String(N)}catch{return null}},V=N=>{var ke,He,Ve,Xe,gt;return _((gt=(Xe=(Ve=(He=(ke=N.stepId)!=null?ke:N.step_id)!=null?He:N.step)!=null?Ve:N.parentId)!=null?Xe:N.flowStepId)!=null?gt:N.flow_step_id)},oe=N=>{var ke,He,Ve,Xe,gt,ot,Mt;return _((Mt=(ot=(gt=(Xe=(Ve=(He=(ke=N.callId)!=null?ke:N.call_id)!=null?He:N.requestId)!=null?Ve:N.request_id)!=null?Xe:N.toolCallId)!=null?gt:N.tool_call_id)!=null?ot:N.stepId)!=null?Mt:N.step_id)},be=n,Qe=!1,je=()=>{if(f)return f;let N;return!Qe&&be?(N=be,Qe=!0):be&&E.current?N=`${be}_${E.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(f),f},ve=(N,ke)=>{h.lastId=ke,N&&h.byStep.set(N,ke)},Ee=(N,ke)=>{var gt;let He=(gt=N.reasoningId)!=null?gt:N.id,Ve=V(N);if(He){let ot=String(He);return ve(Ve,ot),ot}if(Ve){let ot=h.byStep.get(Ve);if(ot)return h.lastId=ot,ot}if(h.lastId&&!ke)return h.lastId;if(!ke)return null;let Xe=`reason-${l()}`;return ve(Ve,Xe),Xe},Ge=N=>{let ke=S.get(N);if(ke)return ke;let He={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:N,status:"streaming",chunks:[]}};return S.set(N,He),u(He),He},_e=(N,ke)=>{M.lastId=ke,N&&M.byCall.set(N,ke)},X=new Set,Ue=new Map,K=new Set,Te=new Map,ae=N=>{if(!N)return!1;let ke=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},xe=(N,ke)=>{var gt;let He=(gt=N.toolId)!=null?gt:N.id,Ve=oe(N);if(He){let ot=String(He);return _e(Ve,ot),ot}if(Ve){let ot=M.byCall.get(Ve);if(ot)return M.lastId=ot,ot}if(M.lastId&&!ke)return M.lastId;if(!ke)return null;let Xe=`tool-${l()}`;return _e(Ve,Xe),Xe},Me=N=>{let ke=k.get(N);if(ke)return ke;let He={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return k.set(N,He),u(He),He},Ke=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let ke=Number(N);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let He=Date.parse(N);if(!Number.isNaN(He))return He}return Date.now()},ce=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},re=new Map,le=new Map,ut=new Map,Ce=new Map,he=null,tt=(N,ke,He)=>{var Mt;let Ve=ut.get(N);Ve||(Ve=[],ut.set(N,Ve));let Xe=0,gt=Ve.length;for(;Xe<gt;){let Xt=Xe+gt>>>1;Ve[Xt].seq<ke?Xe=Xt+1:gt=Xt}((Mt=Ve[Xe])==null?void 0:Mt.seq)===ke?Ve[Xe]={seq:ke,text:He}:Ve.splice(Xe,0,{seq:ke,text:He});let ot="";for(let Xt=0;Xt<Ve.length;Xt++)ot+=Ve[Xt].text;return ot},Ne=(N,ke)=>{let He=ce(ke),Ve=le.get(N.id),Xe=pw(Ve,He);N.rawContent=Xe;let gt=re.get(N.id),ot=at=>{var de;let Nt=(de=N.content)!=null?de:"";at.trim()!==""&&(Nt.trim().length===0||at.startsWith(Nt)||at.trimStart().startsWith(Nt.trim()))&&(N.content=at)},Mt=()=>{var at;if(gt){let Nt=(at=gt.close)==null?void 0:at.call(gt);Nt instanceof Promise&&Nt.catch(()=>{})}re.delete(N.id),le.delete(N.id),N.streaming=!1,u(N)};if(!gt){ot(He),Mt();return}let Xt=oa(Xe);if(Xt!==null&&Xt.trim()!==""){ot(Xt),Mt();return}let G=at=>{var ye;let Nt=typeof at=="string"?at:(ye=at==null?void 0:at.text)!=null?ye:null;if(Nt!==null&&Nt.trim()!=="")return Nt;let de=gt.getExtractedText();return de!==null&&de.trim()!==""?de:He},Jt;try{Jt=gt.processChunk(Xe)}catch{ot(He),Mt();return}if(Jt instanceof Promise){Jt.then(at=>{ot(G(at)),Mt()}).catch(()=>{ot(He),Mt()});return}ot(G(Jt)),Mt()},me=[],J=!1,qe,Z=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,qe()}))},ge=new Qi((N,ke)=>{me.push({payloadType:N,payload:ke}),Z()}),q=null,Re=new Map,Ae=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(qe=()=>{var N,ke,He,Ve,Xe,gt,ot,Mt,Xt,G,Jt,at,Nt,de,ye,Rt,ar,kt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,P,ee,Se,rt,Qt,Ft,tr,Pr,_r,wn,Vt,$t,Ir,vn,bo,eo,wo,zn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn,I,pn,Bn,to,qn,Xa,Hn,Dn,On,ro,Fo,ri,Ja,ni,ha,Lt,Qa,An,tn,oi,ai,xa,no,si,$o,Ya,oo,Za,Co,Ao,ii,li,rd,Uo,So,di,es,To,ci,ts,Mo,rs,pi,ao,ui,ko,Kt,ya,ba,ns,Vn,fi,os,as,mi,wa,va,zo,gi,hi,ss,is,ls,ds,qr,un,so,yt,cs,qo,_n,xi;for(let Eo=0;Eo<me.length;Eo++){let st=me[Eo].payloadType,L=me[Eo].payload;if(st==="reason_start"){let z=(N=Ee(L,!0))!=null?N:`reason-${l()}`,O=Ge(z);O.reasoning=(ke=O.reasoning)!=null?ke:{id:z,status:"streaming",chunks:[]},O.reasoning.startedAt=(Ve=O.reasoning.startedAt)!=null?Ve:Ke((He=L.startedAt)!=null?He:L.timestamp),O.reasoning.completedAt=void 0,O.reasoning.durationMs=void 0,O.streaming=!0,O.reasoning.status="streaming",u(O)}else if(st==="reason_delta"||st==="reason_chunk"){let z=(gt=(Xe=Ee(L,!1))!=null?Xe:Ee(L,!0))!=null?gt:`reason-${l()}`,O=Ge(z);O.reasoning=(ot=O.reasoning)!=null?ot:{id:z,status:"streaming",chunks:[]},O.reasoning.startedAt=(Xt=O.reasoning.startedAt)!=null?Xt:Ke((Mt=L.startedAt)!=null?Mt:L.timestamp);let se=(at=(Jt=(G=L.reasoningText)!=null?G:L.text)!=null?Jt:L.delta)!=null?at:"";if(se&&L.hidden!==!0){let Y=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(Y!==void 0){let te=tt(z,Y,String(se));O.reasoning.chunks=[te]}else O.reasoning.chunks.push(String(se))}if(O.reasoning.status=L.done?"complete":"streaming",L.done){O.reasoning.completedAt=Ke((Nt=L.completedAt)!=null?Nt:L.timestamp);let Y=(de=O.reasoning.startedAt)!=null?de:Date.now();O.reasoning.durationMs=Math.max(0,((ye=O.reasoning.completedAt)!=null?ye:Date.now())-Y)}O.streaming=O.reasoning.status!=="complete",u(O)}else if(st==="reason_complete"){let z=(ar=(Rt=Ee(L,!1))!=null?Rt:Ee(L,!0))!=null?ar:`reason-${l()}`,O=S.get(z);if(O!=null&&O.reasoning){O.reasoning.status="complete",O.reasoning.completedAt=Ke((kt=L.completedAt)!=null?kt:L.timestamp);let Y=(mr=O.reasoning.startedAt)!=null?mr:Date.now();O.reasoning.durationMs=Math.max(0,((Ot=O.reasoning.completedAt)!=null?Ot:Date.now())-Y),O.streaming=!1,u(O)}let se=V(L);se&&h.byStep.delete(se)}else if(st==="tool_start"){let z=(Wt=xe(L,!0))!=null?Wt:`tool-${l()}`,O=(St=L.toolName)!=null?St:L.name;if(ae(O)){X.add(z);continue}let se=Me(z),Y=(Et=se.toolCall)!=null?Et:{id:z,status:"pending"};Y.name=O!=null?O:Y.name,Y.status="running",L.args!==void 0?Y.args=L.args:L.parameters!==void 0&&(Y.args=L.parameters),Y.startedAt=(ft=Y.startedAt)!=null?ft:Ke((sr=L.startedAt)!=null?sr:L.timestamp),Y.completedAt=void 0,Y.durationMs=void 0,se.toolCall=Y,se.streaming=!0;let te=L.agentContext;(te||L.executionId)&&(se.agentMetadata={executionId:(dr=te==null?void 0:te.executionId)!=null?dr:L.executionId,iteration:(wr=te==null?void 0:te.iteration)!=null?wr:L.iteration}),u(se)}else if(st==="tool_chunk"||st==="tool_delta"){let z=(Or=(Lr=xe(L,!1))!=null?Lr:xe(L,!0))!=null?Or:`tool-${l()}`;if(X.has(z))continue;let O=Me(z),se=(xt=O.toolCall)!=null?xt:{id:z,status:"running"};se.startedAt=(fr=se.startedAt)!=null?fr:Ke((sn=L.startedAt)!=null?sn:L.timestamp);let Y=(Zn=(Rr=(Un=L.text)!=null?Un:L.delta)!=null?Rr:L.message)!=null?Zn:"";Y&&(se.chunks=(Pn=se.chunks)!=null?Pn:[],se.chunks.push(String(Y))),se.status="running",O.toolCall=se,O.streaming=!0;let te=L.agentContext;(te||L.executionId)&&(O.agentMetadata=(P=O.agentMetadata)!=null?P:{executionId:(In=te==null?void 0:te.executionId)!=null?In:L.executionId,iteration:(ue=te==null?void 0:te.iteration)!=null?ue:L.iteration}),u(O)}else if(st==="tool_complete"){let z=(Se=(ee=xe(L,!1))!=null?ee:xe(L,!0))!=null?Se:`tool-${l()}`;if(X.has(z)){X.delete(z);continue}let O=Me(z),se=(rt=O.toolCall)!=null?rt:{id:z,status:"running"};se.status="complete",L.result!==void 0&&(se.result=L.result),typeof L.duration=="number"&&(se.duration=L.duration),se.completedAt=Ke((Qt=L.completedAt)!=null?Qt:L.timestamp);let Y=(Ft=L.duration)!=null?Ft:L.executionTime;if(typeof Y=="number")se.durationMs=Y;else{let et=(tr=se.startedAt)!=null?tr:Date.now();se.durationMs=Math.max(0,((Pr=se.completedAt)!=null?Pr:Date.now())-et)}O.toolCall=se,O.streaming=!1;let te=L.agentContext;(te||L.executionId)&&(O.agentMetadata=(Vt=O.agentMetadata)!=null?Vt:{executionId:(_r=te==null?void 0:te.executionId)!=null?_r:L.executionId,iteration:(wn=te==null?void 0:te.iteration)!=null?wn:L.iteration}),u(O);let ct=oe(L);ct&&M.byCall.delete(ct)}else if(st==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let z=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,O=($t=z!=null?z:L.toolId)!=null?$t:`local-${l()}`,se=Me(O),Y=(Ir=se.toolCall)!=null?Ir:{id:O,status:"pending"};Y.name=L.toolName,Y.args=L.parameters,Y.status="complete",Y.chunks=(vn=Y.chunks)!=null?vn:[],Y.startedAt=(eo=Y.startedAt)!=null?eo:Ke((bo=L.startedAt)!=null?bo:L.timestamp),Y.completedAt=(wo=Y.completedAt)!=null?wo:Y.startedAt,se.toolCall=Y,se.streaming=!1,se.agentMetadata={...se.agentMetadata,executionId:(ln=L.executionId)!=null?ln:(zn=se.agentMetadata)==null?void 0:zn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},u(se)}else if(st==="text_start"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let z=L.partId;if(z!==void 0&&E.current!==null&&z!==E.current){let O=f;O&&(O.streaming=!1,u(O),he=O,f=null,T=!0)}z!==void 0&&(E.current=z)}else if(st==="text_end"){if((Pt=L.toolContext)!=null&&Pt.toolId)continue;let z=f;z&&(z.streaming=!1,u(z),he=z,f=null,T=!0)}else if(st==="step_chunk"||st==="step_delta"){let z=L.stepType,O=L.executionType;if(z==="tool"||O==="context")continue;let se=L.toolContext;if(se!=null&&se.toolId){let et=String((hr=(gr=L.id)!=null?gr:se.stepId)!=null?hr:`step-${l()}`),mt=L.partId!==void 0&&L.partId!==null?String(L.partId):"",Fe=`${se.toolId}::${et}`,lt=b.get(Fe);if(mt!==""&&lt!==void 0&&lt!==""&&lt!==mt){let _t=x.get(W(se.toolId,et,lt));_t&&_t.streaming!==!1&&(_t.streaming=!1,u(_t))}mt!==""&&b.set(Fe,mt);let jt=B(se.toolId,et,mt,se.executionId),Sr=(Wn=(Cn=(vo=(dn=L.text)!=null?dn:L.delta)!=null?vo:L.content)!=null?Cn:L.chunk)!=null?Wn:"";Sr&&(jt.content+=String(Sr),jt.streaming=!0,u(jt)),L.isComplete&&(jt.streaming=!1,u(jt));continue}let Y=L.partId;if(Y!==void 0&&E.current!==null&&Y!==E.current){let et=f;et&&(et.streaming=!1,u(et),he=et,f=null,T=!0)}Y!==void 0&&(E.current=Y);let te=Y!==void 0&&(cn=Ce.get(Y))!=null?cn:je();Y!==void 0&&(te.partId||(te.partId=Y),Ce.set(Y,te));let ct=(to=(Bn=(pn=(I=L.text)!=null?I:L.delta)!=null?pn:L.content)!=null?Bn:L.chunk)!=null?to:"";if(ct){let et=typeof L.seq=="number"?L.seq:void 0,mt=Y!=null?Y:te.id,Fe=et!==void 0?tt(mt,et,String(ct)):((qn=le.get(te.id))!=null?qn:"")+ct;te.rawContent=Fe,re.has(te.id)||re.set(te.id,this.createStreamParser());let lt=re.get(te.id),jt=Fe.trim().startsWith("{")||Fe.trim().startsWith("[");if(jt&&le.set(te.id,Fe),lt.__isPlainTextParser===!0){te.content=et!==void 0?Fe:te.content+ct,le.delete(te.id),re.delete(te.id),te.rawContent=void 0,u(te);continue}let _t=lt.processChunk(Fe);if(_t instanceof Promise)_t.then(zt=>{var Nr;let Tr=typeof zt=="string"?zt:(Nr=zt==null?void 0:zt.text)!=null?Nr:null;if(Tr!==null&&Tr.trim()!=="")te.content=Tr,u(te);else if(!jt&&!Fe.trim().startsWith("<")){let Vr=f,xr=Vr&&Vr.id===te.id?Vr:te;xr.id===te.id&&(xr.content=et!==void 0?Fe:xr.content+ct,le.delete(xr.id),re.delete(xr.id),xr.rawContent=void 0,u(xr))}}).catch(()=>{te.content=et!==void 0?Fe:te.content+ct,le.delete(te.id),re.delete(te.id),te.rawContent=void 0,u(te)});else{let zt=typeof _t=="string"?_t:(Xa=_t==null?void 0:_t.text)!=null?Xa:null;zt!==null&&zt.trim()!==""?(te.content=zt,u(te)):!jt&&!Fe.trim().startsWith("<")&&(te.content=et!==void 0?Fe:te.content+ct,le.delete(te.id),re.delete(te.id),te.rawContent=void 0,u(te))}}if(L.isComplete){let et=(Dn=(Hn=L.result)==null?void 0:Hn.response)!=null?Dn:te.content;if(et){let mt=le.get(te.id),Fe=mt!=null?mt:ce(et);te.rawContent=Fe;let lt=re.get(te.id),jt=null,Sr=!1;if(lt&&(jt=lt.getExtractedText(),jt===null&&(jt=oa(Fe)),jt===null)){let _t=lt.processChunk(Fe);_t instanceof Promise?(Sr=!0,_t.then(zt=>{var Nr;let Tr=typeof zt=="string"?zt:(Nr=zt==null?void 0:zt.text)!=null?Nr:null;if(Tr!==null){let Vr=f;Vr&&Vr.id===te.id&&(Vr.content=Tr,Vr.streaming=!1,re.delete(Vr.id),le.delete(Vr.id),u(Vr))}})):jt=typeof _t=="string"?_t:(On=_t==null?void 0:_t.text)!=null?On:null}if(!Sr){jt!==null&&jt.trim()!==""?te.content=jt:le.has(te.id)||(te.content=ce(et));let _t=re.get(te.id);if(_t){let zt=(ro=_t.close)==null?void 0:ro.call(_t);zt instanceof Promise&&zt.catch(()=>{}),re.delete(te.id)}le.delete(te.id),te.streaming=!1,u(te)}}}}else if(st==="step_complete"){let z=L.stepType,O=L.executionType;if(z==="tool"||O==="context")continue;let se=L.toolContext;if(se!=null&&se.toolId){let et=String((ri=(Fo=L.id)!=null?Fo:se.stepId)!=null?ri:"");if(et){let mt=R(se.toolId,et);for(let[Fe,lt]of x)Fe.startsWith(mt)&&lt.streaming!==!1&&(lt.streaming=!1,u(lt));b.delete(`${se.toolId}::${et}`)}continue}let Y=L.stopReason;if(T){if(f!==null){let Fe=f;Y&&(Fe.stopReason=Y),re.delete(Fe.id),le.delete(Fe.id),Fe.streaming!==!1&&(Fe.streaming=!1,u(Fe))}let et=(Ja=L.result)==null?void 0:Ja.response,mt=he;mt&&(Y&&(mt.stopReason=Y),et!=null?Ne(mt,et):(re.delete(mt.id),le.delete(mt.id))),he=null;continue}let te=(ni=L.result)==null?void 0:ni.response,ct=je();if(Y&&(ct.stopReason=Y),te!=null){let et=re.get(ct.id),mt=!1,Fe=!1;if(et){let lt=et.getExtractedText(),jt=le.get(ct.id),Sr=jt!=null?jt:ce(te);if(ct.rawContent=Sr,lt!==null&&lt.trim()!=="")ct.content=lt,mt=!0;else{let _t=oa(Sr);if(_t!==null)ct.content=_t,mt=!0;else{let zt=et.processChunk(Sr);if(zt instanceof Promise)Fe=!0,zt.then(Tr=>{var Vr;let Nr=typeof Tr=="string"?Tr:(Vr=Tr==null?void 0:Tr.text)!=null?Vr:null;if(Nr!==null&&Nr.trim()!==""){let xr=f;xr&&xr.id===ct.id&&(xr.content=Nr,xr.streaming=!1,re.delete(xr.id),le.delete(xr.id),u(xr))}else{let xr=et.getExtractedText(),Sn=f;Sn&&Sn.id===ct.id&&(xr!==null&&xr.trim()!==""?Sn.content=xr:le.has(Sn.id)||(Sn.content=ce(te)),Sn.streaming=!1,re.delete(Sn.id),le.delete(Sn.id),u(Sn))}});else{let Tr=typeof zt=="string"?zt:(ha=zt==null?void 0:zt.text)!=null?ha:null;if(Tr!==null&&Tr.trim()!=="")ct.content=Tr,mt=!0;else{let Nr=et.getExtractedText();Nr!==null&&Nr.trim()!==""&&(ct.content=Nr,mt=!0)}}}}}if(!Fe){if(!ct.rawContent){let lt=le.get(ct.id);ct.rawContent=lt!=null?lt:ce(te)}if(!mt&&!le.has(ct.id)&&(ct.content=ce(te)),et){let lt=(Lt=et.close)==null?void 0:Lt.call(et);lt instanceof Promise&&lt.catch(()=>{})}re.delete(ct.id),le.delete(ct.id),ct.streaming=!1,u(ct)}}else re.delete(ct.id),le.delete(ct.id),ct.streaming=!1,u(ct)}else if(st==="flow_complete"){let z=(Qa=L.result)==null?void 0:Qa.response;if(T){if(f!==null){let O=f;re.delete(O.id),le.delete(O.id),O.streaming!==!1&&(O.streaming=!1,u(O))}}else if(z!=null){let O=je(),se=le.get(O.id),Y=se!=null?se:ce(z);O.rawContent=Y;let te=ce(z),ct=re.get(O.id);if(ct){let Fe=oa(Y);if(Fe!==null)te=Fe;else{let lt=ct.processChunk(Y);lt instanceof Promise&&lt.then(Sr=>{var zt;let _t=typeof Sr=="string"?Sr:(zt=Sr==null?void 0:Sr.text)!=null?zt:null;_t!==null&&(O.content=_t,O.streaming=!1,u(O))});let jt=ct.getExtractedText();jt!==null&&(te=jt)}}re.delete(O.id),le.delete(O.id);let et=te!==O.content,mt=O.streaming!==!1;et&&(O.content=te),O.streaming=!1,(et||mt)&&u(O)}else if(f!==null){let O=f;re.delete(O.id),le.delete(O.id),O.streaming!==!1&&(O.streaming=!1,u(O))}r({type:"status",status:"idle"})}else if(st==="agent_start")q={executionId:L.executionId,agentId:(An=L.agentId)!=null?An:"virtual",agentName:(tn=L.agentName)!=null?tn:"",status:"running",currentIteration:0,maxTurns:(oi=L.maxTurns)!=null?oi:1,startedAt:Ke(L.startedAt)};else if(st==="agent_iteration_start"){if(q&&(q.currentIteration=L.iteration),Ae==="separate"&&L.iteration>1){let z=f;z&&(z.streaming=!1,u(z),Re.set(L.iteration-1,z),f=null)}}else if(st==="agent_turn_start")y=null;else if(st==="agent_turn_delta"){if(L.contentType==="text"){let z=je();z.content+=(ai=L.delta)!=null?ai:"",z.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:q==null?void 0:q.agentName},y=z,u(z)}else if(L.contentType==="thinking"){let z=(xa=L.turnId)!=null?xa:`agent-think-${L.iteration}`,O=Ge(z);O.reasoning=(no=O.reasoning)!=null?no:{id:z,status:"streaming",chunks:[]},O.reasoning.chunks.push((si=L.delta)!=null?si:""),O.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(O)}else if(L.contentType==="tool_input"){let z=($o=L.toolCallId)!=null?$o:M.lastId;if(z){let O=k.get(z);O!=null&&O.toolCall&&(O.toolCall.chunks=(Ya=O.toolCall.chunks)!=null?Ya:[],O.toolCall.chunks.push((oo=L.delta)!=null?oo:""),u(O))}}}else if(st==="agent_turn_complete"){let z=L.turnId;if(z){let Y=S.get(z);if(Y!=null&&Y.reasoning){Y.reasoning.status="complete",Y.reasoning.completedAt=Ke(L.completedAt);let te=(Za=Y.reasoning.startedAt)!=null?Za:Date.now();Y.reasoning.durationMs=Math.max(0,((Co=Y.reasoning.completedAt)!=null?Co:Date.now())-te),Y.streaming=!1,u(Y)}}let O=L.stopReason,se=f!=null?f:y;if(O&&se!==null){let Y=L.turnId;(!Y||((Ao=se.agentMetadata)==null?void 0:Ao.turnId)===Y)&&(se.stopReason=O,u(se))}}else if(st==="agent_tool_start"){f&&(f.streaming=!1,u(f),f=null);let z=(ii=L.toolCallId)!=null?ii:`agent-tool-${l()}`;_e(oe(L),z);let O=Me(z),se=(li=O.toolCall)!=null?li:{id:z,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};se.name=(Uo=(rd=L.toolName)!=null?rd:L.name)!=null?Uo:se.name,se.status="running",L.parameters!==void 0&&(se.args=L.parameters),se.startedAt=Ke((So=L.startedAt)!=null?So:L.timestamp),O.toolCall=se,O.streaming=!0,O.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(O)}else if(st==="agent_tool_delta"){let z=(di=L.toolCallId)!=null?di:M.lastId;if(z){let O=(es=k.get(z))!=null?es:Me(z);O.toolCall&&(O.toolCall.chunks=(To=O.toolCall.chunks)!=null?To:[],O.toolCall.chunks.push((ci=L.delta)!=null?ci:""),O.toolCall.status="running",O.streaming=!0,u(O))}}else if(st==="agent_tool_complete"){let z=(ts=L.toolCallId)!=null?ts:M.lastId;if(z){let O=(Mo=k.get(z))!=null?Mo:Me(z);if(O.toolCall){O.toolCall.status="complete",L.result!==void 0&&(O.toolCall.result=L.result),typeof L.executionTime=="number"&&(O.toolCall.durationMs=L.executionTime),O.toolCall.completedAt=Ke((rs=L.completedAt)!=null?rs:L.timestamp),O.streaming=!1,u(O);let se=oe(L);se&&M.byCall.delete(se)}}}else if(st==="agent_media"){let z=Array.isArray(L.media)?L.media:[],O=[];for(let se of z){if(!se||typeof se!="object")continue;let Y=se,te=typeof Y.type=="string"?Y.type:void 0,ct=typeof Y.mediaType=="string"?Y.mediaType.toLowerCase():"",et=null,mt="";if(te==="media"){let Fe=typeof Y.data=="string"?Y.data:void 0;if(!Fe)continue;mt=ct.length>0?ct:"application/octet-stream",et=`data:${mt};base64,${Fe}`}else if(te==="image-url"){let Fe=typeof Y.url=="string"?Y.url:void 0;if(!Fe)continue;mt=ct,et=Fe}else if(te==="file-url"){let Fe=typeof Y.url=="string"?Y.url:void 0;if(!Fe)continue;mt=ct,et=Fe}else continue;if(et)if(te==="image-url"||mt.startsWith("image/"))O.push({type:"image",image:et,...mt?{mimeType:mt}:{}});else if(mt.startsWith("audio/"))O.push({type:"audio",audio:et,mimeType:mt});else if(mt.startsWith("video/"))O.push({type:"video",video:et,mimeType:mt});else{let Fe=mt||"application/octet-stream";O.push({type:"file",data:et,mimeType:Fe,filename:dw(Fe)})}}if(O.length>0){let se=l(),Y=L.toolCallId,ct={id:`agent-media-${typeof Y=="string"&&Y.length>0?`${Y}-${se}`:String(se)}`,role:"assistant",content:"",contentParts:O,createdAt:new Date().toISOString(),streaming:!1,sequence:se,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(ct);let et=f;et&&(et.streaming=!1,u(et)),f=null,A.current=null}}else if(st!=="agent_iteration_complete"){if(st==="agent_reflection"||st==="agent_reflect"){let z=`agent-reflection-${L.executionId}-${L.iteration}`,O={id:z,role:"assistant",content:(pi=L.reflection)!=null?pi:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(ao=L.reflection)!=null?ao:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(O)}else if(st==="agent_complete"){q&&(q.status=L.success?"complete":"error",q.completedAt=Ke(L.completedAt),q.stopReason=L.stopReason);let z=f;z&&(z.streaming=!1,u(z)),r({type:"status",status:"idle"})}else if(st==="agent_error"){let z=typeof L.error=="string"?L.error:(ko=(ui=L.error)==null?void 0:ui.message)!=null?ko:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):r({type:"error",error:new Error(z)})}else if(st!=="agent_ping"){if(st==="agent_approval_start"){let z=(Kt=L.approvalId)!=null?Kt:`approval-${l()}`,O={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(ya=q==null?void 0:q.agentId)!=null?ya:"virtual",executionId:(ns=(ba=L.executionId)!=null?ba:q==null?void 0:q.executionId)!=null?ns:"",toolName:(Vn=L.toolName)!=null?Vn:"",toolType:L.toolType,description:(os=L.description)!=null?os:`Execute ${(fi=L.toolName)!=null?fi:"tool"}`,parameters:L.parameters}};u(O)}else if(st==="step_await"&&L.awaitReason==="approval_required"){let z=(as=L.approvalId)!=null?as:`approval-${l()}`,O={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(mi=q==null?void 0:q.agentId)!=null?mi:"virtual",executionId:(va=(wa=L.executionId)!=null?wa:q==null?void 0:q.executionId)!=null?va:"",toolName:(zo=L.toolName)!=null?zo:"",toolType:L.toolType,description:(hi=L.description)!=null?hi:`Execute ${(gi=L.toolName)!=null?gi:"tool"}`,parameters:L.parameters}};u(O)}else if(st==="agent_approval_complete"){let z=L.approvalId;if(z){let se={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(ss=L.decision)!=null?ss:"approved",agentId:(is=q==null?void 0:q.agentId)!=null?is:"virtual",executionId:(ds=(ls=L.executionId)!=null?ls:q==null?void 0:q.executionId)!=null?ds:"",toolName:(qr=L.toolName)!=null?qr:"",description:(un=L.description)!=null?un:"",resolvedAt:Date.now()}};u(se)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let z=L.artifactType,O=String(L.id),se=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:O,artifactType:z,title:se,component:typeof L.component=="string"?L.component:void 0}),Te.set(O,{markdown:"",title:se}),!K.has(O)){K.add(O);let Y={id:`artifact-ref-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:O,title:se,artifactType:z,status:"streaming"}})};Ue.set(O,Y),u(Y)}}else if(st==="artifact_delta"){let z=String(L.id),O=typeof L.delta=="string"?L.delta:String((so=L.delta)!=null?so:"");r({type:"artifact_delta",id:z,artDelta:O});let se=Te.get(z);se&&(se.markdown+=O)}else if(st==="artifact_update"){let z=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:z,component:typeof L.component=="string"?L.component:void 0})}else if(st==="artifact_complete"){let z=String(L.id);r({type:"artifact_complete",id:z});let O=Ue.get(z);if(O){O.streaming=!1;try{let se=JSON.parse((yt=O.rawContent)!=null?yt:"{}");if(se.props){se.props.status="complete";let Y=Te.get(z);Y!=null&&Y.markdown&&(se.props.markdown=Y.markdown)}O.rawContent=JSON.stringify(se)}catch{}Te.delete(z),u(O),Ue.delete(z)}}}else if(st==="transcript_insert"){let z=L.message;if(!z||typeof z!="object")continue;let O=String((cs=z.id)!=null?cs:`msg-${l()}`),se=z.role,te={id:O,role:se==="user"?"user":se==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(u(te),te.rawContent)try{let ct=JSON.parse(te.rawContent),et=(qo=ct==null?void 0:ct.props)==null?void 0:qo.artifactId;typeof et=="string"&&K.add(et)}catch{}f=null,A.current=null,re.delete(O),le.delete(O)}else if(st==="error"||st==="step_error"||st==="dispatch_error"||st==="flow_error"){let z=null;if(L.error instanceof Error)z=L.error;else if(st==="dispatch_error"){let O=(_n=L.message)!=null?_n:L.error;O!=null&&O!==""&&(z=new Error(String(O)))}else if(st==="step_error"||st==="flow_error"){let O=L.error;typeof O=="string"&&O!==""?z=new Error(O):O!=null&&typeof O=="object"&&"message"in O&&(z=new Error(String((xi=O.message)!=null?xi:O)))}else st==="error"&&L.error!=null&&L.error!==""&&(z=new Error(String(L.error)));if(z){r({type:"error",error:z});let O=f;O&&O.streaming&&(O.streaming=!1,u(O)),r({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:N,value:ke}=await o.read();if(N)break;a+=s.decode(ke,{stream:!0});let He=a.split(`
60
60
 
61
- `);a=(ge=qe.pop())!=null?ge:"";for(let tt of qe){let Xe=tt.split(`
62
- `),Je="message",pt="";for(let or of Xe)or.startsWith("event:")?Je=or.replace("event:","").trim():or.startsWith("data:")&&(pt+=or.replace("data:","").trim());if(!pt)continue;let ht;try{ht=JSON.parse(pt)}catch(or){r({type:"error",error:or instanceof Error?or:new Error("Failed to parse chat stream payload")});continue}let zt=Je!=="message"?Je:(ue=ht.type)!=null?ue:"message";if((_e=this.onSSEEvent)==null||_e.call(this,zt,ht),this.parseSSEEvent){y.current=f;let or=await this.handleCustomSSEEvent(ht,r,y,u,l,v);if(y.current&&y.current!==f&&(f=y.current),or)continue}ne.push(zt,ht),J()}}ne.flushPending(),J(),ne.destroy()}};function Vh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function is(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var rl="[Image]";function Gh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Kh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Jh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Xh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ba(e){return{type:"text",text:e}}function Yh(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Qh(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}function Zh(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var ex=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Hw=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],mo=[...ex,...Hw];function Bw(e){return ex.includes(e)||e.startsWith("image/")}function nl(e){return Bw(e.type)}async function tx(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;nl(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}function rx(e,t=mo,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Dw(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function nx(e,t){let r=Dw(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var ol=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let n=r.AudioContext||r.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(r),s=n.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=n.createBufferSource();a.buffer=s,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),n=new Float32Array(r),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<r;s++){let a=o.getInt16(s*2,!0);n[s]=a/32768}return n}};var sl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,r,n,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(r),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Da=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new sl;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,r,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(r=this.config)==null?void 0:r.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let y=!1,v=T=>{y||(y=!0,clearTimeout(E),m(new Error(T)))},E=setTimeout(()=>v("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!y){let A=T.code!==1006?` (code ${T.code})`:"";v("WebSocket connection failed"+A+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let r=JSON.parse(t.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var r,n;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(r=t.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(n=t.response.audio)!=null&&n.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ol(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,r,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,n=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(r=>r(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((r,n)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];r(a)},o.onerror=n,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let r=atob(t.base64),n=new Uint8Array(r.length);for(let l=0;l<r.length;l++)n[l]=r.charCodeAt(l);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([n],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var ls=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ds(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Da(e.runtype);case"browser":if(!ls.isSupported())throw new Error("Browser speech recognition not supported");return new ls(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function al(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ds({type:"runtype",runtype:e.runtype});if(ls.isSupported())return ds({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Oa(e){try{return al(e),!0}catch{return!1}}function ox(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}
61
+ `);a=(pe=He.pop())!=null?pe:"";for(let Ve of He){let Xe=Ve.split(`
62
+ `),gt="message",ot="";for(let G of Xe)G.startsWith("event:")?gt=G.replace("event:","").trim():G.startsWith("data:")&&(ot+=G.replace("data:","").trim());if(!ot)continue;let Mt;try{Mt=JSON.parse(ot)}catch(G){r({type:"error",error:G instanceof Error?G:new Error("Failed to parse chat stream payload")});continue}let Xt=gt!=="message"?gt:(Be=Mt.type)!=null?Be:"message";if((Q=this.onSSEEvent)==null||Q.call(this,Xt,Mt),this.parseSSEEvent){A.current=f;let G=await this.handleCustomSSEEvent(Mt,r,A,u,l,E);if(A.current&&A.current!==f&&(f=A.current),G)continue}ge.push(Xt,Mt),qe()}}ge.flushPending(),qe(),ge.destroy()}};function Hh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${t}_${e}`}function Ra(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function sa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Zi="[Image]";function Dh(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Oh(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function _h(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Nh(t){return typeof t=="string"?[]:t.filter(e=>e.type==="image")}function Rs(t){return{type:"text",text:t}}function Fh(t,e){return{type:"image",image:t,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function $h(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;e({type:"image",image:o,mimeType:t.type,alt:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function Uh(t,e=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var zh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],uw=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],mo=[...zh,...uw];function fw(t){return zh.includes(t)||t.startsWith("image/")}function el(t){return fw(t.type)}async function qh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;el(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function Vh(t,e=mo,r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function mw(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function jh(t,e){let r=mw(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var tl=class{constructor(e=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=e}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let n=r.AudioContext||r.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let r=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(r),s=n.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=n.createBufferSource();a.buffer=s,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of e)r()}}pcmToFloat32(e){let r=Math.floor(e.length/2),n=new Float32Array(r),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<r;s++){let a=o.getInt16(s*2,!0);n[s]=a/32768}return n}};var rl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,r,n,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(r),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ws=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new rl;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,r,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(e=this.config)==null?void 0:e.host,i=(r=this.config)==null?void 0:r.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((u,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let y=!1,A=T=>{y||(y=!0,clearTimeout(E),f(new Error(T)))},E=setTimeout(()=>A("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(E),u())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!y){let S=T.code!==1006?` (code ${T.code})`:"";A("WebSocket connection failed"+S+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let r=JSON.parse(e.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var r,n;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(r=e.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(e.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(n=e.response.audio)!=null&&n.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(e.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new tl(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var e,r,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(r=(e=this.config)==null?void 0:e.pauseDuration)!=null?r:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(u=>u("processing")),this.processingStartCallbacks.forEach(u=>u());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,n=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(r=>r(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(e),o=this.getFormatFromMimeType(e.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((r,n)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];r(a)},o.onerror=n,o.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let r=atob(e.base64),n=new Uint8Array(r.length);for(let l=0;l<r.length;l++)n[l]=r.charCodeAt(l);let o=e.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([n],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var ia=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function la(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Ws(t.runtype);case"browser":if(!ia.isSupported())throw new Error("Browser speech recognition not supported");return new ia(t.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function nl(t){if((t==null?void 0:t.type)==="runtype"&&t.runtype)return la({type:"runtype",runtype:t.runtype});if(ia.isSupported())return la({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Bs(t){try{return nl(t),!0}catch{return!1}}function Gh(t,e){let r=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(r);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}
63
63
 
64
- _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var r,n,o,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((r=t.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Ra(p.name)&&this.enqueueWebMcpAwait(t.message),(n=t.message.agentMetadata)!=null&&n.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(o=t.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var n,o;this.messages=[...(n=t.initialMessages)!=null?n:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new as(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Oa((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,n;return(n=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?n:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var r,n,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=ds(s);let a=(r=this.config.voiceRecognition)!=null?r:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,u,f,m,y,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(y=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:y.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,n,o,s,a,i,d,l,p;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=t.runtype)==null?void 0:n.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(r=(t=this.callbacks).onError)==null||r.call(t,n instanceof Error?n:new Error(String(n))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new as(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:n,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,m={id:a!=null?a:r==="user"?Bs():r==="assistant"?is():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let n of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:m}=n,v={id:d!=null?d:o==="user"?Bs():o==="assistant"?is():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};r.push(v)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:n={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:r,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,r){var l,p,u,f,m;let n=t.trim();if(!n&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Bs(),s=is(),a={id:o,role:"user",content:n||rl,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){let v=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!v){let E=ox(y,this.config.errorMessage);if(E){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(y instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,y):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=is();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=ox(l,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,r){var o,s,a;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(t,r){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:r,resolvedAt:Date.now()}}),n(r==="approved")}async resolveApproval(t,r){var d,l,p,u;let n=`approval-${t.id}`,o={...t,status:r,resolvedAt:Date.now()},s={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),f){let m=null;if(f instanceof Response){if(!f.ok){let y=await f.json().catch(()=>null);throw new Error((l=y==null?void 0:y.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,r){let n=this.messages.find(o=>o.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let n=this.messages.find(o=>o.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,u,f,m,y,v,E,T,A,M,b,w;let n=this.messages.find(h=>h.id===t.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof r=="string"?void 0:r;if(a===void 0&&typeof r=="string"){let h=(v=t.toolCall)==null?void 0:v.args,k=Array.isArray(h==null?void 0:h.questions)?h.questions:[];if(k.length===1){let B=typeof((E=k[0])==null?void 0:E.question)=="string"?k[0].question:"";B&&(a={[B]:r})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(A=t.toolCall)==null?void 0:A.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let h=typeof r=="string"?r:Object.entries(r).map(([k,B])=>`${k}: ${Array.isArray(B)?B.join(", "):B}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let h=a!=null?a:{};l.forEach((k,B)=>{let H=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!H)return;let W=h[H],N=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${B}`,role:"assistant",content:H,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${B}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let h=await this.client.resumeFlow(o,{[s]:r});if(!h.ok){let k=await h.json().catch(()=>null);throw new Error((M=k==null?void 0:k.error)!=null?M:`Resume failed: ${h.status}`)}h.body?await this.connectStream(h.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(h){let k=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(w=(b=this.callbacks).onError)==null||w.call(b,h instanceof Error?h:new Error(String(h)))}}enqueueWebMcpAwait(t){var s,a;let r=(s=t.agentMetadata)==null?void 0:s.executionId,n=(a=t.toolCall)==null?void 0:a.id;if(!r||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(r);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,o)),!o.seen.has(n)&&(o.seen.add(n),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=r;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}async resolveWebMcpToolCallBatch(t,r){var i,d,l;let n=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(r.map(async p=>{var A,M,b,w,h,k,B;let u=(A=p.toolCall)==null?void 0:A.name,f=(M=p.toolCall)==null?void 0:M.id;if(!u||!f)return null;let m=`${t}:${f}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),n.push(m),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let y=new AbortController;this.webMcpResolveControllers.add(y),o.push(y);let v=(w=(b=p.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?w:u,E=this.client.executeWebMcpToolCall(u,(h=p.toolCall)==null?void 0:h.args,y.signal),T;if(!E)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await E}catch(H){return H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"))||(B=(k=this.callbacks).onError)==null||B.call(k,H instanceof Error?H:new Error(String(H))),this.webMcpInflightKeys.delete(m),null}return y.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:v,output:T}}));try{let p=a.filter(m=>m!==null);if(p.length===0)return;let u={};for(let m of p)u[m.resumeKey]=m.output;let f=await this.client.resumeFlow(t,u,{signal:s.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${f.status}`)}for(let m of p)this.webMcpResolvedKeys.add(m.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of n)this.webMcpInflightKeys.delete(p);for(let p of o)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,u,f,m,y,v,E,T,A,M,b,w;let r=(p=t.agentMetadata)==null?void 0:p.executionId,n=(u=t.toolCall)==null?void 0:u.name,o=(f=t.toolCall)==null?void 0:f.id;if(!r){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let h=`${r}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(r,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(k){(E=(v=this.callbacks).onError)==null||E.call(v,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(h)}return}let s=`${r}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(T=t.toolCall)==null?void 0:T.args,l=this.client.executeWebMcpToolCall(n,d,i);try{let h;if(l?h=await l:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let k=(M=(A=t.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?M:n;await this.resumeWithToolOutput(r,k,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(h){h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))||(w=(b=this.callbacks).onError)==null||w.call(b,h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,n,o){var a,i;let s=await this.client.resumeFlow(t,{[r]:n},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,s),this.selectedArtifactId=r,this.emitArtifactsState(),s}let n={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(r,n),this.selectedArtifactId=r,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,n;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,t)}speak(t,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t),s=n.getVoices();if(r.voice){let a=s.find(i=>i.name===r.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):e.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(t){var n;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=t.find(a=>a.name===o);if(s)return s}return(n=t.find(o=>o.lang.startsWith("en")))!=null?n:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),n=this.messages.findIndex(o=>o.id===r.id);if(n===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>{var p,u,f,m,y,v;if(s!==n)return o;let a={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(a.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=r.toolCall)==null?void 0:u.name,d=(f=r.agentMetadata)==null?void 0:f.executionId,l=(m=r.toolCall)==null?void 0:m.id;if(i&&Ra(i)&&d&&l&&((y=r.agentMetadata)==null?void 0:y.awaitingLocalTool)===!0){let E=`${d}:${l}`;(this.webMcpInflightKeys.has(E)||this.webMcpResolvedKeys.has(E))&&(a.agentMetadata={...(v=a.agentMetadata)!=null?v:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,n)=>{var d,l;let o=new Date(r.createdAt).getTime(),s=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=r.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return a!==i?a-i:r.id.localeCompare(n.id)})}};var x=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Yn=(e,t,r)=>{let n=e.createElement(t);return r&&(n.className=r),n};var Ud=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var zd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var qd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var jd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Vd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Gd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Kd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Jd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Xd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Yd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var Qd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Zd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var ec=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var tc=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var rc=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var nc=[["path",{d:"M20 6 9 17l-5-5"}]];var oc=[["path",{d:"m6 9 6 6 6-6"}]];var sc=[["path",{d:"m15 18-6-6 6-6"}]];var ac=[["path",{d:"m9 18 6-6-6-6"}]];var ic=[["path",{d:"m18 15-6-6-6 6"}]];var il=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var ll=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var lc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var dc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var cc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var pc=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var uc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var fc=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var mc=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var dl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var cl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var gc=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var hc=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var xc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var yc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var bc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var wc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Cc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var vc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Sc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Ac=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Tc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Mc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var pl=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var kc=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1"}],["path",{d:"M12 8v13"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"}]];var Ec=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Lc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Pc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Ic=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Rc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var ul=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Wc=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Bc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Dc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Oc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var fl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var _c=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Nc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var $c=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Fc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Uc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var zc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var qc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var jc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Vc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Gc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Kc=[["path",{d:"M5 12h14"}]];var Jc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Xc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Yc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Qc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Zc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var ep=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var tp=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var rp=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var np=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var op=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var sp=[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}],["path",{d:"M12 17.5v-11"}]];var ap=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var ip=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var lp=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var dp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var cp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var pp=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var up=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var fp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var mp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var ml=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var gp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var hp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var xp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var yp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var gl=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var bp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var wp=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Cp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var vp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Sp=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Ap=[["path",{d:"M17 14V2"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}]];var Tp=[["path",{d:"M7 10v12"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}]];var Mp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var kp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ep=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var hl=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Lp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Pp=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Ip=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Rp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Wp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Hp=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Bp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Dp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var Ow={activity:Ud,"arrow-down":zd,"arrow-up":Gd,"arrow-up-right":Vd,bot:Qd,"chevron-down":oc,"chevron-up":ic,"chevron-right":ac,"chevron-left":sc,check:nc,clipboard:dc,"clipboard-copy":lc,copy:pc,file:Cc,"file-code":yc,"file-spreadsheet":bc,"file-text":wc,"image-plus":Wc,loader:_c,"loader-circle":fl,mic:Vc,paperclip:Qc,"refresh-cw":ap,search:dp,send:cp,"shield-alert":fp,"shield-check":mp,"shield-x":ml,square:bp,"thumbs-down":Ap,"thumbs-up":Tp,upload:Pp,"volume-2":Rp,x:Bp,user:Ip,mail:$c,phone:rp,calendar:tc,clock:cc,building:Zd,"map-pin":Fc,lock:Nc,key:Dc,"credit-card":uc,"at-sign":Kd,hash:Lc,globe:Ec,link:Oc,"circle-check":il,"circle-x":ll,"triangle-alert":hl,info:Bc,ban:Jd,shield:gp,"arrow-left":qd,"arrow-right":jd,"external-link":gc,ellipsis:cl,"ellipsis-vertical":dl,menu:zc,house:ul,plus:op,minus:Kc,pencil:ep,trash:Ep,"trash-2":kp,save:lp,download:mc,share:up,funnel:pl,settings:pp,"rotate-cw":ip,maximize:Uc,minimize:Gc,"shopping-cart":xp,"shopping-bag":hp,package:Yc,truck:Lp,tag:Sp,gift:kc,receipt:sp,wallet:Hp,store:Cp,"dollar-sign":fc,percent:tp,play:np,pause:Zc,"volume-x":Wp,camera:rc,image:Hc,film:Sc,headphones:Pc,"message-circle":qc,"message-square":jc,bell:Xd,heart:Ic,star:wp,eye:xc,"eye-off":hc,bookmark:Yd,"calendar-days":ec,history:Rc,timer:Mp,folder:Mc,"folder-open":Tc,files:vc,sparkles:gl,zap:Dp,sun:vp,moon:Xc,flag:Ac,monitor:Jc,smartphone:yp},Pe=(e,t=24,r="currentColor",n=2)=>{let o=Ow[e];return o?_w(o,t,r,n):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function _w(e,t,r,n){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var xl={allowedTypes:mo,maxFileSize:10*1024*1024,maxFiles:4};function Nw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $w(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var cs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:xl.allowedTypes,maxFileSize:(n=t.maxFileSize)!=null?n:xl.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:xl.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:xl.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,n,o,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(n=(r=this.config).onFileRejected)==null||n.call(r,l,"count");continue}let p=rx(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await tx(l),f=nl(l)?URL.createObjectURL(l):null,m={id:Nw(),file:l,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let r=this.attachments.findIndex(d=>d.id===t);if(r===-1)return;let n=this.attachments[r];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,r;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=nl(t.file),n=x("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",r&&t.previewUrl){let a=x("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=x("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=$w(t.file.type),d=Pe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=x("span");l.textContent=nx(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),n.appendChild(a)}let o=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Pe("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var sx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _a(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];sx(s)&&sx(o)?r[n]=_a(s,o):r[n]=o}return r}var yn="min(440px, calc(100vw - 24px))",yl="440px",Zt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:yn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ax(e,t){if(!(!e&&!t))return e?t?_a(e,t):e:t}function bl(e){var t,r,n,o,s,a,i,d,l,p,u,f,m,y,v,E,T,A,M,b,w;return e?{...Zt,...e,theme:ax(Zt.theme,e.theme),darkTheme:ax(Zt.darkTheme,e.darkTheme),launcher:{...Zt.launcher,...e.launcher,dock:{...(t=Zt.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(n=Zt.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Zt.copy,...e.copy},sendButton:{...Zt.sendButton,...e.sendButton},statusIndicator:{...Zt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Zt.voiceRecognition,...e.voiceRecognition},features:(()=>{var Te,We,Oe,K,He,j,Ce,Z;let h=(Te=Zt.features)==null?void 0:Te.artifacts,k=(We=e.features)==null?void 0:We.artifacts,B=(Oe=Zt.features)==null?void 0:Oe.scrollToBottom,H=(K=e.features)==null?void 0:K.scrollToBottom,W=(He=Zt.features)==null?void 0:He.streamAnimation,N=(j=e.features)==null?void 0:j.streamAnimation,q=(Ce=Zt.features)==null?void 0:Ce.askUserQuestion,se=(Z=e.features)==null?void 0:Z.askUserQuestion,ve=h===void 0&&k===void 0?void 0:{...h,...k,layout:{...h==null?void 0:h.layout,...k==null?void 0:k.layout}},Ue=B===void 0&&H===void 0?void 0:{...B,...H},je=W===void 0&&N===void 0?void 0:{...W,...N},we=q===void 0&&se===void 0?void 0:{...q,...se,styles:{...q==null?void 0:q.styles,...se==null?void 0:se.styles}};return{...Zt.features,...e.features,...Ue!==void 0?{scrollToBottom:Ue}:{},...ve!==void 0?{artifacts:ve}:{},...je!==void 0?{streamAnimation:je}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Zt.suggestionChips,suggestionChipsConfig:{...Zt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Zt.layout,...e.layout,header:{...(a=Zt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Zt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Zt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(v=(y=Zt.layout)==null?void 0:y.messages)==null?void 0:v.timestamp,...(T=(E=e.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(A=Zt.layout)==null?void 0:A.slots,...(M=e.layout)==null?void 0:M.slots}},markdown:{...Zt.markdown,...e.markdown,options:{...(b=Zt.markdown)==null?void 0:b.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{...Zt.messageActions,...e.messageActions}}:Zt}var Op={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},_p={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Np={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:yn,maxWidth:yl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Os(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let o of r){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Os(e,n):n}function wl(e){let t={};function r(n,o){for(let[s,a]of Object.entries(n)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Os(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&r(a,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function $p(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function ix(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?r[n]=ix(s,o):r[n]=o}return r}function Fw(e,t){return t?ix(e,t):e}function _s(e,t={}){var o,s,a,i,d,l,p,u,f,m,y,v,E;let r={palette:Op,semantic:_p,components:Np},n={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...r.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...r.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...r.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...r.semantic.colors.feedback,...(y=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...r.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...r.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Fw(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=$p(n);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)n=T.transform(n);return n}function Cl(e){var v,E,T,A,M,b,w,h,k,B,H,W,N,q,se,ve,Ue,je,we,Te,We,Oe,K,He,j,Ce,Z,he,xe,Ve,G,ee,Ie,ye,pe,le,Ye,Me,be,J,Ke,ne,Y,Q,Be,ke,ge,ue,_e,I,te,qe,tt,Xe,Je,pt,ht,zt,or,X,kt,ct,Jt,fe,Se,Wt,sr,Et,gr,_t,Ht,Tt,Lt,ar,mt,cr,Cr,Lr,_r,xt,an,mr,Un,Rr,Zn,Pn,In,me,P,oe,Ee,rt,Xt,$t,er,Pr,Nr,wn,Vt,Ft,Ir,Cn,wo,eo,Co,zn,ln,Rn,It,hr,xr,dn,vo,vn,Wn,cn;let t=wl(e),r={};for(let[R,pn]of Object.entries(t)){let Hn=R.replace(/\./g,"-");r[`--persona-${Hn}`]=pn.value}r["--persona-primary"]=(v=r["--persona-semantic-colors-primary"])!=null?v:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(E=r["--persona-semantic-colors-secondary"])!=null?E:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(T=r["--persona-semantic-colors-accent"])!=null?T:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(M=r["--persona-semantic-colors-background"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(b=r["--persona-semantic-colors-container"])!=null?b:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(h=r["--persona-semantic-colors-text-muted"])!=null?h:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(k=r["--persona-semantic-colors-text-inverse"])!=null?k:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(B=r["--persona-semantic-colors-border"])!=null?B:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(H=r["--persona-semantic-colors-divider"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(W=r["--persona-components-voice-recording-indicator"])!=null?W:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(N=r["--persona-components-voice-recording-background"])!=null?N:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(q=r["--persona-components-voice-processing-icon"])!=null?q:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(se=r["--persona-components-voice-speaking-icon"])!=null?se:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(ve=r["--persona-components-approval-requested-background"])!=null?ve:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ue=r["--persona-components-approval-requested-border"])!=null?Ue:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(je=r["--persona-components-approval-requested-text"])!=null?je:r["--persona-palette-colors-gray-900"],r["--persona-approval-approve-bg"]=(we=r["--persona-components-approval-approve-background"])!=null?we:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Te=r["--persona-components-approval-deny-background"])!=null?Te:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(We=r["--persona-components-attachment-image-background"])!=null?We:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(Oe=r["--persona-components-attachment-image-border"])!=null?Oe:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(K=r["--persona-semantic-typography-fontFamily"])!=null?K:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(He=r["--persona-semantic-typography-fontSize"])!=null?He:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(j=r["--persona-semantic-typography-fontWeight"])!=null?j:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Ce=r["--persona-semantic-typography-lineHeight"])!=null?Ce:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(Z=r["--persona-palette-radius-sm"])!=null?Z:"0.125rem",r["--persona-radius-md"]=(he=r["--persona-palette-radius-md"])!=null?he:"0.375rem",r["--persona-radius-lg"]=(xe=r["--persona-palette-radius-lg"])!=null?xe:"0.5rem",r["--persona-radius-xl"]=(Ve=r["--persona-palette-radius-xl"])!=null?Ve:"0.75rem",r["--persona-radius-full"]=(G=r["--persona-palette-radius-full"])!=null?G:"9999px",r["--persona-launcher-radius"]=(Ie=(ee=r["--persona-components-launcher-borderRadius"])!=null?ee:r["--persona-palette-radius-full"])!=null?Ie:"9999px",r["--persona-launcher-bg"]=(ye=r["--persona-components-launcher-background"])!=null?ye:r["--persona-primary"],r["--persona-launcher-fg"]=(pe=r["--persona-components-launcher-foreground"])!=null?pe:r["--persona-text-inverse"],r["--persona-launcher-border"]=(le=r["--persona-components-launcher-border"])!=null?le:r["--persona-border"],r["--persona-button-primary-bg"]=(Ye=r["--persona-components-button-primary-background"])!=null?Ye:r["--persona-primary"],r["--persona-button-primary-fg"]=(Me=r["--persona-components-button-primary-foreground"])!=null?Me:r["--persona-text-inverse"],r["--persona-button-radius"]=(J=(be=r["--persona-components-button-primary-borderRadius"])!=null?be:r["--persona-palette-radius-full"])!=null?J:"9999px",r["--persona-panel-radius"]=(ne=(Ke=r["--persona-components-panel-borderRadius"])!=null?Ke:r["--persona-radius-xl"])!=null?ne:"0.75rem",r["--persona-panel-border"]=(Y=r["--persona-components-panel-border"])!=null?Y:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Be=(Q=r["--persona-components-panel-shadow"])!=null?Q:r["--persona-palette-shadows-xl"])!=null?Be:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-input-radius"]=(ge=(ke=r["--persona-components-input-borderRadius"])!=null?ke:r["--persona-radius-lg"])!=null?ge:"0.5rem",r["--persona-message-user-radius"]=(_e=(ue=r["--persona-components-message-user-borderRadius"])!=null?ue:r["--persona-radius-lg"])!=null?_e:"0.5rem",r["--persona-message-assistant-radius"]=(te=(I=r["--persona-components-message-assistant-borderRadius"])!=null?I:r["--persona-radius-lg"])!=null?te:"0.5rem",r["--persona-header-bg"]=(qe=r["--persona-components-header-background"])!=null?qe:r["--persona-surface"],r["--persona-header-border"]=(tt=r["--persona-components-header-border"])!=null?tt:r["--persona-divider"],r["--persona-header-icon-bg"]=(Xe=r["--persona-components-header-iconBackground"])!=null?Xe:r["--persona-primary"],r["--persona-header-icon-fg"]=(Je=r["--persona-components-header-iconForeground"])!=null?Je:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(pt=r["--persona-components-header-titleForeground"])!=null?pt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(ht=r["--persona-components-header-subtitleForeground"])!=null?ht:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(zt=r["--persona-components-header-actionIconForeground"])!=null?zt:r["--persona-muted"];let n=(or=e.components)==null?void 0:or.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(X=e.components)==null?void 0:X.introCard;r["--persona-intro-card-bg"]=(kt=r["--persona-components-introCard-background"])!=null?kt:r["--persona-surface"],r["--persona-intro-card-radius"]=(ct=r["--persona-components-introCard-borderRadius"])!=null?ct:"1rem",r["--persona-intro-card-padding"]=(Jt=r["--persona-components-introCard-padding"])!=null?Jt:"1.5rem",r["--persona-intro-card-shadow"]=(Se=(fe=o==null?void 0:o.shadow)!=null?fe:r["--persona-components-introCard-shadow"])!=null?Se:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Wt=r["--persona-components-input-background"])!=null?Wt:r["--persona-surface"],r["--persona-input-placeholder"]=(sr=r["--persona-components-input-placeholder"])!=null?sr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Et=r["--persona-components-message-user-background"])!=null?Et:r["--persona-accent"],r["--persona-message-user-text"]=(gr=r["--persona-components-message-user-text"])!=null?gr:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(_t=r["--persona-components-message-user-shadow"])!=null?_t:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Ht=r["--persona-components-message-assistant-background"])!=null?Ht:r["--persona-surface"],r["--persona-message-assistant-text"]=(Tt=r["--persona-components-message-assistant-text"])!=null?Tt:r["--persona-text"],r["--persona-message-assistant-border"]=(Lt=r["--persona-components-message-assistant-border"])!=null?Lt:r["--persona-border"],r["--persona-message-assistant-shadow"]=(ar=r["--persona-components-message-assistant-shadow"])!=null?ar:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(cr=(mt=r["--persona-components-scrollToBottom-background"])!=null?mt:r["--persona-button-primary-bg"])!=null?cr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Lr=(Cr=r["--persona-components-scrollToBottom-foreground"])!=null?Cr:r["--persona-button-primary-fg"])!=null?Lr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(_r=r["--persona-components-scrollToBottom-border"])!=null?_r:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(xt=r["--persona-components-scrollToBottom-size"])!=null?xt:"40px",r["--persona-scroll-to-bottom-radius"]=(Un=(mr=(an=r["--persona-components-scrollToBottom-borderRadius"])!=null?an:r["--persona-button-radius"])!=null?mr:r["--persona-radius-full"])!=null?Un:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Zn=(Rr=r["--persona-components-scrollToBottom-shadow"])!=null?Rr:r["--persona-palette-shadows-sm"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Pn=r["--persona-components-scrollToBottom-padding"])!=null?Pn:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(In=r["--persona-components-scrollToBottom-gap"])!=null?In:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(P=(me=r["--persona-components-scrollToBottom-fontSize"])!=null?me:r["--persona-palette-typography-fontSize-sm"])!=null?P:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(oe=r["--persona-components-scrollToBottom-iconSize"])!=null?oe:"14px",r["--persona-tool-bubble-shadow"]=(Ee=r["--persona-components-toolBubble-shadow"])!=null?Ee:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(rt=r["--persona-components-reasoningBubble-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Xt=r["--persona-components-composer-shadow"])!=null?Xt:"none",r["--persona-md-inline-code-bg"]=($t=r["--persona-components-markdown-inlineCode-background"])!=null?$t:r["--persona-container"],r["--persona-md-inline-code-color"]=(er=r["--persona-components-markdown-inlineCode-foreground"])!=null?er:r["--persona-text"],r["--persona-md-link-color"]=(Nr=(Pr=r["--persona-components-markdown-link-foreground"])!=null?Pr:r["--persona-accent"])!=null?Nr:"#0f0f0f";let s=r["--persona-components-markdown-heading-h1-fontSize"];s&&(r["--persona-md-h1-size"]=s);let a=r["--persona-components-markdown-heading-h1-fontWeight"];a&&(r["--persona-md-h1-weight"]=a);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let d=r["--persona-components-markdown-heading-h2-fontWeight"];d&&(r["--persona-md-h2-weight"]=d);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(wn=r["--persona-components-markdown-codeBlock-background"])!=null?wn:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Vt=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Vt:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Ft=r["--persona-components-markdown-codeBlock-textColor"])!=null?Ft:"inherit",r["--persona-md-table-header-bg"]=(Ir=r["--persona-components-markdown-table-headerBackground"])!=null?Ir:r["--persona-container"],r["--persona-md-table-border-color"]=(Cn=r["--persona-components-markdown-table-borderColor"])!=null?Cn:r["--persona-border"],r["--persona-md-hr-color"]=(wo=r["--persona-components-markdown-hr-color"])!=null?wo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(eo=r["--persona-components-markdown-blockquote-borderColor"])!=null?eo:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(Co=r["--persona-components-markdown-blockquote-background"])!=null?Co:"transparent",r["--persona-md-blockquote-text-color"]=(zn=r["--persona-components-markdown-blockquote-textColor"])!=null?zn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(ln=r["--persona-components-collapsibleWidget-container"])!=null?ln:r["--persona-surface"],r["--cw-surface"]=(Rn=r["--persona-components-collapsibleWidget-surface"])!=null?Rn:r["--persona-surface"],r["--cw-border"]=(It=r["--persona-components-collapsibleWidget-border"])!=null?It:r["--persona-border"],r["--persona-message-border"]=(hr=r["--persona-components-message-border"])!=null?hr:r["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(r["--persona-icon-btn-bg"]=u.background),u.border&&(r["--persona-icon-btn-border"]=u.border),u.color&&(r["--persona-icon-btn-color"]=u.color),u.padding&&(r["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(r["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(r["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(r["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(r["--persona-label-btn-bg"]=f.background),f.border&&(r["--persona-label-btn-border"]=f.border),f.color&&(r["--persona-label-btn-color"]=f.color),f.padding&&(r["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(r["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(r["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(r["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(r["--persona-label-btn-gap"]=f.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let R=y.toolbar;R.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=R.iconHoverColor),R.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=R.iconHoverBackground),R.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=R.iconPadding),R.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=R.iconBorderRadius),R.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=R.iconBorder),R.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=R.toggleGroupGap),R.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=R.toggleBorderRadius),R.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=R.copyBackground),R.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=R.copyBorder),R.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=R.copyColor),R.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=R.copyBorderRadius),R.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=R.copyPadding),R.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=R.copyMenuBackground,r["--persona-dropdown-bg"]=(xr=r["--persona-dropdown-bg"])!=null?xr:R.copyMenuBackground),R.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=R.copyMenuBorder,r["--persona-dropdown-border"]=(dn=r["--persona-dropdown-border"])!=null?dn:R.copyMenuBorder),R.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=R.copyMenuShadow,r["--persona-dropdown-shadow"]=(vo=r["--persona-dropdown-shadow"])!=null?vo:R.copyMenuShadow),R.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=R.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(vn=r["--persona-dropdown-radius"])!=null?vn:R.copyMenuBorderRadius),R.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=R.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Wn=r["--persona-dropdown-item-hover-bg"])!=null?Wn:R.copyMenuItemHoverBackground),R.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=R.iconBackground),R.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=R.toolbarBorder)}if(y!=null&&y.tab){let R=y.tab;R.background&&(r["--persona-artifact-tab-bg"]=R.background),R.activeBackground&&(r["--persona-artifact-tab-active-bg"]=R.activeBackground),R.activeBorder&&(r["--persona-artifact-tab-active-border"]=R.activeBorder),R.borderRadius&&(r["--persona-artifact-tab-radius"]=R.borderRadius),R.textColor&&(r["--persona-artifact-tab-color"]=R.textColor),R.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=R.hoverBackground),R.listBackground&&(r["--persona-artifact-tab-list-bg"]=R.listBackground),R.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=R.listBorderColor),R.listPadding&&(r["--persona-artifact-tab-list-padding"]=R.listPadding)}if(y!=null&&y.pane){let R=y.pane;if(R.toolbarBackground){let pn=(cn=Os(e,R.toolbarBackground))!=null?cn:R.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pn}}return r}var lx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Uw={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},dx=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Na=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},zw=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Na()},Fp=e=>zw(e),qw=e=>_s(e),jw=e=>{var r;let t=_s(void 0,{validate:!1});return _s({...e,palette:{...t.palette,colors:{...Uw.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ns=e=>{let t=Fp(e),r=dx(e==null?void 0:e.theme),n=dx(e==null?void 0:e.darkTheme);return t==="dark"?jw(_a(r!=null?r:{},n!=null?n:{})):qw(r)},Vw=e=>Cl(e),Io=(e,t)=>{var s;let r=Ns(t),n=Vw(r);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let o=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},vl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Na())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Na());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(r=>r())}};var cx=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:f=>f.getAttribute("im-preserve")==="true",shouldReAppend:f=>f.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(f,m,y={}){f=p(f);let v=u(m),E=l(f,v,y),T=o(E,()=>i(E,f,v,A=>A.morphStyle==="innerHTML"?(s(A,f,v),Array.from(f.childNodes)):n(A,f,v)));return E.pantry.remove(),T}function n(f,m,y){let v=u(m);return s(f,v,y,m,m.nextSibling),Array.from(v.childNodes)}function o(f,m){var M;if(!f.config.restoreFocus)return m();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return m();let{id:v,selectionStart:E,selectionEnd:T}=y,A=m();return v&&v!==((M=document.activeElement)==null?void 0:M.getAttribute("id"))&&(y=f.target.querySelector(`[id="${v}"]`),y==null||y.focus()),y&&!y.selectionEnd&&T&&y.setSelectionRange(E,T),A}let s=(function(){function f(b,w,h,k=null,B=null){w instanceof HTMLTemplateElement&&h instanceof HTMLTemplateElement&&(w=w.content,h=h.content),k||(k=w.firstChild);for(let H of h.childNodes){if(k&&k!=B){let N=y(b,H,k,B);if(N){N!==k&&E(b,k,N),a(N,H,b),k=N.nextSibling;continue}}if(H instanceof Element){let N=H.getAttribute("id");if(b.persistentIds.has(N)){let q=T(w,N,k,b);a(q,H,b),k=q.nextSibling;continue}}let W=m(w,H,k,b);W&&(k=W.nextSibling)}for(;k&&k!=B;){let H=k;k=k.nextSibling,v(b,H)}}function m(b,w,h,k){if(k.callbacks.beforeNodeAdded(w)===!1)return null;if(k.idMap.has(w)){let B=document.createElement(w.tagName);return b.insertBefore(B,h),a(B,w,k),k.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(w,!0);return b.insertBefore(B,h),k.callbacks.afterNodeAdded(B),B}}let y=(function(){function b(k,B,H,W){let N=null,q=B.nextSibling,se=0,ve=H;for(;ve&&ve!=W;){if(h(ve,B)){if(w(k,ve,B))return ve;N===null&&(k.idMap.has(ve)||(N=ve))}if(N===null&&q&&h(ve,q)&&(se++,q=q.nextSibling,se>=2&&(N=void 0)),k.activeElementAndParents.includes(ve))break;ve=ve.nextSibling}return N||null}function w(k,B,H){let W=k.idMap.get(B),N=k.idMap.get(H);if(!N||!W)return!1;for(let q of W)if(N.has(q))return!0;return!1}function h(k,B){var N,q,se;let H=k,W=B;return H.nodeType===W.nodeType&&H.tagName===W.tagName&&(!((N=H.getAttribute)!=null&&N.call(H,"id"))||((q=H.getAttribute)==null?void 0:q.call(H,"id"))===((se=W.getAttribute)==null?void 0:se.call(W,"id")))}return b})();function v(b,w){var h;if(b.idMap.has(w))M(b.pantry,w,null);else{if(b.callbacks.beforeNodeRemoved(w)===!1)return;(h=w.parentNode)==null||h.removeChild(w),b.callbacks.afterNodeRemoved(w)}}function E(b,w,h){let k=w;for(;k&&k!==h;){let B=k;k=k.nextSibling,v(b,B)}return k}function T(b,w,h,k){var H,W;let B=((W=(H=k.target).getAttribute)==null?void 0:W.call(H,"id"))===w&&k.target||k.target.querySelector(`[id="${w}"]`)||k.pantry.querySelector(`[id="${w}"]`);return A(B,k),M(b,B,h),B}function A(b,w){let h=b.getAttribute("id");for(;b=b.parentNode;){let k=w.idMap.get(b);k&&(k.delete(h),k.size||w.idMap.delete(b))}}function M(b,w,h){if(b.moveBefore)try{b.moveBefore(w,h)}catch{b.insertBefore(w,h)}else b.insertBefore(w,h)}return f})(),a=(function(){function f(A,M,b){return b.ignoreActive&&A===document.activeElement?null:(b.callbacks.beforeNodeMorphed(A,M)===!1||(A instanceof HTMLHeadElement&&b.head.ignore||(A instanceof HTMLHeadElement&&b.head.style!=="morph"?d(A,M,b):(m(A,M,b),T(A,b)||s(b,A,M))),b.callbacks.afterNodeMorphed(A,M)),A)}function m(A,M,b){let w=M.nodeType;if(w===1){let h=A,k=M,B=h.attributes,H=k.attributes;for(let W of H)E(W.name,h,"update",b)||h.getAttribute(W.name)!==W.value&&h.setAttribute(W.name,W.value);for(let W=B.length-1;0<=W;W--){let N=B[W];if(N&&!k.hasAttribute(N.name)){if(E(N.name,h,"remove",b))continue;h.removeAttribute(N.name)}}T(h,b)||y(h,k,b)}(w===8||w===3)&&A.nodeValue!==M.nodeValue&&(A.nodeValue=M.nodeValue)}function y(A,M,b){if(A instanceof HTMLInputElement&&M instanceof HTMLInputElement&&M.type!=="file"){let w=M.value,h=A.value;v(A,M,"checked",b),v(A,M,"disabled",b),M.hasAttribute("value")?h!==w&&(E("value",A,"update",b)||(A.setAttribute("value",w),A.value=w)):E("value",A,"remove",b)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&M instanceof HTMLOptionElement)v(A,M,"selected",b);else if(A instanceof HTMLTextAreaElement&&M instanceof HTMLTextAreaElement){let w=M.value,h=A.value;if(E("value",A,"update",b))return;w!==h&&(A.value=w),A.firstChild&&A.firstChild.nodeValue!==w&&(A.firstChild.nodeValue=w)}}function v(A,M,b,w){let h=M[b],k=A[b];if(h!==k){let B=E(b,A,"update",w);B||(A[b]=M[b]),h?B||A.setAttribute(b,""):E(b,A,"remove",w)||A.removeAttribute(b)}}function E(A,M,b,w){return A==="value"&&w.ignoreActiveValue&&M===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(A,M,b)===!1}function T(A,M){return!!M.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return f})();function i(f,m,y,v){if(f.head.block){let E=m.querySelector("head"),T=y.querySelector("head");if(E&&T){let A=d(E,T,f);return Promise.all(A).then(()=>{let M=Object.assign(f,{head:{block:!1,ignore:!0}});return v(M)})}}return v(f)}function d(f,m,y){let v=[],E=[],T=[],A=[],M=new Map;for(let w of m.children)M.set(w.outerHTML,w);for(let w of f.children){let h=M.has(w.outerHTML),k=y.head.shouldReAppend(w),B=y.head.shouldPreserve(w);h||B?k?E.push(w):(M.delete(w.outerHTML),T.push(w)):y.head.style==="append"?k&&(E.push(w),A.push(w)):y.head.shouldRemove(w)!==!1&&E.push(w)}A.push(...M.values());let b=[];for(let w of A){let h=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(h)!==!1){if("href"in h&&h.href||"src"in h&&h.src){let k,B=new Promise(function(H){k=H});h.addEventListener("load",function(){k()}),b.push(B)}f.appendChild(h),y.callbacks.afterNodeAdded(h),v.push(h)}}for(let w of E)y.callbacks.beforeNodeRemoved(w)!==!1&&(f.removeChild(w),y.callbacks.afterNodeRemoved(w));return y.head.afterHeadMorphed(f,{added:v,kept:T,removed:E}),b}let l=(function(){function f(b,w,h){let{persistentIds:k,idMap:B}=A(b,w),H=m(h),W=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(W))throw`Do not understand how to morph style ${W}`;return{target:b,newContent:w,config:H,morphStyle:W,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:B,persistentIds:k,pantry:y(),activeElementAndParents:v(b),callbacks:H.callbacks,head:H.head}}function m(b){let w=Object.assign({},t);return Object.assign(w,b),w.callbacks=Object.assign({},t.callbacks,b.callbacks),w.head=Object.assign({},t.head,b.head),w}function y(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function v(b){let w=[],h=document.activeElement;if((h==null?void 0:h.tagName)!=="BODY"&&b.contains(h))for(;h&&(w.push(h),h!==b);)h=h.parentElement;return w}function E(b){var h;let w=Array.from(b.querySelectorAll("[id]"));return(h=b.getAttribute)!=null&&h.call(b,"id")&&w.push(b),w}function T(b,w,h,k){for(let B of k){let H=B.getAttribute("id");if(w.has(H)){let W=B;for(;W;){let N=b.get(W);if(N==null&&(N=new Set,b.set(W,N)),N.add(H),W===h)break;W=W.parentElement}}}}function A(b,w){let h=E(b),k=E(w),B=M(h,k),H=new Map;T(H,B,b,h);let W=w.__idiomorphRoot||w;return T(H,B,W,k),{persistentIds:B,idMap:H}}function M(b,w){let h=new Set,k=new Map;for(let{id:H,tagName:W}of b)k.has(H)?h.add(H):k.set(H,W);let B=new Set;for(let{id:H,tagName:W}of w)B.has(H)?h.add(H):k.get(H)===W&&B.add(H);for(let H of h)B.delete(H);return B}return f})(),{normalizeElement:p,normalizeParent:u}=(function(){let f=new WeakSet;function m(T){return T instanceof Document?T.documentElement:T}function y(T){if(T==null)return document.createElement("div");if(typeof T=="string")return y(E(T));if(f.has(T))return T;if(T instanceof Node){if(T.parentNode)return new v(T);{let A=document.createElement("div");return A.append(T),A}}else{let A=document.createElement("div");for(let M of[...T])A.append(M);return A}}class v{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],M=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;M&&M!=this.nextSibling;)A.push(M),M=M.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((M,b)=>{if(b instanceof Element){b.matches(A)&&M.push(b);let w=b.querySelectorAll(A);for(let h=0;h<w.length;h++)M.push(w[h])}return M},[])}insertBefore(A,M){return this.realParentNode.insertBefore(A,M)}moveBefore(A,M){return this.realParentNode.moveBefore(A,M)}get __idiomorphRoot(){return this.originalNode}}function E(T){let A=new DOMParser,M=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(M.match(/<\/html>/)||M.match(/<\/head>/)||M.match(/<\/body>/)){let b=A.parseFromString(T,"text/html");if(M.match(/<\/html>/))return f.add(b),b;{let w=b.firstChild;return w&&f.add(w),w}}else{let w=A.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return f.add(w),w}}return{normalizeElement:m,normalizeParent:y}})();return{morph:r,defaults:t}})();var Sl=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;cx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Al={index:-1,draft:""};function px(e){let{direction:t,history:r,currentValue:n,atStart:o,state:s}=e,a=s.index!==-1;if(r.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:n}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<r.length-1){let i=s.index+1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Al}}}function ux(e,t){var r,n,o,s,a,i,d,l,p,u,f,m,y,v,E,T,A,M,b,w,h,k,B,H,W,N,q,se,ve,Ue,je,we,Te,We,Oe,K,He,j;return[e.id,e.role,(n=(r=e.content)==null?void 0:r.length)!=null?n:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(y=(m=e.toolCall)==null?void 0:m.status)!=null?y:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(M=(A=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:A.length)!=null?M:0,(k=(h=(w=(b=e.toolCall)==null?void 0:b.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:h.slice(-32))!=null?k:"",typeof((B=e.toolCall)==null?void 0:B.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(q=(N=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:N.length)!=null?q:0,(je=(Ue=(ve=(se=e.reasoning)==null?void 0:se.chunks)==null?void 0:ve[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?je:0,(Oe=(We=(Te=(we=e.reasoning)==null?void 0:we.chunks)==null?void 0:Te[e.reasoning.chunks.length-1])==null?void 0:We.slice(-32))!=null?Oe:"",(He=(K=e.contentParts)==null?void 0:K.length)!=null?He:0,(j=e.stopReason)!=null?j:"",t].join("\0")}function fx(){return new Map}function mx(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}function gx(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}function hx(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function Tl(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function $a(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fa(e,t){return $a(e)-e.scrollTop<=t}function Ml(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=r-n;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:r}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function kl(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}var zr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},qr=1e5,Ro=qr+1;var Ua={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Gw=["pre","code","a","script","style"],El=e=>{var t,r,n,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ua.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ua.placeholder,speed:(n=e==null?void 0:e.speed)!=null?n:Ua.speed,duration:(o=e==null?void 0:e.duration)!=null?o:Ua.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ua.buffer}},yx=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],za=new Map;for(let e of yx)za.set(e.name,e);var ps=e=>{za.set(e.name,e)},qp=e=>{yx.some(t=>t.name===e)||za.delete(e)},jp=()=>Array.from(za.keys()),qa=(e,t)=>{var r,n;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(n=za.get(e))!=null?n:null},Ll=(e,t,r,n,o)=>{if(!o)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,n);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
65
- `);return s<0?"":e.slice(0,s)}return e},Kw=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},Jw=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},Up=/\s/,Xw=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let n=r;if(t.has(n.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Yw=(e,t,r)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=0;for(;i<s.length;)if(Up.test(s[i])){let l=i;for(;l<s.length&&Up.test(s[l]);)l+=1;a.appendChild(n.createTextNode(s.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Up.test(s[p]);)l.appendChild(Kw(n,s[p],t,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Qw=(e,t,r)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(n.createTextNode(l)):(a.appendChild(Jw(n,l,t,r.value)),r.value+=1));o.replaceChild(a,e)},ja=(e,t,r,n)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=n==null?void 0:n.skipTags)!=null?u:Gw).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Xw(d,s)||i.push(d),d=a.nextNode();let l={value:(f=n==null?void 0:n.startIndex)!=null?f:0},p=t==="char"?Yw:Qw;for(let m of i)p(m,r,l);return o.innerHTML},Pl=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Va=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},xx=new WeakMap,Zw=(e,t)=>{var s;if(!e.styles)return;let r=xx.get(t);if(r||(r=new Set,xx.set(t,r)),r.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;r.delete(e.name)}r.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},zp=new WeakMap,eC=(e,t)=>{if(!e.onAttach)return;let r=zp.get(t);if(r||(r=new Map,zp.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)},bx=e=>{let t=zp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Vp=(e,t)=>{Zw(e,t),eC(e,t)};function Gp(e,t=qr){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}var Ga=0,Wo=null;function Kp(e=document){var r;if(Ga++,Ga===1){let n=e.body,s=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Wo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let t=!1;return()=>{var n;if(!t&&(t=!0,Ga=Math.max(0,Ga-1),Ga===0&&Wo)){let o=e.body,s=(n=e.defaultView)!=null?n:window;o.style.overflow=Wo.originalOverflow,o.style.position=Wo.originalPosition,o.style.top=Wo.originalTop,o.style.width=Wo.originalWidth,s.scrollTo(0,Wo.scrollY),Wo=null}}}var Il={side:"right",width:"420px",animate:!0,reveal:"resize"},Tr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Ho=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},kn=e=>{var r,n,o,s,a;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(n=t==null?void 0:t.side)!=null?n:Il.side,width:(o=t==null?void 0:t.width)!=null?o:Il.width,animate:(s=t==null?void 0:t.animate)!=null?s:Il.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Il.reveal}};var Fn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Ka=(e,t)=>{let r=x("button");r.type="button",r.innerHTML=`
64
+ _Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=e=>{var r,n,o,s,a,i,d,l;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall;((r=e.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Ls(p.name)&&this.enqueueWebMcpAwait(e.message),(n=e.message.agentMetadata)!=null&&n.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(o=e.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=e.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var n,o;this.messages=[...(n=e.initialMessages)!=null?n:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new aa(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Bs((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,r,n;return(n=(r=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:r.call(e))!=null?n:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var r,n,o;try{let s=e||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=la(s);let a=(r=this.config.voiceRecognition)!=null?r:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,u,f,y,A;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((u=l.text)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.text)!=null&&f.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(A=this.pendingVoiceAssistantMessageId)!=null?A:(y=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:y.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,n,o,s,a,i,d,l,p;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=e.runtype)==null?void 0:n.agentId)||"",clientToken:((o=e.runtype)==null?void 0:o.clientToken)||"",host:(s=e.runtype)==null?void 0:s.host,voiceId:(a=e.runtype)==null?void 0:a.voiceId,pauseDuration:(i=e.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=e.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=e.browser)==null?void 0:l.language)||"en-US",continuous:(p=e.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var e,r;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(r=(e=this.callbacks).onError)==null||r.call(e,n instanceof Error?n:new Error(String(n))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,r){return this.client.submitMessageFeedback(e,r)}async submitCSATFeedback(e,r){return this.client.submitCSATFeedback(e,r)}async submitNPSFeedback(e,r){return this.client.submitNPSFeedback(e,r)}updateConfig(e){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config={...this.config,...e},this.client=new aa(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:r,content:n,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=e,f={id:a!=null?a:r==="user"?Ra():r==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let r=[];for(let n of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:u,rawContent:f}=n,A={id:d!=null?d:o==="user"?Ra():o==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};r.push(A)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(e){let{component:r,props:n={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,l={text:o,component:r,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,r){var l,p,m,u,f;let n=e.trim();if(!n&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Ra(),s=sa(),a={id:o,role:"user",content:n||Zi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){let A=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!A){let E=Gh(y,this.config.errorMessage);if(E){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,A||(y instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,y):(f=(u=this.callbacks).onError)==null||f.call(u,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=sa();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:r.signal,assistantMessageId:e},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Gh(l,this.config.errorMessage);if(m){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,r){var o,s,a;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(e,r){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:r,resolvedAt:Date.now()}}),n(r==="approved")}async resolveApproval(e,r){var d,l,p,m;let n=`approval-${e.id}`,o={...e,status:r,resolvedAt:Date.now()},s={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},r):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},r),u){let f=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error((l=y==null?void 0:y.error)!=null?l:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let f=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||(m=(p=this.callbacks).onError)==null||m.call(p,u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(e,r){var p,m,u,f,y,A,E,T,S,k,x,b;let n=this.messages.find(h=>h.id===e.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(y=(f=this.callbacks).onError)==null||y.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof r=="string"?void 0:r;if(a===void 0&&typeof r=="string"){let h=(A=e.toolCall)==null?void 0:A.args,M=Array.isArray(h==null?void 0:h.questions)?h.questions:[];if(M.length===1){let W=typeof((E=M[0])==null?void 0:E.question)=="string"?M[0].question:"";W&&(a={[W]:r})}}this.markAskUserQuestionResolved(e,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(S=e.toolCall)==null?void 0:S.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let h=typeof r=="string"?r:Object.entries(r).map(([M,W])=>`${M}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let h=a!=null?a:{};l.forEach((M,W)=>{let R=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!R)return;let B=h[R],_=Array.isArray(B)?B.join(", "):typeof B=="string"?B:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let h=await this.client.resumeFlow(o,{[s]:r});if(!h.ok){let M=await h.json().catch(()=>null);throw new Error((k=M==null?void 0:M.error)!=null?k:`Resume failed: ${h.status}`)}h.body?await this.connectStream(h.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(h){let M=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(b=(x=this.callbacks).onError)==null||b.call(x,h instanceof Error?h:new Error(String(h)))}}enqueueWebMcpAwait(e){var s,a;let r=(s=e.agentMetadata)==null?void 0:s.executionId,n=(a=e.toolCall)==null?void 0:a.id;if(!r||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(r);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,o)),!o.seen.has(n)&&(o.seen.add(n),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(e){let r=this.webMcpAwaitBatches.get(e);if(!r)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=r;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(e,n)}async resolveWebMcpToolCallBatch(e,r){var i,d,l;let n=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(r.map(async p=>{var S,k,x,b,h,M,W;let m=(S=p.toolCall)==null?void 0:S.name,u=(k=p.toolCall)==null?void 0:k.id;if(!m||!u)return null;let f=`${e}:${u}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f))return null;this.webMcpInflightKeys.add(f),n.push(f),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let y=new AbortController;this.webMcpResolveControllers.add(y),o.push(y);let A=(b=(x=p.agentMetadata)==null?void 0:x.webMcpToolCallId)!=null?b:m,E=this.client.executeWebMcpToolCall(m,(h=p.toolCall)==null?void 0:h.args,y.signal),T;if(!E)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await E}catch(R){return R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"))||(W=(M=this.callbacks).onError)==null||W.call(M,R instanceof Error?R:new Error(String(R))),this.webMcpInflightKeys.delete(f),null}return y.signal.aborted?(this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:A,output:T}}));try{let p=a.filter(f=>f!==null);if(p.length===0)return;let m={};for(let f of p)m[f.resumeKey]=f.output;let u=await this.client.resumeFlow(e,m,{signal:s.signal});if(!u.ok){let f=await u.json().catch(()=>null);throw new Error((i=f==null?void 0:f.error)!=null?i:`Resume failed: ${u.status}`)}for(let f of p)this.webMcpResolvedKeys.add(f.dedupeKey);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of n)this.webMcpInflightKeys.delete(p);for(let p of o)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var p,m,u,f,y,A,E,T,S,k,x,b;let r=(p=e.agentMetadata)==null?void 0:p.executionId,n=(m=e.toolCall)==null?void 0:m.name,o=(u=e.toolCall)==null?void 0:u.id;if(!r){(y=(f=this.callbacks).onError)==null||y.call(f,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let h=`${r}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(r,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(M){(E=(A=this.callbacks).onError)==null||E.call(A,M instanceof Error?M:new Error(String(M)))}finally{this.webMcpInflightKeys.delete(h)}return}let s=`${r}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...e,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(T=e.toolCall)==null?void 0:T.args,l=this.client.executeWebMcpToolCall(n,d,i);try{let h;if(l?h=await l:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let M=(k=(S=e.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?k:n;await this.resumeWithToolOutput(r,M,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(h){h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))||(b=(x=this.callbacks).onError)==null||b.call(x,h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,r,n,o){var a,i;let s=await this.client.resumeFlow(e,{[r]:n},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let r=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:r,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(r,s),this.selectedArtifactId=r,this.emitArtifactsState(),s}let n={id:r,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(r,n),this.selectedArtifactId=r,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,r;(r=(e=this.callbacks).onArtifactsState)==null||r.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var r,n;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(r=e.component)!=null?r:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,r=null){this.artifacts.clear();for(let n of e)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let r=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),r&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let n=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,e)}speak(e,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(e),s=n.getVoices();if(r.voice){let a=s.find(i=>i.name===r.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):t.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(e){var n;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=e.find(a=>a.name===o);if(s)return s}return(n=e.find(o=>o.lang.startsWith("en")))!=null?n:e[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),n=this.messages.findIndex(o=>o.id===r.id);if(n===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>{var p,m,u,f,y,A;if(s!==n)return o;let a={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(a.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=r.toolCall)==null?void 0:m.name,d=(u=r.agentMetadata)==null?void 0:u.executionId,l=(f=r.toolCall)==null?void 0:f.id;if(i&&Ls(i)&&d&&l&&((y=r.agentMetadata)==null?void 0:y.awaitingLocalTool)===!0){let E=`${d}:${l}`;(this.webMcpInflightKeys.has(E)||this.webMcpResolvedKeys.has(E))&&(a.agentMetadata={...(A=a.agentMetadata)!=null?A:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,n)=>{var d,l;let o=new Date(r.createdAt).getTime(),s=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=r.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return a!==i?a-i:r.id.localeCompare(n.id)})}};var v=(t,e)=>{let r=document.createElement(t);return e&&(r.className=e),r},Qn=(t,e,r)=>{let n=t.createElement(e);return r&&(n.className=r),n};var Bd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Hd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Dd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Od=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var _d=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Nd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Fd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var $d=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Ud=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var zd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var qd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Vd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var jd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Gd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Kd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Xd=[["path",{d:"M20 6 9 17l-5-5"}]];var Jd=[["path",{d:"m6 9 6 6 6-6"}]];var Qd=[["path",{d:"m15 18-6-6 6-6"}]];var Yd=[["path",{d:"m9 18 6-6-6-6"}]];var Zd=[["path",{d:"m18 15-6-6-6 6"}]];var ol=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var al=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var ec=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var tc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var rc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var nc=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var oc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var ac=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var sc=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var sl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var il=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var ic=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var lc=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var dc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var cc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var pc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var uc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var fc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var mc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var gc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var hc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var xc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var yc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var ll=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var bc=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1"}],["path",{d:"M12 8v13"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"}]];var wc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var vc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Cc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Ac=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Sc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var dl=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Tc=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Mc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var kc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Ec=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Lc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var cl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Pc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Ic=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Rc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Wc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Bc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Hc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Dc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Oc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var _c=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Nc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Fc=[["path",{d:"M5 12h14"}]];var $c=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Uc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var zc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var qc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Vc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var jc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Gc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Kc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Xc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Jc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Qc=[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}],["path",{d:"M12 17.5v-11"}]];var Yc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Zc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var ep=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var tp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var rp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var np=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var op=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var ap=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var sp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var pl=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var ip=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var lp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var dp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var cp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var ul=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var pp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var up=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var fp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var mp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var gp=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var hp=[["path",{d:"M17 14V2"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}]];var xp=[["path",{d:"M7 10v12"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}]];var yp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var bp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var wp=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var fl=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var vp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Cp=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Ap=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Sp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Tp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Mp=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var kp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ep=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var gw={activity:Bd,"arrow-down":Hd,"arrow-up":Nd,"arrow-up-right":_d,bot:qd,"chevron-down":Jd,"chevron-up":Zd,"chevron-right":Yd,"chevron-left":Qd,check:Xd,clipboard:tc,"clipboard-copy":ec,copy:nc,file:fc,"file-code":cc,"file-spreadsheet":pc,"file-text":uc,"image-plus":Tc,loader:Pc,"loader-circle":cl,mic:_c,paperclip:qc,"refresh-cw":Yc,search:tp,send:rp,"shield-alert":ap,"shield-check":sp,"shield-x":pl,square:pp,"thumbs-down":hp,"thumbs-up":xp,upload:Cp,"volume-2":Sp,x:kp,user:Ap,mail:Rc,phone:Kc,calendar:Gd,clock:rc,building:Vd,"map-pin":Wc,lock:Ic,key:Ec,"credit-card":oc,"at-sign":Fd,hash:vc,globe:wc,link:Lc,"circle-check":ol,"circle-x":al,"triangle-alert":fl,info:kc,ban:$d,shield:ip,"arrow-left":Dd,"arrow-right":Od,"external-link":ic,ellipsis:il,"ellipsis-vertical":sl,menu:Hc,house:dl,plus:Jc,minus:Fc,pencil:jc,trash:wp,"trash-2":bp,save:ep,download:sc,share:op,funnel:ll,settings:np,"rotate-cw":Zc,maximize:Bc,minimize:Nc,"shopping-cart":dp,"shopping-bag":lp,package:zc,truck:vp,tag:gp,gift:bc,receipt:Qc,wallet:Mp,store:fp,"dollar-sign":ac,percent:Gc,play:Xc,pause:Vc,"volume-x":Tp,camera:Kd,image:Mc,film:gc,headphones:Cc,"message-circle":Dc,"message-square":Oc,bell:Ud,heart:Ac,star:up,eye:dc,"eye-off":lc,bookmark:zd,"calendar-days":jd,history:Sc,timer:yp,folder:yc,"folder-open":xc,files:mc,sparkles:ul,zap:Ep,sun:mp,moon:Uc,flag:hc,monitor:$c,smartphone:cp},Ie=(t,e=24,r="currentColor",n=2)=>{let o=gw[t];return o?hw(o,e,r,n):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function hw(t,e,r,n){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var ml={allowedTypes:mo,maxFileSize:10*1024*1024,maxFiles:4};function xw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yw(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var da=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=e.allowedTypes)!=null?r:ml.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:ml.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:ml.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ml.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var r,n,o,s,a,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(n=(r=this.config).onFileRejected)==null||n.call(r,l,"count");continue}let p=Vh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await qh(l),u=el(l)?URL.createObjectURL(l):null,f={id:xw(),file:l,previewUrl:u,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let r=this.attachments.findIndex(d=>d.id===e);if(r===-1)return;let n=this.attachments[r];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,r;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(e=this.config).onAttachmentsChange)==null||r.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let r=el(e.file),n=v("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",e.id),n.style.width="48px",n.style.height="48px",r&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=yw(e.file.type),d=Ie(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=v("span");l.textContent=jh(e.file.type,e.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),n.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,r){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:r})}};var Kh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Hs(t,e){if(!t)return e;if(!e)return t;let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];Kh(s)&&Kh(o)?r[n]=Hs(s,o):r[n]=o}return r}var yn="min(440px, calc(100vw - 24px))",gl="440px",er={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:yn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xh(t,e){if(!(!t&&!e))return t?e?Hs(t,e):t:e}function hl(t){var e,r,n,o,s,a,i,d,l,p,m,u,f,y,A,E,T,S,k,x,b;return t?{...er,...t,theme:Xh(er.theme,t.theme),darkTheme:Xh(er.darkTheme,t.darkTheme),launcher:{...er.launcher,...t.launcher,dock:{...(e=er.launcher)==null?void 0:e.dock,...(r=t.launcher)==null?void 0:r.dock},clearChat:{...(n=er.launcher)==null?void 0:n.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...er.copy,...t.copy},sendButton:{...er.sendButton,...t.sendButton},statusIndicator:{...er.statusIndicator,...t.statusIndicator},voiceRecognition:{...er.voiceRecognition,...t.voiceRecognition},features:(()=>{var Ee,Ge,_e,X,Ue,K,Te,ae;let h=(Ee=er.features)==null?void 0:Ee.artifacts,M=(Ge=t.features)==null?void 0:Ge.artifacts,W=(_e=er.features)==null?void 0:_e.scrollToBottom,R=(X=t.features)==null?void 0:X.scrollToBottom,B=(Ue=er.features)==null?void 0:Ue.streamAnimation,_=(K=t.features)==null?void 0:K.streamAnimation,V=(Te=er.features)==null?void 0:Te.askUserQuestion,oe=(ae=t.features)==null?void 0:ae.askUserQuestion,be=h===void 0&&M===void 0?void 0:{...h,...M,layout:{...h==null?void 0:h.layout,...M==null?void 0:M.layout}},Qe=W===void 0&&R===void 0?void 0:{...W,...R},je=B===void 0&&_===void 0?void 0:{...B,..._},ve=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{...er.features,...t.features,...Qe!==void 0?{scrollToBottom:Qe}:{},...be!==void 0?{artifacts:be}:{},...je!==void 0?{streamAnimation:je}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:er.suggestionChips,suggestionChipsConfig:{...er.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...er.layout,...t.layout,header:{...(a=er.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=er.layout)==null?void 0:d.messages,...(l=t.layout)==null?void 0:l.messages,avatar:{...(m=(p=er.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(f=(u=t.layout)==null?void 0:u.messages)==null?void 0:f.avatar},timestamp:{...(A=(y=er.layout)==null?void 0:y.messages)==null?void 0:A.timestamp,...(T=(E=t.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(S=er.layout)==null?void 0:S.slots,...(k=t.layout)==null?void 0:k.slots}},markdown:{...er.markdown,...t.markdown,options:{...(x=er.markdown)==null?void 0:x.options,...(b=t.markdown)==null?void 0:b.options}},messageActions:{...er.messageActions,...t.messageActions}}:er}var Lp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Pp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Ip={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:yn,maxWidth:gl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ba(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let r=e.split("."),n=t;for(let o of r){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ba(t,n):n}function xl(t){let e={};function r(n,o){for(let[s,a]of Object.entries(n)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ba(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&r(a,i)}}return r(t.palette,"palette"),r(t.semantic,"semantic"),r(t.components,"components"),e}function Rp(t){let e=[],r=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:r}}function Jh(t,e){let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?r[n]=Jh(s,o):r[n]=o}return r}function bw(t,e){return e?Jh(t,e):t}function Ha(t,e={}){var o,s,a,i,d,l,p,m,u,f,y,A,E;let r={palette:Lp,semantic:Pp,components:Ip},n={palette:{...r.palette,...t==null?void 0:t.palette,colors:{...r.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...r.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...r.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...r.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...r.palette.radius,...(l=t==null?void 0:t.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...t==null?void 0:t.semantic,colors:{...r.semantic.colors,...(p=t==null?void 0:t.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(y=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:y.feedback}},spacing:{...r.semantic.spacing,...(A=t==null?void 0:t.semantic)==null?void 0:A.spacing},typography:{...r.semantic.typography,...(E=t==null?void 0:t.semantic)==null?void 0:E.typography}},components:bw(r.components,t==null?void 0:t.components)};if(e.validate!==!1){let T=Rp(n);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(S=>S.message).join(", ")}`)}if(e.plugins)for(let T of e.plugins)n=T.transform(n);return n}function yl(t){var A,E,T,S,k,x,b,h,M,W,R,B,_,V,oe,be,Qe,je,ve,Ee,Ge,_e,X,Ue,K,Te,ae,xe,Me,Ke,ce,re,le,ut,Ce,he,tt,Ne,me,J,qe,Z,ge,q,Re,Ae,fe,pe,Be,Q,N,ke,He,Ve,Xe,gt,ot,Mt,Xt,G,Jt,at,Nt,de,ye,Rt,ar,kt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,P,ee,Se,rt,Qt,Ft,tr,Pr,_r,wn,Vt,$t,Ir,vn,bo,eo,wo,zn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn;let e=xl(t),r={};for(let[I,pn]of Object.entries(e)){let Bn=I.replace(/\./g,"-");r[`--persona-${Bn}`]=pn.value}r["--persona-primary"]=(A=r["--persona-semantic-colors-primary"])!=null?A:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(E=r["--persona-semantic-colors-secondary"])!=null?E:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(T=r["--persona-semantic-colors-accent"])!=null?T:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(S=r["--persona-semantic-colors-surface"])!=null?S:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(k=r["--persona-semantic-colors-background"])!=null?k:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(x=r["--persona-semantic-colors-container"])!=null?x:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(b=r["--persona-semantic-colors-text"])!=null?b:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(h=r["--persona-semantic-colors-text-muted"])!=null?h:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(R=r["--persona-semantic-colors-divider"])!=null?R:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(B=r["--persona-components-voice-recording-indicator"])!=null?B:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(_=r["--persona-components-voice-recording-background"])!=null?_:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(V=r["--persona-components-voice-processing-icon"])!=null?V:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(oe=r["--persona-components-voice-speaking-icon"])!=null?oe:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(be=r["--persona-components-approval-requested-background"])!=null?be:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Qe=r["--persona-components-approval-requested-border"])!=null?Qe:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(je=r["--persona-components-approval-requested-text"])!=null?je:r["--persona-palette-colors-gray-900"],r["--persona-approval-approve-bg"]=(ve=r["--persona-components-approval-approve-background"])!=null?ve:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Ee=r["--persona-components-approval-deny-background"])!=null?Ee:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(Ge=r["--persona-components-attachment-image-background"])!=null?Ge:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(_e=r["--persona-components-attachment-image-border"])!=null?_e:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(X=r["--persona-semantic-typography-fontFamily"])!=null?X:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(Ue=r["--persona-semantic-typography-fontSize"])!=null?Ue:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(K=r["--persona-semantic-typography-fontWeight"])!=null?K:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Te=r["--persona-semantic-typography-lineHeight"])!=null?Te:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(ae=r["--persona-palette-radius-sm"])!=null?ae:"0.125rem",r["--persona-radius-md"]=(xe=r["--persona-palette-radius-md"])!=null?xe:"0.375rem",r["--persona-radius-lg"]=(Me=r["--persona-palette-radius-lg"])!=null?Me:"0.5rem",r["--persona-radius-xl"]=(Ke=r["--persona-palette-radius-xl"])!=null?Ke:"0.75rem",r["--persona-radius-full"]=(ce=r["--persona-palette-radius-full"])!=null?ce:"9999px",r["--persona-launcher-radius"]=(le=(re=r["--persona-components-launcher-borderRadius"])!=null?re:r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-bg"]=(ut=r["--persona-components-launcher-background"])!=null?ut:r["--persona-primary"],r["--persona-launcher-fg"]=(Ce=r["--persona-components-launcher-foreground"])!=null?Ce:r["--persona-text-inverse"],r["--persona-launcher-border"]=(he=r["--persona-components-launcher-border"])!=null?he:r["--persona-border"],r["--persona-button-primary-bg"]=(tt=r["--persona-components-button-primary-background"])!=null?tt:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ne=r["--persona-components-button-primary-foreground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-button-radius"]=(J=(me=r["--persona-components-button-primary-borderRadius"])!=null?me:r["--persona-palette-radius-full"])!=null?J:"9999px",r["--persona-panel-radius"]=(Z=(qe=r["--persona-components-panel-borderRadius"])!=null?qe:r["--persona-radius-xl"])!=null?Z:"0.75rem",r["--persona-panel-border"]=(ge=r["--persona-components-panel-border"])!=null?ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Re=(q=r["--persona-components-panel-shadow"])!=null?q:r["--persona-palette-shadows-xl"])!=null?Re:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-input-radius"]=(fe=(Ae=r["--persona-components-input-borderRadius"])!=null?Ae:r["--persona-radius-lg"])!=null?fe:"0.5rem",r["--persona-message-user-radius"]=(Be=(pe=r["--persona-components-message-user-borderRadius"])!=null?pe:r["--persona-radius-lg"])!=null?Be:"0.5rem",r["--persona-message-assistant-radius"]=(N=(Q=r["--persona-components-message-assistant-borderRadius"])!=null?Q:r["--persona-radius-lg"])!=null?N:"0.5rem",r["--persona-header-bg"]=(ke=r["--persona-components-header-background"])!=null?ke:r["--persona-surface"],r["--persona-header-border"]=(He=r["--persona-components-header-border"])!=null?He:r["--persona-divider"],r["--persona-header-icon-bg"]=(Ve=r["--persona-components-header-iconBackground"])!=null?Ve:r["--persona-primary"],r["--persona-header-icon-fg"]=(Xe=r["--persona-components-header-iconForeground"])!=null?Xe:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(gt=r["--persona-components-header-titleForeground"])!=null?gt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(ot=r["--persona-components-header-subtitleForeground"])!=null?ot:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Mt=r["--persona-components-header-actionIconForeground"])!=null?Mt:r["--persona-muted"];let n=(Xt=t.components)==null?void 0:Xt.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(G=t.components)==null?void 0:G.introCard;r["--persona-intro-card-bg"]=(Jt=r["--persona-components-introCard-background"])!=null?Jt:r["--persona-surface"],r["--persona-intro-card-radius"]=(at=r["--persona-components-introCard-borderRadius"])!=null?at:"1rem",r["--persona-intro-card-padding"]=(Nt=r["--persona-components-introCard-padding"])!=null?Nt:"1.5rem",r["--persona-intro-card-shadow"]=(ye=(de=o==null?void 0:o.shadow)!=null?de:r["--persona-components-introCard-shadow"])!=null?ye:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Rt=r["--persona-components-input-background"])!=null?Rt:r["--persona-surface"],r["--persona-input-placeholder"]=(ar=r["--persona-components-input-placeholder"])!=null?ar:r["--persona-text-muted"],r["--persona-message-user-bg"]=(kt=r["--persona-components-message-user-background"])!=null?kt:r["--persona-accent"],r["--persona-message-user-text"]=(mr=r["--persona-components-message-user-text"])!=null?mr:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Ot=r["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Wt=r["--persona-components-message-assistant-background"])!=null?Wt:r["--persona-surface"],r["--persona-message-assistant-text"]=(St=r["--persona-components-message-assistant-text"])!=null?St:r["--persona-text"],r["--persona-message-assistant-border"]=(Et=r["--persona-components-message-assistant-border"])!=null?Et:r["--persona-border"],r["--persona-message-assistant-shadow"]=(sr=r["--persona-components-message-assistant-shadow"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(dr=(ft=r["--persona-components-scrollToBottom-background"])!=null?ft:r["--persona-button-primary-bg"])!=null?dr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Lr=(wr=r["--persona-components-scrollToBottom-foreground"])!=null?wr:r["--persona-button-primary-fg"])!=null?Lr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(Or=r["--persona-components-scrollToBottom-border"])!=null?Or:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(xt=r["--persona-components-scrollToBottom-size"])!=null?xt:"40px",r["--persona-scroll-to-bottom-radius"]=(Un=(fr=(sn=r["--persona-components-scrollToBottom-borderRadius"])!=null?sn:r["--persona-button-radius"])!=null?fr:r["--persona-radius-full"])!=null?Un:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Zn=(Rr=r["--persona-components-scrollToBottom-shadow"])!=null?Rr:r["--persona-palette-shadows-sm"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Pn=r["--persona-components-scrollToBottom-padding"])!=null?Pn:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(In=r["--persona-components-scrollToBottom-gap"])!=null?In:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(P=(ue=r["--persona-components-scrollToBottom-fontSize"])!=null?ue:r["--persona-palette-typography-fontSize-sm"])!=null?P:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(ee=r["--persona-components-scrollToBottom-iconSize"])!=null?ee:"14px",r["--persona-tool-bubble-shadow"]=(Se=r["--persona-components-toolBubble-shadow"])!=null?Se:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(rt=r["--persona-components-reasoningBubble-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Qt=r["--persona-components-composer-shadow"])!=null?Qt:"none",r["--persona-md-inline-code-bg"]=(Ft=r["--persona-components-markdown-inlineCode-background"])!=null?Ft:r["--persona-container"],r["--persona-md-inline-code-color"]=(tr=r["--persona-components-markdown-inlineCode-foreground"])!=null?tr:r["--persona-text"],r["--persona-md-link-color"]=(_r=(Pr=r["--persona-components-markdown-link-foreground"])!=null?Pr:r["--persona-accent"])!=null?_r:"#0f0f0f";let s=r["--persona-components-markdown-heading-h1-fontSize"];s&&(r["--persona-md-h1-size"]=s);let a=r["--persona-components-markdown-heading-h1-fontWeight"];a&&(r["--persona-md-h1-weight"]=a);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let d=r["--persona-components-markdown-heading-h2-fontWeight"];d&&(r["--persona-md-h2-weight"]=d);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(wn=r["--persona-components-markdown-codeBlock-background"])!=null?wn:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Vt=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Vt:r["--persona-border"],r["--persona-md-code-block-text-color"]=($t=r["--persona-components-markdown-codeBlock-textColor"])!=null?$t:"inherit",r["--persona-md-table-header-bg"]=(Ir=r["--persona-components-markdown-table-headerBackground"])!=null?Ir:r["--persona-container"],r["--persona-md-table-border-color"]=(vn=r["--persona-components-markdown-table-borderColor"])!=null?vn:r["--persona-border"],r["--persona-md-hr-color"]=(bo=r["--persona-components-markdown-hr-color"])!=null?bo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(eo=r["--persona-components-markdown-blockquote-borderColor"])!=null?eo:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(wo=r["--persona-components-markdown-blockquote-background"])!=null?wo:"transparent",r["--persona-md-blockquote-text-color"]=(zn=r["--persona-components-markdown-blockquote-textColor"])!=null?zn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(ln=r["--persona-components-collapsibleWidget-container"])!=null?ln:r["--persona-surface"],r["--cw-surface"]=(Rn=r["--persona-components-collapsibleWidget-surface"])!=null?Rn:r["--persona-surface"],r["--cw-border"]=(Pt=r["--persona-components-collapsibleWidget-border"])!=null?Pt:r["--persona-border"],r["--persona-message-border"]=(gr=r["--persona-components-message-border"])!=null?gr:r["--persona-border"];let p=t.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(r["--persona-icon-btn-bg"]=m.background),m.border&&(r["--persona-icon-btn-border"]=m.border),m.color&&(r["--persona-icon-btn-color"]=m.color),m.padding&&(r["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(r["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(r["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(r["--persona-icon-btn-active-border"]=m.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let I=y.toolbar;I.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=I.iconHoverColor),I.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=I.iconHoverBackground),I.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=I.iconPadding),I.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=I.iconBorderRadius),I.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=I.iconBorder),I.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=I.toggleGroupGap),I.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=I.toggleBorderRadius),I.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=I.copyBackground),I.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=I.copyBorder),I.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=I.copyColor),I.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=I.copyBorderRadius),I.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=I.copyPadding),I.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=I.copyMenuBackground,r["--persona-dropdown-bg"]=(hr=r["--persona-dropdown-bg"])!=null?hr:I.copyMenuBackground),I.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=I.copyMenuBorder,r["--persona-dropdown-border"]=(dn=r["--persona-dropdown-border"])!=null?dn:I.copyMenuBorder),I.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=I.copyMenuShadow,r["--persona-dropdown-shadow"]=(vo=r["--persona-dropdown-shadow"])!=null?vo:I.copyMenuShadow),I.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=I.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Cn=r["--persona-dropdown-radius"])!=null?Cn:I.copyMenuBorderRadius),I.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=I.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Wn=r["--persona-dropdown-item-hover-bg"])!=null?Wn:I.copyMenuItemHoverBackground),I.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=I.iconBackground),I.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=I.toolbarBorder)}if(y!=null&&y.tab){let I=y.tab;I.background&&(r["--persona-artifact-tab-bg"]=I.background),I.activeBackground&&(r["--persona-artifact-tab-active-bg"]=I.activeBackground),I.activeBorder&&(r["--persona-artifact-tab-active-border"]=I.activeBorder),I.borderRadius&&(r["--persona-artifact-tab-radius"]=I.borderRadius),I.textColor&&(r["--persona-artifact-tab-color"]=I.textColor),I.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=I.hoverBackground),I.listBackground&&(r["--persona-artifact-tab-list-bg"]=I.listBackground),I.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=I.listBorderColor),I.listPadding&&(r["--persona-artifact-tab-list-padding"]=I.listPadding)}if(y!=null&&y.pane){let I=y.pane;if(I.toolbarBackground){let pn=(cn=Ba(t,I.toolbarBackground))!=null?cn:I.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pn}}return r}var Qh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var ww={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Yh=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ds=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},vw=t=>{var r;let e=(r=t==null?void 0:t.colorScheme)!=null?r:"light";return e==="light"?"light":e==="dark"?"dark":Ds()},Wp=t=>vw(t),Cw=t=>Ha(t),Aw=t=>{var r;let e=Ha(void 0,{validate:!1});return Ha({...t,palette:{...e.palette,colors:{...ww.colors,...(r=t==null?void 0:t.palette)==null?void 0:r.colors}}},{validate:!1})},Da=t=>{let e=Wp(t),r=Yh(t==null?void 0:t.theme),n=Yh(t==null?void 0:t.darkTheme);return e==="dark"?Aw(Hs(r!=null?r:{},n!=null?n:{})):Cw(r)},Sw=t=>yl(t),Io=(t,e)=>{var s;let r=Da(e),n=Sw(r);for(let[a,i]of Object.entries(n))t.style.setProperty(a,i);let o=(s=e==null?void 0:e.toolCall)==null?void 0:s.shadow;o!==void 0&&t.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},bl=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Ds())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>t(Ds());r.addEventListener?(r.addEventListener("change",n),e.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),e.push(()=>r.removeListener(n)))}return()=>{e.forEach(r=>r())}};var Zh=(function(){"use strict";let t=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:t,afterNodeAdded:t,beforeNodeMorphed:t,afterNodeMorphed:t,beforeNodeRemoved:t,afterNodeRemoved:t,beforeAttributeUpdated:t},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:t,afterHeadMorphed:t},restoreFocus:!0};function r(u,f,y={}){u=p(u);let A=m(f),E=l(u,A,y),T=o(E,()=>i(E,u,A,S=>S.morphStyle==="innerHTML"?(s(S,u,A),Array.from(u.childNodes)):n(S,u,A)));return E.pantry.remove(),T}function n(u,f,y){let A=m(f);return s(u,A,y,f,f.nextSibling),Array.from(A.childNodes)}function o(u,f){var k;if(!u.config.restoreFocus)return f();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return f();let{id:A,selectionStart:E,selectionEnd:T}=y,S=f();return A&&A!==((k=document.activeElement)==null?void 0:k.getAttribute("id"))&&(y=u.target.querySelector(`[id="${A}"]`),y==null||y.focus()),y&&!y.selectionEnd&&T&&y.setSelectionRange(E,T),S}let s=(function(){function u(x,b,h,M=null,W=null){b instanceof HTMLTemplateElement&&h instanceof HTMLTemplateElement&&(b=b.content,h=h.content),M||(M=b.firstChild);for(let R of h.childNodes){if(M&&M!=W){let _=y(x,R,M,W);if(_){_!==M&&E(x,M,_),a(_,R,x),M=_.nextSibling;continue}}if(R instanceof Element){let _=R.getAttribute("id");if(x.persistentIds.has(_)){let V=T(b,_,M,x);a(V,R,x),M=V.nextSibling;continue}}let B=f(b,R,M,x);B&&(M=B.nextSibling)}for(;M&&M!=W;){let R=M;M=M.nextSibling,A(x,R)}}function f(x,b,h,M){if(M.callbacks.beforeNodeAdded(b)===!1)return null;if(M.idMap.has(b)){let W=document.createElement(b.tagName);return x.insertBefore(W,h),a(W,b,M),M.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(b,!0);return x.insertBefore(W,h),M.callbacks.afterNodeAdded(W),W}}let y=(function(){function x(M,W,R,B){let _=null,V=W.nextSibling,oe=0,be=R;for(;be&&be!=B;){if(h(be,W)){if(b(M,be,W))return be;_===null&&(M.idMap.has(be)||(_=be))}if(_===null&&V&&h(be,V)&&(oe++,V=V.nextSibling,oe>=2&&(_=void 0)),M.activeElementAndParents.includes(be))break;be=be.nextSibling}return _||null}function b(M,W,R){let B=M.idMap.get(W),_=M.idMap.get(R);if(!_||!B)return!1;for(let V of B)if(_.has(V))return!0;return!1}function h(M,W){var _,V,oe;let R=M,B=W;return R.nodeType===B.nodeType&&R.tagName===B.tagName&&(!((_=R.getAttribute)!=null&&_.call(R,"id"))||((V=R.getAttribute)==null?void 0:V.call(R,"id"))===((oe=B.getAttribute)==null?void 0:oe.call(B,"id")))}return x})();function A(x,b){var h;if(x.idMap.has(b))k(x.pantry,b,null);else{if(x.callbacks.beforeNodeRemoved(b)===!1)return;(h=b.parentNode)==null||h.removeChild(b),x.callbacks.afterNodeRemoved(b)}}function E(x,b,h){let M=b;for(;M&&M!==h;){let W=M;M=M.nextSibling,A(x,W)}return M}function T(x,b,h,M){var R,B;let W=((B=(R=M.target).getAttribute)==null?void 0:B.call(R,"id"))===b&&M.target||M.target.querySelector(`[id="${b}"]`)||M.pantry.querySelector(`[id="${b}"]`);return S(W,M),k(x,W,h),W}function S(x,b){let h=x.getAttribute("id");for(;x=x.parentNode;){let M=b.idMap.get(x);M&&(M.delete(h),M.size||b.idMap.delete(x))}}function k(x,b,h){if(x.moveBefore)try{x.moveBefore(b,h)}catch{x.insertBefore(b,h)}else x.insertBefore(b,h)}return u})(),a=(function(){function u(S,k,x){return x.ignoreActive&&S===document.activeElement?null:(x.callbacks.beforeNodeMorphed(S,k)===!1||(S instanceof HTMLHeadElement&&x.head.ignore||(S instanceof HTMLHeadElement&&x.head.style!=="morph"?d(S,k,x):(f(S,k,x),T(S,x)||s(x,S,k))),x.callbacks.afterNodeMorphed(S,k)),S)}function f(S,k,x){let b=k.nodeType;if(b===1){let h=S,M=k,W=h.attributes,R=M.attributes;for(let B of R)E(B.name,h,"update",x)||h.getAttribute(B.name)!==B.value&&h.setAttribute(B.name,B.value);for(let B=W.length-1;0<=B;B--){let _=W[B];if(_&&!M.hasAttribute(_.name)){if(E(_.name,h,"remove",x))continue;h.removeAttribute(_.name)}}T(h,x)||y(h,M,x)}(b===8||b===3)&&S.nodeValue!==k.nodeValue&&(S.nodeValue=k.nodeValue)}function y(S,k,x){if(S instanceof HTMLInputElement&&k instanceof HTMLInputElement&&k.type!=="file"){let b=k.value,h=S.value;A(S,k,"checked",x),A(S,k,"disabled",x),k.hasAttribute("value")?h!==b&&(E("value",S,"update",x)||(S.setAttribute("value",b),S.value=b)):E("value",S,"remove",x)||(S.value="",S.removeAttribute("value"))}else if(S instanceof HTMLOptionElement&&k instanceof HTMLOptionElement)A(S,k,"selected",x);else if(S instanceof HTMLTextAreaElement&&k instanceof HTMLTextAreaElement){let b=k.value,h=S.value;if(E("value",S,"update",x))return;b!==h&&(S.value=b),S.firstChild&&S.firstChild.nodeValue!==b&&(S.firstChild.nodeValue=b)}}function A(S,k,x,b){let h=k[x],M=S[x];if(h!==M){let W=E(x,S,"update",b);W||(S[x]=k[x]),h?W||S.setAttribute(x,""):E(x,S,"remove",b)||S.removeAttribute(x)}}function E(S,k,x,b){return S==="value"&&b.ignoreActiveValue&&k===document.activeElement?!0:b.callbacks.beforeAttributeUpdated(S,k,x)===!1}function T(S,k){return!!k.ignoreActiveValue&&S===document.activeElement&&S!==document.body}return u})();function i(u,f,y,A){if(u.head.block){let E=f.querySelector("head"),T=y.querySelector("head");if(E&&T){let S=d(E,T,u);return Promise.all(S).then(()=>{let k=Object.assign(u,{head:{block:!1,ignore:!0}});return A(k)})}}return A(u)}function d(u,f,y){let A=[],E=[],T=[],S=[],k=new Map;for(let b of f.children)k.set(b.outerHTML,b);for(let b of u.children){let h=k.has(b.outerHTML),M=y.head.shouldReAppend(b),W=y.head.shouldPreserve(b);h||W?M?E.push(b):(k.delete(b.outerHTML),T.push(b)):y.head.style==="append"?M&&(E.push(b),S.push(b)):y.head.shouldRemove(b)!==!1&&E.push(b)}S.push(...k.values());let x=[];for(let b of S){let h=document.createRange().createContextualFragment(b.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(h)!==!1){if("href"in h&&h.href||"src"in h&&h.src){let M,W=new Promise(function(R){M=R});h.addEventListener("load",function(){M()}),x.push(W)}u.appendChild(h),y.callbacks.afterNodeAdded(h),A.push(h)}}for(let b of E)y.callbacks.beforeNodeRemoved(b)!==!1&&(u.removeChild(b),y.callbacks.afterNodeRemoved(b));return y.head.afterHeadMorphed(u,{added:A,kept:T,removed:E}),x}let l=(function(){function u(x,b,h){let{persistentIds:M,idMap:W}=S(x,b),R=f(h),B=R.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(B))throw`Do not understand how to morph style ${B}`;return{target:x,newContent:b,config:R,morphStyle:B,ignoreActive:R.ignoreActive,ignoreActiveValue:R.ignoreActiveValue,restoreFocus:R.restoreFocus,idMap:W,persistentIds:M,pantry:y(),activeElementAndParents:A(x),callbacks:R.callbacks,head:R.head}}function f(x){let b=Object.assign({},e);return Object.assign(b,x),b.callbacks=Object.assign({},e.callbacks,x.callbacks),b.head=Object.assign({},e.head,x.head),b}function y(){let x=document.createElement("div");return x.hidden=!0,document.body.insertAdjacentElement("afterend",x),x}function A(x){let b=[],h=document.activeElement;if((h==null?void 0:h.tagName)!=="BODY"&&x.contains(h))for(;h&&(b.push(h),h!==x);)h=h.parentElement;return b}function E(x){var h;let b=Array.from(x.querySelectorAll("[id]"));return(h=x.getAttribute)!=null&&h.call(x,"id")&&b.push(x),b}function T(x,b,h,M){for(let W of M){let R=W.getAttribute("id");if(b.has(R)){let B=W;for(;B;){let _=x.get(B);if(_==null&&(_=new Set,x.set(B,_)),_.add(R),B===h)break;B=B.parentElement}}}}function S(x,b){let h=E(x),M=E(b),W=k(h,M),R=new Map;T(R,W,x,h);let B=b.__idiomorphRoot||b;return T(R,W,B,M),{persistentIds:W,idMap:R}}function k(x,b){let h=new Set,M=new Map;for(let{id:R,tagName:B}of x)M.has(R)?h.add(R):M.set(R,B);let W=new Set;for(let{id:R,tagName:B}of b)W.has(R)?h.add(R):M.get(R)===B&&W.add(R);for(let R of h)W.delete(R);return W}return u})(),{normalizeElement:p,normalizeParent:m}=(function(){let u=new WeakSet;function f(T){return T instanceof Document?T.documentElement:T}function y(T){if(T==null)return document.createElement("div");if(typeof T=="string")return y(E(T));if(u.has(T))return T;if(T instanceof Node){if(T.parentNode)return new A(T);{let S=document.createElement("div");return S.append(T),S}}else{let S=document.createElement("div");for(let k of[...T])S.append(k);return S}}class A{constructor(S){this.originalNode=S,this.realParentNode=S.parentNode,this.previousSibling=S.previousSibling,this.nextSibling=S.nextSibling}get childNodes(){let S=[],k=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;k&&k!=this.nextSibling;)S.push(k),k=k.nextSibling;return S}querySelectorAll(S){return this.childNodes.reduce((k,x)=>{if(x instanceof Element){x.matches(S)&&k.push(x);let b=x.querySelectorAll(S);for(let h=0;h<b.length;h++)k.push(b[h])}return k},[])}insertBefore(S,k){return this.realParentNode.insertBefore(S,k)}moveBefore(S,k){return this.realParentNode.moveBefore(S,k)}get __idiomorphRoot(){return this.originalNode}}function E(T){let S=new DOMParser,k=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(k.match(/<\/html>/)||k.match(/<\/head>/)||k.match(/<\/body>/)){let x=S.parseFromString(T,"text/html");if(k.match(/<\/html>/))return u.add(x),x;{let b=x.firstChild;return b&&u.add(b),b}}else{let b=S.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return u.add(b),b}}return{normalizeElement:f,normalizeParent:y}})();return{morph:r,defaults:e}})();var wl=(t,e,r={})=>{let{preserveTypingAnimation:n=!0}=r;Zh.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var vl={index:-1,draft:""};function ex(t){let{direction:e,history:r,currentValue:n,atStart:o,state:s}=t,a=s.index!==-1;if(r.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:n}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<r.length-1){let i=s.index+1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...vl}}}function tx(t,e){var r,n,o,s,a,i,d,l,p,m,u,f,y,A,E,T,S,k,x,b,h,M,W,R,B,_,V,oe,be,Qe,je,ve,Ee,Ge,_e,X,Ue,K;return[t.id,t.role,(n=(r=t.content)==null?void 0:r.length)!=null?n:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=t.llmContent)==null?void 0:l.length)!=null?p:0,(u=(m=t.approval)==null?void 0:m.status)!=null?u:"",(y=(f=t.toolCall)==null?void 0:f.status)!=null?y:"",(E=(A=t.toolCall)==null?void 0:A.name)!=null?E:"",(k=(S=(T=t.toolCall)==null?void 0:T.chunks)==null?void 0:S.length)!=null?k:0,(M=(h=(b=(x=t.toolCall)==null?void 0:x.chunks)==null?void 0:b[t.toolCall.chunks.length-1])==null?void 0:h.slice(-32))!=null?M:"",typeof((W=t.toolCall)==null?void 0:W.args)=="string"?t.toolCall.args.length:(R=t.toolCall)!=null&&R.args?JSON.stringify(t.toolCall.args).length:0,(V=(_=(B=t.reasoning)==null?void 0:B.chunks)==null?void 0:_.length)!=null?V:0,(je=(Qe=(be=(oe=t.reasoning)==null?void 0:oe.chunks)==null?void 0:be[t.reasoning.chunks.length-1])==null?void 0:Qe.length)!=null?je:0,(_e=(Ge=(Ee=(ve=t.reasoning)==null?void 0:ve.chunks)==null?void 0:Ee[t.reasoning.chunks.length-1])==null?void 0:Ge.slice(-32))!=null?_e:"",(Ue=(X=t.contentParts)==null?void 0:X.length)!=null?Ue:0,(K=t.stopReason)!=null?K:"",e].join("\0")}function rx(){return new Map}function nx(t,e,r){let n=t.get(e);return n&&n.fingerprint===r?n.wrapper:null}function ox(t,e,r,n){t.set(e,{fingerprint:r,wrapper:n})}function ax(t,e){for(let r of t.keys())e.has(r)||t.delete(r)}function Cl(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Os(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function _s(t,e){return Os(t)-t.scrollTop<=e}function Al(t){let{following:e,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=t,p=r-n;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:r}:!e&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Sl(t){let{following:e,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=t;return e&&r<0?"pause":!e&&o&&r>0&&n?"resume":"none"}var Ur={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},zr=1e5,Ro=zr+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Tw=["pre","code","a","script","style"],Tl=t=>{var e,r,n,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Ns.type,placeholder:(r=t==null?void 0:t.placeholder)!=null?r:Ns.placeholder,speed:(n=t==null?void 0:t.speed)!=null?n:Ns.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Ns.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Ns.buffer}},ix=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Fs=new Map;for(let t of ix)Fs.set(t.name,t);var ca=t=>{Fs.set(t.name,t)},Dp=t=>{ix.some(e=>e.name===t)||Fs.delete(t)},Op=()=>Array.from(Fs.keys()),$s=(t,e)=>{var r,n;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(r=e[t])!=null?r:null:(n=Fs.get(t))!=null?n:null},Ml=(t,e,r,n,o)=>{if(!o)return t;if(r!=null&&r.bufferContent)return r.bufferContent(t,n);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
65
+ `);return s<0?"":t.slice(0,s)}return t},Mw=(t,e,r,n)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=e,o},kw=(t,e,r,n)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=e,o},Bp=/\s/,Ew=(t,e)=>{let r=t.parentNode;for(;r;){if(r.nodeType===1){let n=r;if(e.has(n.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Lw=(t,e,r)=>{var d;let n=t.ownerDocument,o=t.parentNode;if(!n||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=0;for(;i<s.length;)if(Bp.test(s[i])){let l=i;for(;l<s.length&&Bp.test(s[l]);)l+=1;a.appendChild(n.createTextNode(s.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Bp.test(s[p]);)l.appendChild(Mw(n,s[p],e,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,t)},Pw=(t,e,r)=>{var d;let n=t.ownerDocument,o=t.parentNode;if(!n||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(n.createTextNode(l)):(a.appendChild(kw(n,l,e,r.value)),r.value+=1));o.replaceChild(a,t)},Us=(t,e,r,n)=>{var m,u;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((m=n==null?void 0:n.skipTags)!=null?m:Tw).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Ew(d,s)||i.push(d),d=a.nextNode();let l={value:(u=n==null?void 0:n.startIndex)!=null?u:0},p=e==="char"?Lw:Pw;for(let f of i)p(f,r,l);return o.innerHTML},kl=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},zs=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let r=t.createElement("div");return r.className="persona-stream-skeleton-line",e.appendChild(r),e},sx=new WeakMap,Iw=(t,e)=>{var s;if(!t.styles)return;let r=sx.get(e);if(r||(r=new Set,sx.set(e,r)),r.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;r.delete(t.name)}r.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Hp=new WeakMap,Rw=(t,e)=>{if(!t.onAttach)return;let r=Hp.get(e);if(r||(r=new Map,Hp.set(e,r)),r.has(t.name))return;let n=t.onAttach(e);r.set(t.name,n)},lx=t=>{let e=Hp.get(t);if(e){for(let r of e.values())typeof r=="function"&&r();e.clear()}},_p=(t,e)=>{Iw(t,e),Rw(t,e)};function Np(t,e=zr){let r=t.style.position,n=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=r),t.style.zIndex=n,t.style.isolation=o}}var qs=0,Wo=null;function Fp(t=document){var r;if(qs++,qs===1){let n=t.body,s=((r=t.defaultView)!=null?r:window).scrollY||t.documentElement.scrollTop;Wo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{var n;if(!e&&(e=!0,qs=Math.max(0,qs-1),qs===0&&Wo)){let o=t.body,s=(n=t.defaultView)!=null?n:window;o.style.overflow=Wo.originalOverflow,o.style.position=Wo.originalPosition,o.style.top=Wo.originalTop,o.style.width=Wo.originalWidth,s.scrollTo(0,Wo.scrollY),Wo=null}}}var El={side:"right",width:"420px",animate:!0,reveal:"resize"},Ar=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="docked"},Bo=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="composer-bar"},kn=t=>{var r,n,o,s,a;let e=(r=t==null?void 0:t.launcher)==null?void 0:r.dock;return{side:(n=e==null?void 0:e.side)!=null?n:El.side,width:(o=e==null?void 0:e.width)!=null?o:El.width,animate:(s=e==null?void 0:e.animate)!=null?s:El.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:El.reveal}};var $n={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Vs=(t,e)=>{let r=v("button");r.type="button",r.innerHTML=`
66
66
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
67
67
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
68
68
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -70,14 +70,14 @@ _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this
70
70
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
71
71
  </span>
72
72
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
73
- `,r.addEventListener("click",t);let n=s=>{var M,b,w,h,k,B,H,W,N,q,se,ve,Ue,je;let a=(M=s.launcher)!=null?M:{},i=Tr(s),d=r.querySelector("[data-role='launcher-title']");if(d){let we=(b=a.title)!=null?b:"Chat Assistant";d.textContent=we,d.setAttribute("title",we)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let we=(w=a.subtitle)!=null?w:"Get answers fast";l.textContent=we,l.setAttribute("title",we)}let p=r.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let we=(h=a.agentIconSize)!=null?h:"40px";if(u.style.height=we,u.style.width=we,u.innerHTML="",a.agentIconName){let Te=parseFloat(we)||24,We=Pe(a.agentIconName,Te*.6,"var(--persona-text-inverse, #ffffff)",2);We?(u.appendChild(We),u.style.display=""):(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",u.style.display="")}let f=r.querySelector("[data-role='launcher-image']");if(f){let we=(H=a.agentIconSize)!=null?H:"40px";f.style.height=we,f.style.width=we,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let we=(W=a.callToActionIconSize)!=null?W:"32px";m.style.height=we,m.style.width=we,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Te=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Te=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let We=parseFloat(we)||24,Oe=Math.max(We-Te,8),K=Pe(a.callToActionIconName,Oe,"currentColor",2);K?m.appendChild(K):m.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}let y=a.position&&Fn[a.position]?Fn[a.position]:Fn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?E:`${v} ${y}`,i||(r.style.zIndex=String((se=a.zIndex)!=null?se:qr));let T="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(ve=a.border)!=null?ve:T,r.style.boxShadow=(Ue=a.shadow)!=null?Ue:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(je=a.collapsedMaxWidth)!=null?je:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},o=()=>{r.removeEventListener("click",t),r.remove()};return e&&n(e),{element:r,update:n,destroy:o}};var tC="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Rl=(e,t={})=>{var v,E,T,A,M,b;let{showClose:r=!0,wrapperClassName:n=tC,buttonSize:o,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=x("div",n),l=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(A=a.closeButtonShowTooltip)!=null?A:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let f=(M=a.closeButtonIconName)!=null?M:"x",m=(b=a.closeButtonIconText)!=null?b:"\xD7";l.style.color=a.closeButtonColor||en.actionIconColor;let y=Pe(f,s,"currentColor",1);if(y?(y.style.display="block",l.appendChild(y)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let w=a.closeButtonBorderWidth||"0px",h=a.closeButtonBorderColor||"transparent";l.style.border=`${w} solid ${h}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&p){let w=null,h=()=>{if(w)return;let B=l.ownerDocument,H=B.body;if(!H)return;w=Yn(B,"div","persona-clear-chat-tooltip"),w.textContent=p;let W=Yn(B,"div");W.className="persona-clear-chat-tooltip-arrow",w.appendChild(W);let N=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(Ro),w.style.left=`${N.left+N.width/2}px`,w.style.top=`${N.top-8}px`,w.style.transform="translate(-50%, -100%)",H.appendChild(w)},k=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};d.addEventListener("mouseenter",h),d.addEventListener("mouseleave",k),l.addEventListener("focus",h),l.addEventListener("blur",k),d._cleanupTooltip=()=>{k(),d.removeEventListener("mouseenter",h),d.removeEventListener("mouseleave",k),l.removeEventListener("focus",h),l.removeEventListener("blur",k)}}return{button:l,wrapper:d}},rC="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wl=(e,t={})=>{var w,h,k,B,H,W,N,q,se,ve,Ue,je,we;let{wrapperClassName:r=rC,buttonSize:n,iconSize:o="20px"}=t,a=(h=((w=e==null?void 0:e.launcher)!=null?w:{}).clearChat)!=null?h:{},i=(k=n!=null?n:a.size)!=null?k:"32px",d=(B=a.iconName)!=null?B:"refresh-cw",l=(H=a.iconColor)!=null?H:"",p=(W=a.backgroundColor)!=null?W:"",u=(N=a.borderWidth)!=null?N:"",f=(q=a.borderColor)!=null?q:"",m=(se=a.borderRadius)!=null?se:"",y=(ve=a.paddingX)!=null?ve:"",v=(Ue=a.paddingY)!=null?Ue:"",E=(je=a.tooltipText)!=null?je:"Clear chat",T=(we=a.showTooltip)!=null?we:!0,A=x("div",r),M=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",E),M.style.color=l||en.actionIconColor;let b=Pe(d,o,"currentColor",1);if(b&&(b.style.display="block",M.appendChild(b)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),u||f){let Te=u||"0px",We=f||"transparent";M.style.border=`${Te} solid ${We}`,M.classList.remove("persona-border-none")}if(m&&(M.style.borderRadius=m,M.classList.remove("persona-rounded-full")),y&&(M.style.paddingLeft=y,M.style.paddingRight=y),v&&(M.style.paddingTop=v,M.style.paddingBottom=v),A.appendChild(M),T&&E){let Te=null,We=()=>{if(Te)return;let K=M.ownerDocument,He=K.body;if(!He)return;Te=Yn(K,"div","persona-clear-chat-tooltip"),Te.textContent=E;let j=Yn(K,"div");j.className="persona-clear-chat-tooltip-arrow",Te.appendChild(j);let Ce=M.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(Ro),Te.style.left=`${Ce.left+Ce.width/2}px`,Te.style.top=`${Ce.top-8}px`,Te.style.transform="translate(-50%, -100%)",He.appendChild(Te)},Oe=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};A.addEventListener("mouseenter",We),A.addEventListener("mouseleave",Oe),M.addEventListener("focus",We),M.addEventListener("blur",Oe),A._cleanupTooltip=()=>{Oe(),A.removeEventListener("mouseenter",We),A.removeEventListener("mouseleave",Oe),M.removeEventListener("focus",We),M.removeEventListener("blur",Oe)}}return{button:M,wrapper:A}};var en={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},go=e=>{var w,h,k,B,H,W,N,q,se,ve,Ue,je,we,Te,We,Oe;let{config:t,showClose:r=!0}=e,n=x("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(w=t==null?void 0:t.launcher)!=null?w:{},s=(h=o.headerIconSize)!=null?h:"48px",a=(k=o.closeButtonPlacement)!=null?k:"inline",i=(B=o.headerIconHidden)!=null?B:!1,d=o.headerIconName,l=x("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let K=parseFloat(s)||24,He=Pe(d,K*.6,"currentColor",1);He?l.replaceChildren(He):l.textContent=(W=(H=t==null?void 0:t.launcher)==null?void 0:H.agentIconText)!=null?W:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let K=x("img");K.src=t.launcher.iconUrl,K.alt="",K.className="persona-rounded-xl persona-object-cover",K.style.height=s,K.style.width=s,l.replaceChildren(K)}else l.textContent=(se=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?se:"\u{1F4AC}";let p=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=x("span","persona-text-base persona-font-semibold");u.style.color=en.titleColor,u.textContent=(Ue=(ve=t==null?void 0:t.launcher)==null?void 0:ve.title)!=null?Ue:"Chat Assistant";let f=x("span","persona-text-xs");f.style.color=en.subtitleColor,f.textContent=(we=(je=t==null?void 0:t.launcher)==null?void 0:je.subtitle)!=null?we:"Here to help you get answers fast",p.append(u,f),i?n.append(p):n.append(l,p);let m=(Te=o.clearChat)!=null?Te:{},y=(We=m.enabled)!=null?We:!0,v=(Oe=m.placement)!=null?Oe:"inline",E=null,T=null;if(y){let He=Wl(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=He.button,T=He.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&n.appendChild(T)}let A=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:M,wrapper:b}=Rl(t,{showClose:r,wrapperClassName:A});return a!=="top-right"&&n.appendChild(b),{header:n,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:M,closeButtonWrapper:b,clearChatButton:E,clearChatButtonWrapper:T}},us=(e,t,r)=>{var a,i,d,l;let n=(a=r==null?void 0:r.launcher)!=null?a:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",s=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Bo(e){let{items:t,onSelect:r,anchor:n,position:o="bottom-left",portal:s}=e,a=x("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ro)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",m.id),m.destructive&&y.setAttribute("data-destructive",""),m.icon){let E=Pe(m.icon,16,"currentColor",1.5);E&&y.appendChild(E)}let v=document.createElement("span");v.textContent=m.label,y.appendChild(v),y.addEventListener("click",E=>{E.stopPropagation(),p(),r(m.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=y=>{!a.contains(y.target)&&!n.contains(y.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function ir(e){let{icon:t,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=x("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",r),d.title=r;let l=Pe(t,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Ja(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=x("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let f=Pe(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=x("span");if(u.textContent=r,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function Xa(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,s=x("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=r,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=ir({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=x("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Hl(e){var m,y;let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=x("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=x("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=Pe(r,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Bo({items:n,onSelect:v=>{l.setAttribute("aria-expanded","false"),o(v)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{p.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Jp=e=>{var n;let t=go({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(r){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>r()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())}))}return t};function nC(e,t,r){var n,o,s;if(t!=null&&t.length)for(let a of t){let i=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=a.ariaLabel)!=null?n:a.label)!=null?o:a.id),a.icon){let d=Pe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=x("div","persona-relative");d.appendChild(i);let l=Bo({items:a.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>r==null?void 0:r(a.id)),e.appendChild(i)}}var Xp=e=>{var A,M,b,w,h,k,B,H,W;let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(A=t==null?void 0:t.launcher)!=null?A:{},i=x("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Hl({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=en.titleColor,p=(b=l.querySelector(".persona-combo-btn-label"))!=null?b:l;else{if(l=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=x("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=en.titleColor,p.textContent=(w=a.title)!=null?w:"Chat Assistant",l.appendChild(p),nC(l,o==null?void 0:o.trailingActions,(h=o==null?void 0:o.onAction)!=null?h:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let q=o.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||q()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),q())})}let N=o==null?void 0:o.titleRowHover;N&&(l.style.borderRadius=(k=N.borderRadius)!=null?k:"10px",l.style.padding=(B=N.padding)!=null?B:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var q,se;l.style.backgroundColor=(q=N.background)!=null?q:"",l.style.borderColor=(se=N.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(H=a.closeButtonSize)!=null?H:"32px",f=x("div",""),m=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=a.closeButtonColor||en.actionIconColor;let y=(W=a.closeButtonIconName)!=null?W:"x",v=Pe(y,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let E=x("div");E.style.display="none";let T=x("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Bl={default:Jp,minimal:Xp},Yp=e=>{var t;return(t=Bl[e])!=null?t:Bl.default},$s=(e,t,r)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=x("div");p.style.display="none";let u=x("span"),f=x("span"),m=x("button");m.style.display="none";let y=x("div");return y.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=t==null?void 0:t.layout)!=null?a:"default",s=Yp(n)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Dl=e=>{var a,i;let t=x("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,n=20;t.style.maxHeight=`${r*n}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:r*n},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Ol=e=>{var w,h,k,B,H,W,N,q,se,ve,Ue,je;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(h=t.useIcon)!=null?h:!1,n=(k=t.iconText)!=null?k:"\u2191",o=t.iconName,s=(B=t.stopIconName)!=null?B:"square",a=(H=t.tooltipText)!=null?H:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(q=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?q:"Send",l=(ve=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?ve:"Stop",p=(Ue=t.showTooltip)!=null?Ue:!1,u=(je=t.size)!=null?je:"40px",f=t.backgroundColor,m=t.textColor,y=x("div","persona-send-button-wrapper"),v=x("button",r?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let E=null,T=null;if(r){v.style.width=u,v.style.height=u,v.style.minWidth=u,v.style.minHeight=u,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",m?v.style.color=m:v.style.color="var(--persona-button-primary-fg, #ffffff)";let we=parseFloat(u)||24,Te=(m==null?void 0:m.trim())||"currentColor";o?(E=Pe(o,we,Te,2),E?v.appendChild(E):v.textContent=n):v.textContent=n,T=Pe(s,we,Te,2),f?v.style.backgroundColor=f:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,m?v.style.color=m:v.classList.add("persona-text-white");t.borderWidth&&(v.style.borderWidth=t.borderWidth,v.style.borderStyle="solid"),t.borderColor&&(v.style.borderColor=t.borderColor),t.paddingX?(v.style.paddingLeft=t.paddingX,v.style.paddingRight=t.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),t.paddingY?(v.style.paddingTop=t.paddingY,v.style.paddingBottom=t.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let A=null;p&&a&&(A=x("div","persona-send-button-tooltip"),A.textContent=a,y.appendChild(A)),v.setAttribute("aria-label",a),y.appendChild(v);let M="send";return{button:v,wrapper:y,setMode:we=>{if(we===M)return;M=we;let Te=we==="stop"?i:a;if(v.setAttribute("aria-label",Te),A&&(A.textContent=Te),r){if(E&&T){let We=we==="stop"?T:E;v.replaceChildren(We)}}else v.textContent=we==="stop"?l:d}}},_l=e=>{var A,M,b,w,h,k,B,H,W,N,q,se;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=t.provider)==null?void 0:M.type)==="runtype";if(!(n||o))return null;let a=(w=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?w:"40px",i=x("div","persona-send-button-wrapper"),d=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(h=t.iconName)!=null?h:"mic",p=(k=t.iconSize)!=null?k:a,u=parseFloat(p)||24,f=(H=t.backgroundColor)!=null?H:(B=e==null?void 0:e.sendButton)==null?void 0:B.backgroundColor,m=(N=t.iconColor)!=null?N:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=Pe(l,u,m||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let E=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((se=t.showTooltip)!=null?se:!1)&&E){let ve=x("div","persona-send-button-tooltip");ve.textContent=E,i.appendChild(ve)}return{button:d,wrapper:i}},Nl=e=>{var y,v,E,T,A,M,b,w;let t=(y=e==null?void 0:e.attachments)!=null?y:{};if(t.enabled!==!0)return null;let r=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",n=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=x("input");o.type="file",o.accept=((T=t.allowedTypes)!=null?T:mo).join(","),o.multiple=((A=t.maxFiles)!=null?A:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=x("div","persona-send-button-wrapper"),a=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(M=t.buttonTooltipText)!=null?M:"Attach file");let i=(b=t.buttonIconName)!=null?b:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Pe(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",h=>{h.preventDefault(),o.click()}),s.appendChild(a);let f=(w=t.buttonTooltipText)!=null?w:"Attach file",m=x("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:o,previewsContainer:n}},$l=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=x("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;n.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=x("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=s;return n},Fl=()=>x("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Fs=e=>{var y,v,E,T,A,M;let{config:t}=e,r=x("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");r.setAttribute("data-persona-theme-zone","composer");let n=Fl(),o=x("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Dl(t);a();let i=Ol(t),d=_l(t),l=Nl(t),p=$l(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=x("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=x("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=x("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(f,m),o.append(u),o.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.target!==(l==null?void 0:l.wrapper)&&s.focus()}),r.append(n,o,p),{footer:r,suggestions:n,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var wx=()=>{let e=x("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=x("span","persona-pill-peek__icon"),r=Pe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let n=x("span","persona-pill-peek__text"),o=x("span","persona-pill-peek__caret"),s=Pe("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,n,o),{root:e,textNode:n}},Cx=e=>{var y,v,E,T,A,M;let{config:t}=e,r=x("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=Fl();n.style.display="none";let o=$l(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Dl(t);s.style.maxHeight="100px",a();let i=Ol(t),d=_l(t),l=Nl(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=x("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let u=x("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let f=x("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,f),l&&r.append(l.previewsContainer),r.append(p,n,o);let m=p;return{footer:r,suggestions:n,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var vx=e=>{var p,u,f,m,y,v,E,T,A,M,b,w,h,k,B,H,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,r=Tr(e);if(Ho(e)){let N=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},q=x("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(y=N.expandedSize)!=null?y:"anchored",q.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:qr);let se=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",q.appendChild(se);let ve=x("div","persona-widget-pill-root");return ve.setAttribute("data-persona-composer-bar",""),ve.dataset.state="collapsed",ve.dataset.expandedSize=(T=N.expandedSize)!=null?T:"anchored",ve.style.zIndex=String((M=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?M:qr),{wrapper:q,panel:se,pillRoot:ve}}if(r){let N=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(q),{wrapper:N,panel:q}}if(!t){let N=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(w=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?w:"100%";return N.style.width=se,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let o=(h=e==null?void 0:e.launcher)!=null?h:{},s=o.position&&Fn[o.position]?Fn[o.position]:Fn["bottom-right"],a=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((B=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?B:qr);let i=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},oC=(e,t)=>{var b,w,h,k,B,H,W,N,q;let r=x("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Rl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(h=(w=(b=e==null?void 0:e.launcher)==null?void 0:b.clearChat)==null?void 0:w.enabled)!=null?h:!0,a=null,i=null;if(s){let se=Wl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=x("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=x("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=x("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let u=x("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(B=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?B:"Hello \u{1F44B}";let f=x("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(W=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",p.append(u,f);let m=x("div","persona-flex persona-flex-col persona-gap-3"),y=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;y&&(m.style.maxWidth=y,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,m);let E=x("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let T=Cx({config:e}),{root:A,textNode:M}=wx();return r.append(d,o,l,E),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:u,introSubtitle:f,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:A,peekTextNode:M}},Sx=(e,t=!0)=>{var E,T,A,M,b,w,h,k,B;if(Ho(e))return oC(e,t);let r=x("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");r.setAttribute("data-persona-theme-zone","container");let n=(E=e==null?void 0:e.layout)==null?void 0:E.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=n?$s(e,n,{showClose:t}):go({config:e,showClose:t}),a=x("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=x("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Tr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=x("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(M=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=x("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(b=e==null?void 0:e.copy)==null?void 0:b.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let p=x("div","persona-flex persona-flex-col persona-gap-3"),u=(h=e==null?void 0:e.layout)==null?void 0:h.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=Fs({config:e}),y=((B=e==null?void 0:e.layout)==null?void 0:B.showFooter)!==!1;o?us(r,s,e):(s.header.style.display="none",us(r,s,e)),r.append(a);let v=x("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",y||(m.footer.style.display="none"),r.append(m.footer),r.append(v),{container:r,body:a,messagesWrapper:p,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var sC=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},aC=(e,t)=>{if(!e)return null;let r=sC(e);if(r===null)return null;let n=t==null?void 0:t[e],o=n!==void 0?n:r;return o||null},iC=(e,t)=>{let r=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},lC=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Qp=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Zp=320,Tx=320,dC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),cC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),pC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),uC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),fC=(e,t,r)=>{if(e.length===0)return null;try{let n=x("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,n.remove(),r==null||r())};return e.forEach((i,d)=>{var u;let l=x("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Zp}px`,l.style.maxHeight=`${Tx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),lC(i.image)?(l.src=i.image,n.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):n}catch{return r==null||r(),null}},mC=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(n=>{if(!Qp(n.audio))return;let o=x("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Zp}px`,t.appendChild(o),r+=1}),r===0?(t.remove(),null):t}catch{return null}},gC=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(n=>{if(!Qp(n.video))return;let o=x("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Zp}px`,o.style.maxHeight=`${Tx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),r+=1}),r===0?(t.remove(),null):t}catch{return null}},hC=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(n=>{if(!Qp(n.data))return;let o=x("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),r+=1}),r===0?(t.remove(),null):t}catch{return null}},fs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(n),e.appendChild(o),e},eu=(e,t,r)=>{let n={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:fs};if(t){let o=t(n);if(o!==null)return o}return fs()},xC=(e,t)=>{let r=x("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=x("img");o.src=n,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(o)}else r.textContent=n,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Ax=(e,t)=>{let r=x("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?r.textContent=t.format(n):r.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},yC=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},tu=(e,t,r)=>{var m,y,v,E,T,A;let n=(m=t.showCopy)!=null?m:!0,o=(y=t.showUpvote)!=null?y:!0,s=(v=t.showDownvote)!=null?v:!0;if(!n&&!o&&!s){let M=x("div");return M.style.display="none",M.id=`actions-${e.id}`,M.setAttribute("data-actions-for",e.id),M}let a=(E=t.visibility)!=null?E:"hover",i=(T=t.align)!=null?T:"right",d=(A=t.layout)!=null?A:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(M,b,w)=>{let h=ir({icon:M,label:b,size:14,className:"persona-message-action-btn"});return h.setAttribute("data-action",w),h};return n&&u.appendChild(f("copy","Copy message","copy")),o&&u.appendChild(f("thumbs-up","Upvote","upvote")),s&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Us=(e,t,r,n,o,s)=>{var K,He,j,Ce,Z,he,xe,Ve,G,ee,Ie,ye,pe,le,Ye,Me,be;let a=r!=null?r:{},i=(K=a.layout)!=null?K:"bubble",d=a.avatar,l=a.timestamp,p=(He=d==null?void 0:d.show)!=null?He:!1,u=(j=l==null?void 0:l.show)!=null?j:!1,f=(Ce=d==null?void 0:d.position)!=null?Ce:"left",m=(Z=l==null?void 0:l.position)!=null?Z:"below",y=yC(e.role,i),v=x("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=dC(e),T=(xe=(he=e.content)==null?void 0:he.trim())!=null?xe:"",M=E.length>0&&T===rl,b=El((G=(Ve=s==null?void 0:s.widgetConfig)==null?void 0:Ve.features)==null?void 0:G.streamAnimation),w=(ye=(Ie=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:Ie.streamAnimation)==null?void 0:ye.plugins,h=e.role==="assistant"&&b.type!=="none"?qa(b.type,w):null,k=e.role==="assistant"&&((pe=h==null?void 0:h.isAnimating)==null?void 0:pe.call(h,e))===!0,B=e.role==="assistant"&&h!==null&&(!!e.streaming||k);B&&(h!=null&&h.bubbleClass)&&v.classList.add(h.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),B&&h&&(h.containerClass&&H.classList.add(h.containerClass),H.style.setProperty("--persona-stream-step",`${b.speed}ms`),H.style.setProperty("--persona-stream-duration",`${b.duration}ms`));let W=B?Ll((le=e.content)!=null?le:"",b.buffer,h,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",N=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;B&&(h==null?void 0:h.wrap)==="char"?q=ja(N,"char",e.id,{skipTags:h.skipTags}):B&&(h==null?void 0:h.wrap)==="word"&&(q=ja(N,"word",e.id,{skipTags:h.skipTags}));let se=null;if(M?(se=document.createElement("div"),se.innerHTML=q,se.style.display="none",H.appendChild(se)):H.innerHTML=q,B&&(h!=null&&h.useCaret)&&!M&&T){let J=Pl(),Ke=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ne=Ke[Ke.length-1];if(ne!=null&&ne.parentNode)ne.parentNode.insertBefore(J,ne.nextSibling);else{let Y=H.lastElementChild;Y?Y.appendChild(J):H.appendChild(J)}}if(u&&m==="inline"&&e.createdAt){let J=Ax(e,l);J.classList.add("persona-ml-2","persona-inline"),H.appendChild(J)}if(E.length>0){let J=fC(E,!M&&!!T,()=>{M&&se&&(se.style.display="")});J?v.appendChild(J):M&&se&&(se.style.display="")}let ve=cC(e);if(ve.length>0){let J=mC(ve);J&&v.appendChild(J)}let Ue=pC(e);if(Ue.length>0){let J=gC(Ue);J&&v.appendChild(J)}let je=uC(e);if(je.length>0){let J=hC(je);J&&v.appendChild(J)}if(v.appendChild(H),u&&m==="below"&&e.createdAt){let J=Ax(e,l);J.classList.add("persona-mt-1"),v.appendChild(J)}let we=e.role==="assistant"?aC(e.stopReason,(be=(Me=s==null?void 0:s.widgetConfig)==null?void 0:Me.copy)==null?void 0:be.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(W&&W.trim()),Ke=b.placeholder==="skeleton",ne=Ke&&b.buffer==="line"&&J;if(J)ne&&v.appendChild(Va());else if(Ke)v.appendChild(Va());else{let Y=eu("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Y&&v.appendChild(Y)}}if(we&&e.stopReason&&!e.streaming&&(T||(H.style.display="none"),v.appendChild(iC(e.stopReason,we))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let J=tu(e,n,o);v.appendChild(J)}if(!p||e.role==="system")return v;let We=x("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Oe=xC(d,e.role);return f==="right"||f==="left"&&e.role==="user"?We.append(v,Oe):We.append(Oe,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),We},Mx=(e,t,r,n,o,s)=>{let a=r!=null?r:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Us(e,t,r,n,o,s)};var zs=new Set,bC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wC=(e,t)=>{var n,o;let r=(o=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
74
- `):""},kx=(e,t)=>{let r=zs.has(e),n=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",r?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Pe(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none",s&&(s.style.display=r?"none":s.textContent||s.childNodes.length?"":"none")},ru=(e,t)=>{var Ue,je,we,Te,We,Oe,K,He,j,Ce,Z;let r=e.reasoning,n=x("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!r)return n;let o=(je=(Ue=t==null?void 0:t.features)==null?void 0:Ue.reasoningDisplay)!=null?je:{},s=o.expandable!==!1,a=s&&zs.has(e.id),i=r.status!=="complete",d=wC(e,(we=o.previewMaxLines)!=null?we:3),l=x("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=x("div","persona-flex persona-flex-col persona-text-left"),u=x("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(Te=t==null?void 0:t.reasoning)!=null?Te:{},y=String((We=r.startedAt)!=null?We:Date.now()),v=()=>{let he=x("span","");return he.setAttribute("data-tool-elapsed",y),he.textContent=Ki(r),he},E=(Oe=m.renderCollapsedSummary)==null?void 0:Oe.call(m,{message:e,reasoning:r,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ki(r),createElapsedElement:v});typeof E=="string"&&E.trim()?(u.textContent=E,p.appendChild(u)):E instanceof HTMLElement?p.appendChild(E):(u.textContent=f,p.appendChild(u));let T=x("span","persona-text-xs persona-text-persona-primary");T.textContent=Uh(r),p.appendChild(T);let A=(K=o.loadingAnimation)!=null?K:"none",M=m.activeTextTemplate,b=m.completeTextTemplate,w=i?M:b,h=E instanceof HTMLElement,k=(he,xe,Ve)=>{let G=Ve;for(let ee of xe){let Ie=x("span","persona-tool-char");Ie.style.setProperty("--char-index",String(G)),Ie.textContent=ee===" "?"\xA0":ee,he.appendChild(Ie),G++}return G},B=(he,xe)=>{u.textContent="";let Ve=Ji(he,""),G=0;for(let ee of Ve){let Ie=ee.styles.length>0?(()=>{let ye=x("span",ee.styles.map(pe=>`persona-tool-text-${pe}`).join(" "));return u.appendChild(ye),ye})():u;if(ee.isDuration&&i)Ie.appendChild(v());else{let ye=ee.isDuration?Ki(r):ee.text;xe?G=k(Ie,ye,G):Ie.appendChild(document.createTextNode(ye))}}};if(!h&&w)if(T.style.display="none",u.style.display="",i&&A!=="none"){let he=(He=m.loadingAnimationDuration)!=null?He:2e3;u.setAttribute("data-preserve-animation","true"),A==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),B(w,!1)):(u.classList.add(`persona-tool-loading-${A}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),B(w,!0))}else B(w,!1);else if(!h&&i&&A!=="none"){u.style.display="";let he=(j=m.loadingAnimationDuration)!=null?j:2e3;if(u.setAttribute("data-preserve-animation","true"),A==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${A}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let xe=u.textContent||f;u.textContent="",k(u,xe,0)}r.status==="complete"&&(u.style.display="none")}else h||(r.status==="complete"?u.style.display="none":u.style.display="");let H=null;if(s){H=x("div","persona-flex persona-items-center");let xe=Pe(a?"chevron-up":"chevron-down",16,"currentColor",2);xe?H.appendChild(xe):H.textContent=a?"Hide":"Show";let Ve=x("div","persona-flex persona-items-center persona-ml-auto");Ve.append(H),l.append(p,Ve)}else l.append(p);let W=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let he=(Z=(Ce=t==null?void 0:t.reasoning)==null?void 0:Ce.renderCollapsedPreview)==null?void 0:Z.call(Ce,{message:e,reasoning:r,defaultPreview:d,isActive:i,config:t!=null?t:{}});bC(W,he)||(W.textContent=d),W.style.display=""}if(!a&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!s)return n.append(l,W),n;let N=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=a?"":"none";let q=r.chunks.join(""),se=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return se.textContent=q||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(se),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),H){H.innerHTML="";let xe=Pe(a?"chevron-up":"chevron-down",16,"currentColor",2);xe?H.appendChild(xe):H.textContent=a?"Hide":"Show"}N.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),n.append(l,W,N),n};var qs=new Set,CC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),vC=(e,t)=>{var s;let r=e.toolCall;if(!r)return"";let n=((s=r.chunks)!=null?s:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
75
- `);let o=Hs(r.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
76
- `):""},SC=(e,t)=>{var p,u,f,m,y;let r=e.toolCall,n=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=n==null?void 0:n.collapsedMode)!=null?u:"tool-call",s=vC(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=r?zh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return o==="tool-name"?l=((y=r.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=$d(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=$d(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Ex=(e,t,r)=>{var p;let n=qs.has(e),o=(p=r==null?void 0:r.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",n?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"currentColor",f=Pe(n?"chevron-up":"chevron-down",16,u,2);f?l.appendChild(f):l.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},nu=(e,t)=>{var q,se,ve,Ue,je,we,Te,We,Oe;let r=e.toolCall,n=(q=t==null?void 0:t.toolCall)!=null?q:{},o=x("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!r)return o;let s=(ve=(se=t==null?void 0:t.features)==null?void 0:se.toolCallDisplay)!=null?ve:{},a=s.expandable!==!1,i=a&&qs.has(e.id),{summary:d,previewText:l,isActive:p}=SC(e,t),u=x("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(u.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(u.style.paddingLeft=n.headerPaddingX,u.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(u.style.paddingTop=n.headerPaddingY,u.style.paddingBottom=n.headerPaddingY);let f=x("div","persona-flex persona-flex-col persona-text-left"),m=x("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let y=String((Ue=r.startedAt)!=null?Ue:Date.now()),v=()=>{let K=x("span","");return K.setAttribute("data-tool-elapsed",y),K.textContent=Ha(r),K},E=(we=n.renderCollapsedSummary)==null?void 0:we.call(n,{message:e,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(je=s.collapsedMode)!=null?je:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ha(r),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,f.appendChild(m)):E instanceof HTMLElement?f.appendChild(E):(m.textContent=d,f.appendChild(m));let T=(Te=s.loadingAnimation)!=null?Te:"none",A=n.activeTextTemplate,M=n.completeTextTemplate,b=p?A:M,w=E instanceof HTMLElement,h=(K,He,j)=>{let Ce=j;for(let Z of He){let he=x("span","persona-tool-char");he.style.setProperty("--char-index",String(Ce)),he.textContent=Z===" "?"\xA0":Z,K.appendChild(he),Ce++}return Ce},k=(K,He)=>{var he;m.textContent="";let j=((he=r.name)==null?void 0:he.trim())||"tool",Ce=Ji(K,j),Z=0;for(let xe of Ce){let Ve=xe.styles.length>0?(()=>{let G=x("span",xe.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(G),G})():m;if(xe.isDuration&&p)Ve.appendChild(v());else{let G=xe.isDuration?Ha(r):xe.text;He?Z=h(Ve,G,Z):Ve.appendChild(document.createTextNode(G))}}};if(!w)if(p&&T!=="none"){let K=(We=n.loadingAnimationDuration)!=null?We:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),b&&k(b,!1);else if(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),T==="shimmer-color"&&(n.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)k(b,!0);else{let He=m.textContent||d;m.textContent="",h(m,He,0)}}else b&&k(b,!1);let B=null;if(a){B=x("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",He=Pe(i?"chevron-up":"chevron-down",16,K,2);He?B.appendChild(He):B.textContent=i?"Hide":"Show";let j=x("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");j.append(B),u.append(f,j)}else u.append(f);let H=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let K=(Oe=n.renderCollapsedPreview)==null?void 0:Oe.call(n,{message:e,toolCall:r,defaultPreview:l,isActive:p,config:t!=null?t:{}});CC(H,K)||(H.textContent=l),H.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,H),o;let W=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",n.contentBackgroundColor&&(W.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(W.style.color=n.contentTextColor),n.contentPaddingX&&(W.style.paddingLeft=n.contentPaddingX,W.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(W.style.paddingTop=n.contentPaddingY,W.style.paddingBottom=n.contentPaddingY),r.name){let K=x("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=r.name,W.appendChild(K)}if(r.args!==void 0){let K=x("div","persona-space-y-1"),He=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(He.style.color=n.labelTextColor),He.textContent="Arguments";let j=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(j.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(j.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(j.style.color=n.codeBlockTextColor),j.textContent=Hs(r.args),K.append(He,j),W.appendChild(K)}if(r.chunks&&r.chunks.length){let K=x("div","persona-space-y-1"),He=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(He.style.color=n.labelTextColor),He.textContent="Activity";let j=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(j.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(j.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(j.style.color=n.codeBlockTextColor),j.textContent=r.chunks.join(""),K.append(He,j),W.appendChild(K)}if(r.status==="complete"&&r.result!==void 0){let K=x("div","persona-space-y-1"),He=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(He.style.color=n.labelTextColor),He.textContent="Result";let j=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(j.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(j.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(j.style.color=n.codeBlockTextColor),j.textContent=Hs(r.result),K.append(He,j),W.appendChild(K)}if(r.status==="complete"&&typeof r.duration=="number"){let K=x("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${r.duration}ms`,W.appendChild(K)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),B){B.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",He=Pe(i?"chevron-up":"chevron-down",16,K,2);He?B.appendChild(He):B.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),o.append(u,H,W),o};var Do=ud(ji(),1);var su="ask_user_question",ou=8,js="data-persona-ask-sheet-for",AC="Other",TC="Other\u2026",Px="Type your own answer here",Ix="Send",MC="Next",kC="Back",EC="Submit all",LC="Skip",PC=3,au="data-ask-current-index",iu="data-ask-question-count",Rx="data-ask-answers",lu="data-ask-grouped",Wx="data-ask-layout",IC=e=>e.layout==="pills"?"pills":"rows",RC=e=>e.getAttribute(Wx)==="pills"?"pills":"rows",Lx=!1,Hx=e=>e.replace(/["\\]/g,"\\$&"),ho=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===su,Ul=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},xo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:r};try{let o=n.join(""),s=(0,Do.parse)(o,Do.STR|Do.OBJ|Do.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},Ya=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ou&&!Lx&&(Lx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ou}.`)),t.slice(0,ou)},WC=e=>{var t;return(t=Ya(e)[0])!=null?t:null},HC=(e,t)=>{var r;return(r=Ya(e)[t])!=null?r:null},Bx=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Dx=(e,t,r)=>{if(e!=="rows")return null;let n=x("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let o=x("span","persona-ask-row-check");n.appendChild(o)}else{let o=x("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},BC=(e,t,r,n)=>{let s=x("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",n?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),r==="rows"){let a=x("span","persona-ask-row-content"),i=x("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=x("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Dx(r,n,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},DC=e=>{let r=x("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},OC=(e,t,r,n)=>{var p,u,f;let s=x("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!r){for(let m=0;m<PC;m++)s.appendChild(DC(n));return s}if(d.forEach((m,y)=>{s.appendChild(BC(m,y,n,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=n==="rows"?AC:TC;if(n==="rows"){let y=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let v=x("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:Px,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),v.appendChild(E),y.appendChild(v);let T=Dx(n,a,d.length);T&&y.appendChild(T),s.appendChild(y)}else{let y=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(f=t.freeTextLabel)!=null?f:m,s.appendChild(y)}}return s},Ox=(e,t)=>{var s,a;let n=x("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:Px,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),t!=="rows"){let i=x("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Ix,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},_C=e=>{var n;let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=x("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=e.submitLabel)!=null?n:Ix,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},NC=(e,t,r)=>{var l,p,u,f;let n=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=x("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:kC,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,n.appendChild(o);let s=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=x("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:LC,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=x("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=r.submitAllLabel)!=null?u:EC:(f=r.nextLabel)!=null?f:MC,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},ms=e=>{let t=e.getAttribute(Rx);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},_x=(e,t)=>{e.setAttribute(Rx,JSON.stringify(t))},En=e=>{var r;let t=Number((r=e.getAttribute(au))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},$C=(e,t)=>{e.setAttribute(au,String(Math.max(0,Math.floor(t))))},Vs=e=>{var r;let t=Number((r=e.getAttribute(iu))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Oo=e=>e.getAttribute(lu)==="true",FC=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let n={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let d=r[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},UC=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},zl=(e,t)=>{let{payload:r}=xo(t),n=Ya(r),o=ms(e),s={},a=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Nx=e=>{let t=ms(e),r=En(e),n=t[r],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!a.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},$x=e=>{if(!Oo(e))return;let t=ms(e),r=En(e),n=t[r],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},du=(e,t,r)=>{let n=Ul(r),o=RC(e),{payload:s,complete:a}=xo(t),i=Oo(e),d=En(e),l=Vs(e),p=i?HC(s,d):WC(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=A,y.classList.toggle("persona-ask-question-skeleton",!A&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let A=OC(p,n,a,o);v.replaceWith(A)}if(o!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Ox(n,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(_C(n)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=NC(d,l,n);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();Nx(e),$x(e)},zC=(e,t,r)=>{let n=Ul(t),o=IC(n),s=e.toolCall.id,a=Ya(r),i=Math.max(1,a.length),d=i>1,l=FC(e,a),p=d?UC(e,i):0,u=x("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(js,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(iu,String(i)),u.setAttribute(au,String(p)),u.setAttribute(lu,d?"true":"false"),u.setAttribute(Wx,o),_x(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Bx(u,n);let f=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=x("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let y=x("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),u.appendChild(f);let E=x("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(Ox(n,o)),du(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},qC=(e,t,r)=>{let{payload:n}=xo(t),o=Math.max(1,Ya(n).length);o>Vs(e)&&(e.setAttribute(iu,String(o)),o>1&&!Oo(e)&&e.setAttribute(lu,"true")),du(e,t,r)},Fx=(e,t)=>{let r=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Ul(t);Bx(r,n);let o=x("span","persona-ask-stub-label"),{complete:s}=xo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},Gs=(e,t,r)=>{if(!r||!ho(e)||Ul(t).enabled===!1)return;let o=e.toolCall.id;r.querySelectorAll(`[${js}]`).forEach(l=>{l.getAttribute(js)!==o&&l.remove()});let a=r.querySelector(`[${js}="${Hx(o)}"]`);if(a){qC(a,e,t);return}let{payload:i}=xo(e),d=zC(e,t,i);r.appendChild(d)},_o=(e,t)=>{if(!e)return;let r=t?`[${js}="${Hx(t)}"]`:`[${js}]`;e.querySelectorAll(r).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},cu=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),No=(e,t)=>{let r=ms(e),n=En(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[n]:r[n]=t,_x(e,r),Nx(e),$x(e)},ql=(e,t,r,n)=>{let o=Vs(e),s=Math.max(0,Math.min(o-1,n));$C(e,s),du(e,t,r)};var pu=(e,t)=>{var v,E,T,A,M,b,w,h,k,B,H,W;let r=e.approval,n=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=x("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(v=n==null?void 0:n.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=n==null?void 0:n.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!r)return s;let a=x("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=x("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(T=n==null?void 0:n.titleColor)!=null?T:"currentColor",p=Pe(d,20,l,2);p&&i.appendChild(p);let u=x("div","persona-flex-1 persona-min-w-0"),f=x("div","persona-flex persona-items-center persona-gap-2"),m=x("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(A=n==null?void 0:n.title)!=null?A:"Approval Required",f.appendChild(m),!o){let N=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");N.setAttribute("data-approval-status",r.status),r.status==="approved"?(N.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",N.style.color="var(--persona-palette-colors-success-700, #15803d)",N.textContent="Approved"):r.status==="denied"?(N.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",N.style.color="var(--persona-palette-colors-error-700, #b91c1c)",N.textContent="Denied"):r.status==="timeout"&&(N.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",N.style.color="var(--persona-palette-colors-warning-700, #b45309)",N.textContent="Timeout"),f.appendChild(N)}u.appendChild(f);let y=x("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(y.style.color=n.descriptionColor),y.textContent=r.description,u.appendChild(y),r.parameters){let N=x("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(N.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(N.style.color=n.parameterTextColor),N.style.fontSize="0.75rem",N.style.lineHeight="1rem",N.textContent=Hs(r.parameters),u.appendChild(N)}if(o){let N=x("div","persona-flex persona-gap-2 persona-mt-2");N.setAttribute("data-approval-buttons","true");let q=x("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");q.type="button",q.style.backgroundColor=(M=n==null?void 0:n.approveButtonColor)!=null?M:"var(--persona-approval-approve-bg, #22c55e)",q.style.color=(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",q.setAttribute("data-approval-action","approve");let se=Pe("shield-check",14,(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",2);se&&(se.style.marginRight="4px",q.appendChild(se));let ve=document.createTextNode((h=n==null?void 0:n.approveLabel)!=null?h:"Approve");q.appendChild(ve);let Ue=x("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Ue.type="button",Ue.style.backgroundColor=(k=n==null?void 0:n.denyButtonColor)!=null?k:"transparent",Ue.style.color=(B=n==null?void 0:n.denyButtonTextColor)!=null?B:"var(--persona-feedback-error, #dc2626)",Ue.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ue.setAttribute("data-approval-action","deny");let je=Pe("shield-x",14,(H=n==null?void 0:n.denyButtonTextColor)!=null?H:"var(--persona-feedback-error, #dc2626)",2);je&&(je.style.marginRight="4px",Ue.appendChild(je));let we=document.createTextNode((W=n==null?void 0:n.denyLabel)!=null?W:"Deny");Ue.appendChild(we),N.append(q,Ue),u.appendChild(N)}return a.append(i,u),s.appendChild(a),s};var Ux=e=>{let t=[];return{buttons:t,render:(n,o,s,a,i)=>{if(e.innerHTML="",t.length=0,!n||!n.length||(a!=null?a:o?o.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=o?o.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let y=x("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");y.type="button",y.textContent=m,y.disabled=u,i!=null&&i.fontFamily&&(y.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(y.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(y.style.paddingLeft=i.paddingX,y.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(y.style.paddingTop=i.paddingY,y.style.paddingBottom=i.paddingY),y.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),p.appendChild(y),t.push(y)}),e.appendChild(p)}}};var Qa=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let n of r)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Za=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,t()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)n.put(o)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(n){r(n)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{t()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)n.put(o)}catch{}}};var jC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),VC=new Set(["step_start","execution_start"]),GC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),KC=new Set(["step_complete","agent_turn_complete"]),JC=new Set(["flow_complete","agent_complete"]),zx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,gs=(e,t)=>{let r=e[t];return jx(r)?r:void 0};function uu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function jl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function XC(e,t){return typeof t.type=="string"?t.type:e}function YC(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function QC(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function qx(e){var n,o,s,a,i;let t=gs(e,"result"),r=[gs(e,"tokens"),gs(e,"totalTokens"),t?gs(t,"tokens"):void 0,gs(e,"usage"),t?gs(t,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=bn(d.output))!=null?n:bn(d.outputTokens))!=null?o:bn(d.completionTokens);if(l!==void 0)return l}return(i=(s=bn(e.outputTokens))!=null?s:bn(e.completionTokens))!=null?i:t?(a=bn(t.outputTokens))!=null?a:bn(t.completionTokens):void 0}function ZC(e){var r,n,o,s,a;let t=gs(e,"result");return(a=(o=(n=(r=bn(e.executionTime))!=null?r:bn(e.executionTimeMs))!=null?n:bn(e.execution_time))!=null?o:bn(e.duration))!=null?a:t?(s=bn(t.executionTime))!=null?s:bn(t.executionTimeMs):void 0}function ev(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ei=class{constructor(t=ev){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:jl(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,r){var s;if(!jx(r)){zx.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=XC(t,r),o=this.now();if(jC.has(n)){this.startRun(o);return}if(VC.has(n)){this.run||this.startRun(o);return}if(GC.has(n)){if(!QC(n,r))return;let a=YC(r);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+uu(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:jl(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(KC.has(n)){if(!this.run)return;let a=this.run,i=qx(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+uu(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:jl(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(JC.has(n)){if(!this.run)return;let a=this.run,i=qx(r),d=i!=null?i:a.exactOutputTokens+uu(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:jl(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(zx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,n){let o=t.firstDeltaAt!==void 0?n-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=ZC(r);return s!=null?s:n-t.startedAt}};function Ks(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var tv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},rv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},nv=["flowName","stepName","reasoningText","text","name","tool","toolName"],ov=100;function sv(e,t){let r={...tv,...t};if(r[e])return r[e];for(let n of Object.keys(r))if(n.endsWith("_")&&e.startsWith(n))return r[n];return rv}function av(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function iv(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),n=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${n}:${o}.${s}`}function lv(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let n of t){let o=n.split("."),s=r;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function dv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),r()})}function cv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function pv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function uv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function fv(e,t,r){let n,o;try{o=JSON.parse(e.payload),n=JSON.stringify(o,null,2)}catch{o=e.payload,n=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let i=s.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=x("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=x("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function fu(e,t,r,n,o,s,a,i){var f;let d=o.has(e.id),l=x("div","persona-border-b persona-border-persona-divider persona-text-xs");Ks(l,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var q,se;let m=x("div",""),y=x("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");y.setAttribute("data-event-id",e.id);let v=x("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Pe(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let T=x("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(q=n.timestampFormat)!=null?q:"relative";T.textContent=A==="relative"?av(e.timestamp,r):iv(e.timestamp);let M=null;n.showSequenceNumbers!==!1&&(M=x("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let b=sv(e.type,n.badgeColors),w=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=b.bg,w.style.color=b.text,w.style.borderColor=b.text+"50",w.textContent=e.type;let h=(se=n.descriptionFields)!=null?se:nv,k=lv(e.payload,h),B=null;k&&(B=x("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=k);let H=x("div","persona-flex-1 persona-min-w-0"),W=x("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=Pe("clipboard","12px","currentColor",1.5);return N&&W.appendChild(N),W.addEventListener("click",async ve=>{ve.stopPropagation(),await dv(cv(e)),W.innerHTML="";let Ue=Pe("check","12px","currentColor",1.5);Ue&&W.appendChild(Ue),setTimeout(()=>{W.innerHTML="";let je=Pe("clipboard","12px","currentColor",1.5);je&&W.appendChild(je)},1500)}),y.appendChild(v),y.appendChild(T),M&&y.appendChild(M),y.appendChild(w),B&&y.appendChild(B),y.appendChild(H),y.appendChild(W),m.appendChild(y),d&&m.appendChild(fv(e,a,i)),m}}function Vx(e){var y,v,E,T,A;let{buffer:t,getFullHistory:r,onClose:n,config:o,plugins:s=[],getThroughput:a}=e,i=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",u=(A=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?A:{},f=s.find(M=>M.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let M=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return m();function m(){let M=u.classNames,b=x("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ks(b,M==null?void 0:M.panel);let w=[],h="",k="",B=null,H=[],W={},N=0,q=Tl(),se=0,ve=0,Ue=!1,je=null,we=!1,Te=0,We=new Set,Oe=new Map,K="",He="",j=null,Ce,Z,he,xe,Ve,G=null,ee=null,Ie=null;function ye(){let fe=x("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Se=x("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ks(Se,M==null?void 0:M.headerBar);let Wt=x("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Wt.textContent="Events",Ce=x("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Ce.textContent="0",a){ee=x("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let cr=x("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");cr.textContent="Throughput",G=x("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),G.textContent="-- tok/s",Ie=x("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Ie.style.display="none",Ie.style.pointerEvents="none";let Cr=ee,Lr=Ie,_r=()=>{if(!Lr.textContent)return;let an=Cr.getBoundingClientRect(),mr=fe.getBoundingClientRect();Lr.style.left=`${an.left-mr.left}px`,Lr.style.top=`${an.bottom-mr.top+4}px`,Lr.style.display="block"},xt=()=>{Lr.style.display="none"};ee.addEventListener("mouseenter",_r),ee.addEventListener("mouseleave",xt),ee.appendChild(cr),ee.appendChild(G)}let sr=x("div","persona-flex-1");Z=x("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Et=x("option","");Et.value="",Et.textContent="All events",Z.appendChild(Et),he=x("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),he.type="button",he.title="Copy All";let _t=Pe("clipboard-copy","12px","currentColor",1.5);_t&&he.appendChild(_t);let Ht=x("span","persona-text-xs");Ht.textContent="Copy All",he.appendChild(Ht),Se.appendChild(Wt),Se.appendChild(Ce),ee&&Se.appendChild(ee),Se.appendChild(sr),Se.appendChild(Z),Se.appendChild(he);let Tt=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ks(Tt,M==null?void 0:M.searchBar);let Lt=Pe("search","14px","var(--persona-muted, #9ca3af)",1.5),ar=x("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Lt&&ar.appendChild(Lt),xe=x("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ks(xe,M==null?void 0:M.searchInput),xe.type="text",xe.placeholder="Search event payloads...",Ve=x("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ve.type="button",Ve.style.display="none";let mt=Pe("x","12px","currentColor",2);return mt&&Ve.appendChild(mt),Tt.appendChild(ar),Tt.appendChild(xe),Tt.appendChild(Ve),fe.appendChild(Se),fe.appendChild(Tt),Ie&&fe.appendChild(Ie),fe}let pe,le=s.find(fe=>fe.renderEventStreamToolbar);if(le!=null&&le.renderEventStreamToolbar&&o){let fe=le.renderEventStreamToolbar({config:o,defaultRenderer:()=>ye(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Se=>{h=Se,ue(),te()},onSearchChange:Se=>{k=Se,ue(),te()}});pe=fe!=null?fe:ye()}else pe=ye();let Ye=x("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ye.style.display="none";function Me(){if(!a||!G||!ee)return;let fe=a();G.textContent=pv(fe);let Se=uv(fe);Ie&&(Ie.textContent=Se,Se||(Ie.style.display="none")),Se?ee.setAttribute("aria-label",Se):ee.removeAttribute("aria-label")}let be=x("div","persona-flex-1 persona-min-h-0 persona-relative"),J=x("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let Ke=x("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ks(Ke,M==null?void 0:M.scrollIndicator),Ke.style.display="none",Ke.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let ne=Pe(l,"14px","currentColor",2);ne&&Ke.appendChild(ne);let Y=x("span","");Y.textContent=p,Ke.appendChild(Y);let Q=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Q.style.display="none",be.appendChild(J),be.appendChild(Q),be.appendChild(Ke),b.setAttribute("tabindex","0"),b.appendChild(pe),b.appendChild(Ye),b.appendChild(be);function Be(){let fe=t.getAll(),Se={};for(let Ht of fe)Se[Ht.type]=(Se[Ht.type]||0)+1;let Wt=Object.keys(Se).sort(),sr=Wt.length!==H.length||!Wt.every((Ht,Tt)=>Ht===H[Tt]),Et=!sr&&Wt.some(Ht=>Se[Ht]!==W[Ht]),gr=fe.length!==Object.values(W).reduce((Ht,Tt)=>Ht+Tt,0);if(!sr&&!Et&&!gr||(H=Wt,W=Se,!Z))return;let _t=Z.value;if(Z.options[0].textContent="All events",sr){for(;Z.options.length>1;)Z.remove(1);for(let Ht of Wt){let Tt=x("option","");Tt.value=Ht,Tt.textContent=`${Ht} (${Se[Ht]||0})`,Z.appendChild(Tt)}_t&&Wt.includes(_t)?Z.value=_t:_t&&(Z.value="",h="")}else for(let Ht=1;Ht<Z.options.length;Ht++){let Tt=Z.options[Ht];Tt.textContent=`${Tt.value} (${Se[Tt.value]||0})`}}function ke(){let fe=t.getAll();if(h&&(fe=fe.filter(Se=>Se.type===h)),k){let Se=k.toLowerCase();fe=fe.filter(Wt=>Wt.type.toLowerCase().includes(Se)||Wt.payload.toLowerCase().includes(Se))}return fe}function ge(){return h!==""||k!==""}function ue(){N=0,se=0,q.resume(),Ke.style.display="none"}function _e(fe){We.has(fe)?We.delete(fe):We.add(fe),j=fe;let Se=J.scrollTop,Wt=q.isFollowing();we=!0,q.pause(),te(),J.scrollTop=Se,Wt&&q.resume(),we=!1}function I(){return Fa(J,50)}function te(){ve=Date.now(),Ue=!1,Me(),Be();let fe=t.getEvictedCount();fe>0?(Ye.textContent=`${fe.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",w=ke();let Se=w.length,Wt=t.getSize()>0;Ce&&(Ce.textContent=String(t.getSize())),Se===0&&Wt&&ge()?(Q.textContent=k?`No events matching '${k}'`:"No events matching filter",Q.style.display="",J.style.display="none"):(Q.style.display="none",J.style.display=""),he&&(he.title=ge()?`Copy Filtered (${Se})`:"Copy All"),d&&!q.isFollowing()&&Se>N&&(se+=Se-N,Y.textContent=p?`${p}${se>0?` (${se})`:""}`:"",Ke.style.display=""),N=Se;let sr=t.getAll(),Et=sr.length>0?sr[0].timestamp:0,gr=new Set(w.map(Tt=>Tt.id));for(let Tt of We)gr.has(Tt)||We.delete(Tt);let _t=h!==K||k!==He,Ht=Oe.size===0&&w.length>0;if(_t||Ht||w.length===0){J.innerHTML="",Oe.clear();let Tt=document.createDocumentFragment();for(let Lt=0;Lt<w.length;Lt++){let ar=fu(w[Lt],Lt,Et,u,We,_e,s,o);Oe.set(w[Lt].id,ar),Tt.appendChild(ar)}J.appendChild(Tt),K=h,He=k,j=null}else{if(j!==null){let Lt=Oe.get(j);if(Lt&&Lt.parentNode===J){let ar=w.findIndex(mt=>mt.id===j);if(ar>=0){let mt=fu(w[ar],ar,Et,u,We,_e,s,o);J.insertBefore(mt,Lt),Lt.remove(),Oe.set(j,mt)}}j=null}let Tt=new Set(w.map(Lt=>Lt.id));for(let[Lt,ar]of Oe)Tt.has(Lt)||(ar.remove(),Oe.delete(Lt));for(let Lt=0;Lt<w.length;Lt++){let ar=w[Lt];if(!Oe.has(ar.id)){let mt=fu(ar,Lt,Et,u,We,_e,s,o);Oe.set(ar.id,mt),J.appendChild(mt)}}}q.isFollowing()&&(J.scrollTop=J.scrollHeight)}function qe(){if(Date.now()-ve>=ov){je!==null&&(cancelAnimationFrame(je),je=null),te();return}Ue||(Ue=!0,je=requestAnimationFrame(()=>{je=null,te()}))}let tt=(fe,Se)=>{if(!he)return;he.innerHTML="";let Wt=Pe(fe,"12px","currentColor",1.5);Wt&&he.appendChild(Wt);let sr=x("span","persona-text-xs");sr.textContent="Copy All",he.appendChild(sr),setTimeout(()=>{he.innerHTML="";let Et=Pe("clipboard-copy","12px","currentColor",1.5);Et&&he.appendChild(Et);let gr=x("span","persona-text-xs");gr.textContent="Copy All",he.appendChild(gr),he.disabled=!1},Se)},Xe=async()=>{if(he){he.disabled=!0;try{let fe;ge()?fe=w:r?(fe=await r(),fe.length===0&&(fe=t.getAll())):fe=t.getAll();let Se=fe.map(Wt=>{try{return JSON.parse(Wt.payload)}catch{return Wt.payload}});await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),tt("check",1500)}catch{tt("x",1500)}}},Je=()=>{Z&&(h=Z.value,ue(),te())},pt=()=>{!xe||!Ve||(Ve.style.display=xe.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{k=xe.value,ue(),te()},150))},ht=()=>{!xe||!Ve||(xe.value="",k="",Ve.style.display="none",B&&clearTimeout(B),ue(),te())},zt=()=>{if(we)return;let fe=J.scrollTop,{action:Se,nextLastScrollTop:Wt}=Ml({following:q.isFollowing(),currentScrollTop:fe,lastScrollTop:Te,nearBottom:I(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Te=Wt,Se==="resume"?(q.resume(),se=0,Ke.style.display="none"):Se==="pause"&&(q.pause(),d&&(Y.textContent=p,Ke.style.display=""))},or=fe=>{let Se=kl({following:q.isFollowing(),deltaY:fe.deltaY,nearBottom:I(),resumeWhenNearBottom:!0});Se==="pause"?(q.pause(),d&&(Y.textContent=p,Ke.style.display="")):Se==="resume"&&(q.resume(),se=0,Ke.style.display="none")},X=()=>{d&&(J.scrollTop=J.scrollHeight,q.resume(),se=0,Ke.style.display="none")},kt=fe=>{let Se=fe.target;if(!Se||Se.closest("button"))return;let Wt=Se.closest("[data-event-id]");if(!Wt)return;let sr=Wt.getAttribute("data-event-id");sr&&_e(sr)},ct=fe=>{if((fe.metaKey||fe.ctrlKey)&&fe.key==="f"){fe.preventDefault(),xe==null||xe.focus(),xe==null||xe.select();return}fe.key==="Escape"&&(xe&&document.activeElement===xe?(ht(),xe.blur(),b.focus()):n&&n())};he&&he.addEventListener("click",Xe),Z&&Z.addEventListener("change",Je),xe&&xe.addEventListener("input",pt),Ve&&Ve.addEventListener("click",ht),J.addEventListener("scroll",zt),J.addEventListener("wheel",or,{passive:!0}),J.addEventListener("click",kt),Ke.addEventListener("click",X),b.addEventListener("keydown",ct);function Jt(){B&&clearTimeout(B),je!==null&&(cancelAnimationFrame(je),je=null),Ue=!1,Oe.clear(),he&&he.removeEventListener("click",Xe),Z&&Z.removeEventListener("change",Je),xe&&xe.removeEventListener("input",pt),Ve&&Ve.removeEventListener("click",ht),J.removeEventListener("scroll",zt),J.removeEventListener("wheel",or),J.removeEventListener("click",kt),Ke.removeEventListener("click",X),b.removeEventListener("keydown",ct)}return{element:b,update:qe,destroy:Jt}}}function Gx(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${r}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var Kx=(e,t)=>{var n,o,s;let r=(s=(o=(n=t==null?void 0:t.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(r){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Gx(e,t)});if(p)return p}return Gx(e,t)};var mu=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,n])=>{this.register(r,n)})}},yo=new mu;yo.register("PersonaArtifactCard",Kx);function mv(e){var o;let t=x("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=x("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let n=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(r),t.appendChild(n),t}function Jx(e,t){var Z,he,xe,Ve;let r=(he=(Z=e.features)==null?void 0:Z.artifacts)==null?void 0:he.layout,o=((xe=r==null?void 0:r.toolbarPreset)!=null?xe:"default")==="document",s=(Ve=r==null?void 0:r.panePadding)==null?void 0:Ve.trim(),a=e.markdown?ns(e.markdown):null,i=Ps(e.sanitize),d=G=>{let ee=a?a(G):os(G);return i?i(ee):ee},l=typeof document!="undefined"?x("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};l&&l.addEventListener("click",()=>{var G;p(),(G=t.onDismiss)==null||G.call(t)});let u=x("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=x("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let m=x("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let y=x("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var G;p(),(G=t.onDismiss)==null||G.call(t)});let v="rendered",E=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?ir({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):ir({icon:"eye",label:"Rendered view"}),A=o?ir({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):ir({icon:"code-2",label:"Source"}),M=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),b=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,h=r==null?void 0:r.documentToolbarCopyMenuItems,k=!!(w&&h&&h.length>0),B=null,H,W=null,N=null;if(o&&(b||w)&&!k){if(H=b?Ja({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ir({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let G=Pe("chevron-down",14,"currentColor",2);G&&H.appendChild(G)}}else o&&k?(B=x("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=b?Ja({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ir({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=ir({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),B.append(H,W)):o?H=ir({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=ir({icon:"copy",label:"Copy"});let q=o?ir({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):ir({icon:"refresh-cw",label:"Refresh"}),se=o?ir({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):ir({icon:"x",label:"Close"}),ve=()=>{var pe,le,Ye;let G=(pe=Oe.find(Me=>Me.id===K))!=null?pe:Oe[Oe.length-1],ee=(le=G==null?void 0:G.id)!=null?le:null,Ie=(G==null?void 0:G.artifactType)==="markdown"&&(Ye=G.markdown)!=null?Ye:"",ye=G?JSON.stringify({component:G.component,props:G.props},null,2):"";return{markdown:Ie,jsonPayload:ye,id:ee}},Ue=async()=>{var pe;let{markdown:G,jsonPayload:ee}=ve(),Ie=(pe=Oe.find(le=>le.id===K))!=null?pe:Oe[Oe.length-1],ye=(Ie==null?void 0:Ie.artifactType)==="markdown"?G:Ie?ee:"";try{await navigator.clipboard.writeText(ye)}catch{}};if(H.addEventListener("click",async()=>{let G=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(G&&k){let{markdown:ee,jsonPayload:Ie,id:ye}=ve();try{await G({actionId:"primary",artifactId:ye,markdown:ee,jsonPayload:Ie})}catch{}return}await Ue()}),W&&(h!=null&&h.length)){let G=()=>{var Ie;return(Ie=u.closest("[data-persona-root]"))!=null?Ie:document.body},ee=()=>{N=Bo({items:h.map(Ie=>({id:Ie.id,label:Ie.label})),onSelect:async Ie=>{let{markdown:ye,jsonPayload:pe,id:le}=ve(),Ye=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:Ie,artifactId:le,markdown:ye,jsonPayload:pe}):Ie==="markdown"||Ie==="md"?await navigator.clipboard.writeText(ye):Ie==="json"||Ie==="source"?await navigator.clipboard.writeText(pe):await navigator.clipboard.writeText(ye||pe)}catch{}},anchor:B!=null?B:W,position:"bottom-right",portal:G()})};u.isConnected?ee():requestAnimationFrame(ee),W.addEventListener("click",Ie=>{Ie.stopPropagation(),N==null||N.toggle()})}q.addEventListener("click",async()=>{var G;try{await((G=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:G.call(r))}catch{}j()}),se.addEventListener("click",()=>{var G;p(),(G=t.onDismiss)==null||G.call(t)});let je=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),A.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",je(),j()}),A.addEventListener("click",()=>{v="source",je(),j()});let we=x("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),E.append(T,A),B?M.append(B,q,se):M.append(H,q,se),f.append(E,we,M),je()):(f.appendChild(m),f.appendChild(y)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Te=x("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),We=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Te.style.paddingLeft=s,Te.style.paddingRight=s,We.style.padding=s),u.appendChild(f),u.appendChild(Te),u.appendChild(We);let Oe=[],K=null,He=!1,j=()=>{var ye,pe,le,Ye;let G=o&&Oe.length<=1;Te.classList.toggle("persona-hidden",G),Te.replaceChildren();for(let Me of Oe){let be=x("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");be.type="button",be.textContent=Me.title||Me.id.slice(0,8),Me.id===K&&be.classList.add("persona-bg-persona-container","persona-border-persona-border"),be.addEventListener("click",()=>t.onSelect(Me.id)),Te.appendChild(be)}We.replaceChildren();let ee=K&&Oe.find(Me=>Me.id===K)||Oe[Oe.length-1];if(!ee)return;if(o){let Me=ee.artifactType==="markdown"?"MD":(ye=ee.component)!=null?ye:"Component",J=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";we.textContent=`${J} \xB7 ${Me}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&v==="source"){let be=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");be.textContent=(pe=ee.markdown)!=null?pe:"",We.appendChild(be);return}let Me=x("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Me.innerHTML=d((le=ee.markdown)!=null?le:""),We.appendChild(Me);return}let Ie=ee.component?yo.get(ee.component):void 0;if(Ie){let be={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=Ie((Ye=ee.props)!=null?Ye:{},be);if(J){We.appendChild(J);return}}catch{}}We.appendChild(mv(ee))},Ce=()=>{var ee;let G=Oe.length>0;if(u.classList.toggle("persona-hidden",!G),l){let Ie=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,pe=((ee=Ie==null?void 0:Ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;G&&pe&&He?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(G){var ee,Ie,ye;Oe=G.artifacts,K=(ye=(Ie=G.selectedId)!=null?Ie:(ee=G.artifacts[G.artifacts.length-1])==null?void 0:ee.id)!=null?ye:null,Oe.length>0&&(He=!0),j(),Ce()},setMobileOpen(G){He=G,!G&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):Ce()}}}function Ln(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function Xx(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Ln(t))return;let r=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,n=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),o=(d=r==null?void 0:r.paneBorderLeft)==null?void 0:d.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function gv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Vl(e,t){var d,l,p,u,f,m,y,v,E,T;if(!Ln(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),gv(e),Xx(e,t);return}let r=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=r==null?void 0:r.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=r==null?void 0:r.paneMaxWidth)!=null?f:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let o=(y=r==null?void 0:r.panePadding)==null?void 0:y.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=r==null?void 0:r.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Xx(e,t)}var Yx=["panel","seamless"];function Gl(e,t){var i,d,l,p,u,f;for(let m of Yx)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Ln(t))return;let r=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",o=Yx.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=r==null?void 0:r.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=r.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Qx(e,t){var r,n,o;return!t||!Ln(e)?!1:((o=(n=(r=e.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function hv(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function xv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function yv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function bv(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}function Zx(e,t){var a;let n=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(n);return s?Number(s[1]):8}function ey(e,t,r,n,o,s){let a=hv(o,200),i=bv(t,r,n,200);i=Math.max(a,i);let d=xv(s);return d!==null&&(i=Math.min(i,d)),yv(e,a,i)}var ty={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},gu=(e,t,r,n)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,v,E;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(v=ty[a])!=null?v:ty.init;s.classList.add("persona-form-card","persona-space-y-4");let d=x("div","persona-space-y-1"),l=x("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=x("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var h,k;let A=x("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${a}-${T.name}`;let M=x("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=T.label,A.appendChild(M);let b=(h=T.type)!=null?h:"text",w;b==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=b),w.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",w.id=`${t.id}-${a}-${T.name}`,w.name=T.name,w.placeholder=(k=T.placeholder)!=null?k:"",T.required&&(w.required=!0),A.appendChild(w),p.appendChild(A)});let u=x("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=x("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=x("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var w,h;T.preventDefault();let A=(w=r.formEndpoint)!=null?w:"/form",M=new FormData(p),b={};M.forEach((k,B)=>{b[B]=k}),b.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let B=await k.json();f.textContent=(h=B.message)!=null?h:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await n.sendMessage(String(B.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var hu=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var n;let r=this.plugins.get(t);r&&((n=r.onUnregister)==null||n.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var n,o;return((n=r.priority)!=null?n:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let n=new Set(t.map(s=>s.id));return[...r.filter(s=>!n.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},ti=new hu;var ry=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:r,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var wv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Cv=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let n=0;for(let o=r;o<t.length;o+=1){let s=t[o];if(s==="{"&&(n+=1),s==="}"&&(n-=1,n===0))return t.slice(r,o+1)}return null},ri=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wv(e),r=Cv(t);if(!r)return null;let n=JSON.parse(r);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...s}=n;return{type:String(o),payload:s,raw:n}}catch{return null}},xu=e=>typeof e=="string"?e:e==null?"":String(e),hs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:xu(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,n=xu(r.element);if(n&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(n);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:xu(r.text)}}},ny=e=>Array.isArray(e)?e.map(t=>String(t)):[],ni=e=>{let t=new Set(ny(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ny(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),n();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var vv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Sv=e=>e.map(t=>({...t,streaming:!1})),Av=e=>e.map(t=>({...t,status:"complete"})),Kl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?vv(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let o={...r,messages:r.messages?Sv(r.messages):void 0,artifacts:r.artifacts?Av(r.artifacts):void 0};n.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Js=ud(ji(),1);function Tv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Mv(e,t){if(!Tv(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function Jl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return e;try{let o=(0,Js.parse)(r,Js.STR|Js.OBJ),s=Mv(o,r);s&&(e=s)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function oy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Xl(e,t){let{config:r,message:n,onPropsUpdate:o}=t,s=yo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:r,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function sy(){let e=Jl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ay(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Yl(e){let t=ay(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Ql(e){let t=ay(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let n=r;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var kv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Zl(e){let{onSubmit:t,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=kv}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=n,m.appendChild(y);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,m.appendChild(v),f.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let h=1;h<=5;h++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${h} star${h>1?"s":""}: ${l[h-1]}`),k.title=l[h-1],k.dataset.rating=String(h),k.innerHTML=`
73
+ `,r.addEventListener("click",e);let n=s=>{var k,x,b,h,M,W,R,B,_,V,oe,be,Qe,je;let a=(k=s.launcher)!=null?k:{},i=Ar(s),d=r.querySelector("[data-role='launcher-title']");if(d){let ve=(x=a.title)!=null?x:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let ve=(b=a.subtitle)!=null?b:"Get answers fast";l.textContent=ve,l.setAttribute("title",ve)}let p=r.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=r.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ve=(h=a.agentIconSize)!=null?h:"40px";if(m.style.height=ve,m.style.width=ve,m.innerHTML="",a.agentIconName){let Ee=parseFloat(ve)||24,Ge=Ie(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);Ge?(m.appendChild(Ge),m.style.display=""):(m.textContent=(M=a.agentIconText)!=null?M:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let ve=(R=a.agentIconSize)!=null?R:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ve=(B=a.callToActionIconSize)!=null?B:"32px";f.style.height=ve,f.style.width=ve,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ge=parseFloat(ve)||24,_e=Math.max(Ge-Ee,8),X=Ie(a.callToActionIconName,_e,"currentColor",2);X?f.appendChild(X):f.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else f.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let y=a.position&&$n[a.position]?$n[a.position]:$n["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?E:`${A} ${y}`,i||(r.style.zIndex=String((oe=a.zIndex)!=null?oe:zr));let T="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(be=a.border)!=null?be:T,r.style.boxShadow=(Qe=a.shadow)!=null?Qe:S,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(je=a.collapsedMaxWidth)!=null?je:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},o=()=>{r.removeEventListener("click",e),r.remove()};return t&&n(t),{element:r,update:n,destroy:o}};var Ww="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ll=(t,e={})=>{var A,E,T,S,k,x;let{showClose:r=!0,wrapperClassName:n=Ww,buttonSize:o,iconSize:s="28px"}=e,a=(A=t==null?void 0:t.launcher)!=null?A:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=v("div",n),l=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(T=a.closeButtonTooltipText)!=null?T:"Close chat",m=(S=a.closeButtonShowTooltip)!=null?S:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let u=(k=a.closeButtonIconName)!=null?k:"x",f=(x=a.closeButtonIconText)!=null?x:"\xD7";l.style.color=a.closeButtonColor||en.actionIconColor;let y=Ie(u,s,"currentColor",1);if(y?(y.style.display="block",l.appendChild(y)):l.textContent=f,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let b=a.closeButtonBorderWidth||"0px",h=a.closeButtonBorderColor||"transparent";l.style.border=`${b} solid ${h}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let b=null,h=()=>{if(b)return;let W=l.ownerDocument,R=W.body;if(!R)return;b=Qn(W,"div","persona-clear-chat-tooltip"),b.textContent=p;let B=Qn(W,"div");B.className="persona-clear-chat-tooltip-arrow",b.appendChild(B);let _=l.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Ro),b.style.left=`${_.left+_.width/2}px`,b.style.top=`${_.top-8}px`,b.style.transform="translate(-50%, -100%)",R.appendChild(b)},M=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};d.addEventListener("mouseenter",h),d.addEventListener("mouseleave",M),l.addEventListener("focus",h),l.addEventListener("blur",M),d._cleanupTooltip=()=>{M(),d.removeEventListener("mouseenter",h),d.removeEventListener("mouseleave",M),l.removeEventListener("focus",h),l.removeEventListener("blur",M)}}return{button:l,wrapper:d}},Bw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pl=(t,e={})=>{var b,h,M,W,R,B,_,V,oe,be,Qe,je,ve;let{wrapperClassName:r=Bw,buttonSize:n,iconSize:o="20px"}=e,a=(h=((b=t==null?void 0:t.launcher)!=null?b:{}).clearChat)!=null?h:{},i=(M=n!=null?n:a.size)!=null?M:"32px",d=(W=a.iconName)!=null?W:"refresh-cw",l=(R=a.iconColor)!=null?R:"",p=(B=a.backgroundColor)!=null?B:"",m=(_=a.borderWidth)!=null?_:"",u=(V=a.borderColor)!=null?V:"",f=(oe=a.borderRadius)!=null?oe:"",y=(be=a.paddingX)!=null?be:"",A=(Qe=a.paddingY)!=null?Qe:"",E=(je=a.tooltipText)!=null?je:"Clear chat",T=(ve=a.showTooltip)!=null?ve:!0,S=v("div",r),k=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",E),k.style.color=l||en.actionIconColor;let x=Ie(d,o,"currentColor",1);if(x&&(x.style.display="block",k.appendChild(x)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),m||u){let Ee=m||"0px",Ge=u||"transparent";k.style.border=`${Ee} solid ${Ge}`,k.classList.remove("persona-border-none")}if(f&&(k.style.borderRadius=f,k.classList.remove("persona-rounded-full")),y&&(k.style.paddingLeft=y,k.style.paddingRight=y),A&&(k.style.paddingTop=A,k.style.paddingBottom=A),S.appendChild(k),T&&E){let Ee=null,Ge=()=>{if(Ee)return;let X=k.ownerDocument,Ue=X.body;if(!Ue)return;Ee=Qn(X,"div","persona-clear-chat-tooltip"),Ee.textContent=E;let K=Qn(X,"div");K.className="persona-clear-chat-tooltip-arrow",Ee.appendChild(K);let Te=k.getBoundingClientRect();Ee.style.position="fixed",Ee.style.zIndex=String(Ro),Ee.style.left=`${Te.left+Te.width/2}px`,Ee.style.top=`${Te.top-8}px`,Ee.style.transform="translate(-50%, -100%)",Ue.appendChild(Ee)},_e=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};S.addEventListener("mouseenter",Ge),S.addEventListener("mouseleave",_e),k.addEventListener("focus",Ge),k.addEventListener("blur",_e),S._cleanupTooltip=()=>{_e(),S.removeEventListener("mouseenter",Ge),S.removeEventListener("mouseleave",_e),k.removeEventListener("focus",Ge),k.removeEventListener("blur",_e)}}return{button:k,wrapper:S}};var en={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},go=t=>{var b,h,M,W,R,B,_,V,oe,be,Qe,je,ve,Ee,Ge,_e;let{config:e,showClose:r=!0}=t,n=v("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(b=e==null?void 0:e.launcher)!=null?b:{},s=(h=o.headerIconSize)!=null?h:"48px",a=(M=o.closeButtonPlacement)!=null?M:"inline",i=(W=o.headerIconHidden)!=null?W:!1,d=o.headerIconName,l=v("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let X=parseFloat(s)||24,Ue=Ie(d,X*.6,"currentColor",1);Ue?l.replaceChildren(Ue):l.textContent=(B=(R=e==null?void 0:e.launcher)==null?void 0:R.agentIconText)!=null?B:"\u{1F4AC}"}else if((_=e==null?void 0:e.launcher)!=null&&_.iconUrl){let X=v("img");X.src=e.launcher.iconUrl,X.alt="",X.className="persona-rounded-xl persona-object-cover",X.style.height=s,X.style.width=s,l.replaceChildren(X)}else l.textContent=(oe=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=v("span","persona-text-base persona-font-semibold");m.style.color=en.titleColor,m.textContent=(Qe=(be=e==null?void 0:e.launcher)==null?void 0:be.title)!=null?Qe:"Chat Assistant";let u=v("span","persona-text-xs");u.style.color=en.subtitleColor,u.textContent=(ve=(je=e==null?void 0:e.launcher)==null?void 0:je.subtitle)!=null?ve:"Here to help you get answers fast",p.append(m,u),i?n.append(p):n.append(l,p);let f=(Ee=o.clearChat)!=null?Ee:{},y=(Ge=f.enabled)!=null?Ge:!0,A=(_e=f.placement)!=null?_e:"inline",E=null,T=null;if(y){let Ue=Pl(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=Ue.button,T=Ue.wrapper,A==="top-right"&&(T.style.right="48px"),A==="inline"&&n.appendChild(T)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:x}=Ll(e,{showClose:r,wrapperClassName:S});return a!=="top-right"&&n.appendChild(x),{header:n,iconHolder:l,headerTitle:m,headerSubtitle:u,closeButton:k,closeButtonWrapper:x,clearChatButton:E,clearChatButtonWrapper:T}},pa=(t,e,r)=>{var a,i,d,l;let n=(a=r==null?void 0:r.launcher)!=null?a:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",s=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function Ho(t){let{items:e,onSelect:r,anchor:n,position:o="bottom-left",portal:s}=t,a=v("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ro)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",f.id),f.destructive&&y.setAttribute("data-destructive",""),f.icon){let E=Ie(f.icon,16,"currentColor",1.5);E&&y.appendChild(E)}let A=document.createElement("span");A.textContent=f.label,y.appendChild(A),y.addEventListener("click",E=>{E.stopPropagation(),p(),r(f.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let f=n.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=y=>{!a.contains(y.target)&&!n.contains(y.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function u(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:u}}function Er(t){let{icon:e,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",r),d.title=r;let l=Ie(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function js(t){let{icon:e,label:r,variant:n="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=v("button",l);if(p.type="button",p.setAttribute("aria-label",r),e){let u=Ie(e,s!=null?s:14,"currentColor",2);u&&p.appendChild(u)}let m=v("span");if(m.textContent=r,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[u,f]of Object.entries(d))p.setAttribute(u,f);return p}function dx(t){let{items:e,selectedId:r,onSelect:n,className:o}=t,s=v("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=r,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of e){let m;p.icon?m=Er({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(m=v("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),s.appendChild(m)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Il(t){var f,y;let{label:e,icon:r="chevron-down",menuItems:n,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,l=v("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",e);let p=v("span","persona-combo-btn-label");p.textContent=e,l.appendChild(p);let m=Ie(r,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var A,E;l.style.backgroundColor=(A=d.background)!=null?A:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Ho({items:n,onSelect:A=>{l.setAttribute("aria-expanded","false"),o(A)},anchor:l,position:s,portal:a});return a||l.appendChild(u.element),l.addEventListener("click",A=>{A.stopPropagation();let E=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),u.toggle()}),l.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),l.click())}),{element:l,setLabel:A=>{p.textContent=A,l.setAttribute("aria-label",A)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let A=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",A?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var $p=t=>{var n;let e=go({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),r=(n=t.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(r){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>r()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())}))}return e};function Hw(t,e,r){var n,o,s;if(e!=null&&e.length)for(let a of e){let i=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=a.ariaLabel)!=null?n:a.label)!=null?o:a.id),a.icon){let d=Ie(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(i);let l=Ho({items:a.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>r==null?void 0:r(a.id)),t.appendChild(i)}}var Up=t=>{var S,k,x,b,h,M,W,R,B;let{config:e,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Il({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=en.titleColor,p=(x=l.querySelector(".persona-combo-btn-label"))!=null?x:l;else{if(l=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=en.titleColor,p.textContent=(b=a.title)!=null?b:"Chat Assistant",l.appendChild(p),Hw(l,o==null?void 0:o.trailingActions,(h=o==null?void 0:o.onAction)!=null?h:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let _=o==null?void 0:o.titleRowHover;_&&(l.style.borderRadius=(M=_.borderRadius)!=null?M:"10px",l.style.padding=(W=_.padding)!=null?W:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,oe;l.style.backgroundColor=(V=_.background)!=null?V:"",l.style.borderColor=(oe=_.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(R=a.closeButtonSize)!=null?R:"32px",u=v("div",""),f=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=a.closeButtonColor||en.actionIconColor;let y=(B=a.closeButtonIconName)!=null?B:"x",A=Ie(y,"28px","currentColor",1);A?f.appendChild(A):f.textContent="\xD7",n&&f.addEventListener("click",n),u.appendChild(f),i.appendChild(u);let E=v("div");E.style.display="none";let T=v("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Rl={default:$p,minimal:Up},zp=t=>{var e;return(e=Rl[t])!=null?e:Rl.default},Oa=(t,e,r)=>{var a,i,d;if(e!=null&&e.render){let l=e.render({config:t,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=v("div");p.style.display="none";let m=v("span"),u=v("span"),f=v("button");f.style.display="none";let y=v("div");return y.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:u,closeButton:f,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=e==null?void 0:e.layout)!=null?a:"default",s=zp(n)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Wl=t=>{var a,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,n=20;e.style.maxHeight=`${r*n}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:r*n},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Bl=t=>{var b,h,M,W,R,B,_,V,oe,be,Qe,je;let e=(b=t==null?void 0:t.sendButton)!=null?b:{},r=(h=e.useIcon)!=null?h:!1,n=(M=e.iconText)!=null?M:"\u2191",o=e.iconName,s=(W=e.stopIconName)!=null?W:"square",a=(R=e.tooltipText)!=null?R:"Send message",i=(B=e.stopTooltipText)!=null?B:"Stop generating",d=(V=(_=t==null?void 0:t.copy)==null?void 0:_.sendButtonLabel)!=null?V:"Send",l=(be=(oe=t==null?void 0:t.copy)==null?void 0:oe.stopButtonLabel)!=null?be:"Stop",p=(Qe=e.showTooltip)!=null?Qe:!1,m=(je=e.size)!=null?je:"40px",u=e.backgroundColor,f=e.textColor,y=v("div","persona-send-button-wrapper"),A=v("button",r?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");A.type="submit",A.setAttribute("data-persona-composer-submit","");let E=null,T=null;if(r){A.style.width=m,A.style.height=m,A.style.minWidth=m,A.style.minHeight=m,A.style.fontSize="18px",A.style.lineHeight="1",A.innerHTML="",f?A.style.color=f:A.style.color="var(--persona-button-primary-fg, #ffffff)";let ve=parseFloat(m)||24,Ee=(f==null?void 0:f.trim())||"currentColor";o?(E=Ie(o,ve,Ee,2),E?A.appendChild(E):A.textContent=n):A.textContent=n,T=Ie(s,ve,Ee,2),u?A.style.backgroundColor=u:A.classList.add("persona-bg-persona-primary")}else A.textContent=d,f?A.style.color=f:A.classList.add("persona-text-white");e.borderWidth&&(A.style.borderWidth=e.borderWidth,A.style.borderStyle="solid"),e.borderColor&&(A.style.borderColor=e.borderColor),e.paddingX?(A.style.paddingLeft=e.paddingX,A.style.paddingRight=e.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),e.paddingY?(A.style.paddingTop=e.paddingY,A.style.paddingBottom=e.paddingY):(A.style.paddingTop="",A.style.paddingBottom="");let S=null;p&&a&&(S=v("div","persona-send-button-tooltip"),S.textContent=a,y.appendChild(S)),A.setAttribute("aria-label",a),y.appendChild(A);let k="send";return{button:A,wrapper:y,setMode:ve=>{if(ve===k)return;k=ve;let Ee=ve==="stop"?i:a;if(A.setAttribute("aria-label",Ee),S&&(S.textContent=Ee),r){if(E&&T){let Ge=ve==="stop"?T:E;A.replaceChildren(Ge)}}else A.textContent=ve==="stop"?l:d}}},Hl=t=>{var S,k,x,b,h,M,W,R,B,_,V,oe;let e=(S=t==null?void 0:t.voiceRecognition)!=null?S:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(n||o))return null;let a=(b=(x=t==null?void 0:t.sendButton)==null?void 0:x.size)!=null?b:"40px",i=v("div","persona-send-button-wrapper"),d=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(h=e.iconName)!=null?h:"mic",p=(M=e.iconSize)!=null?M:a,m=parseFloat(p)||24,u=(R=e.backgroundColor)!=null?R:(W=t==null?void 0:t.sendButton)==null?void 0:W.backgroundColor,f=(_=e.iconColor)!=null?_:(B=t==null?void 0:t.sendButton)==null?void 0:B.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",f?d.style.color=f:d.style.color="var(--persona-text, #111827)";let A=Ie(l,m,f||"currentColor",1.5);A?d.appendChild(A):d.textContent="\u{1F3A4}",u&&(d.style.backgroundColor=u),e.borderWidth&&(d.style.borderWidth=e.borderWidth,d.style.borderStyle="solid"),e.borderColor&&(d.style.borderColor=e.borderColor),e.paddingX&&(d.style.paddingLeft=e.paddingX,d.style.paddingRight=e.paddingX),e.paddingY&&(d.style.paddingTop=e.paddingY,d.style.paddingBottom=e.paddingY),i.appendChild(d);let E=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((oe=e.showTooltip)!=null?oe:!1)&&E){let be=v("div","persona-send-button-tooltip");be.textContent=E,i.appendChild(be)}return{button:d,wrapper:i}},Dl=t=>{var y,A,E,T,S,k,x,b;let e=(y=t==null?void 0:t.attachments)!=null?y:{};if(e.enabled!==!0)return null;let r=(E=(A=t==null?void 0:t.sendButton)==null?void 0:A.size)!=null?E:"40px",n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=v("input");o.type="file",o.accept=((T=e.allowedTypes)!=null?T:mo).join(","),o.multiple=((S=e.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=v("div","persona-send-button-wrapper"),a=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(k=e.buttonTooltipText)!=null?k:"Attach file");let i=(x=e.buttonIconName)!=null?x:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Ie(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",h=>{h.preventDefault(),o.click()}),s.appendChild(a);let u=(b=e.buttonTooltipText)!=null?b:"Attach file",f=v("div","persona-send-button-tooltip");return f.textContent=u,s.appendChild(f),{button:a,wrapper:s,input:o,previewsContainer:n}},Ol=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},r=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",n=v("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;n.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=v("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=s;return n},_l=()=>v("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var _a=t=>{var y,A,E,T,S,k;let{config:e}=t,r=v("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");r.setAttribute("data-persona-theme-zone","composer");let n=_l(),o=v("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Wl(e);a();let i=Bl(e),d=Hl(e),l=Dl(e),p=Ol(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let m=v("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),u=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(u,f),o.append(m),o.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==(d==null?void 0:d.button)&&x.target!==(d==null?void 0:d.wrapper)&&x.target!==(l==null?void 0:l.button)&&x.target!==(l==null?void 0:l.wrapper)&&s.focus()}),r.append(n,o,p),{footer:r,suggestions:n,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(A=d==null?void 0:d.wrapper)!=null?A:null,statusText:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(S=l==null?void 0:l.input)!=null?S:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var cx=()=>{let t=v("button","persona-pill-peek");t.type="button",t.setAttribute("data-persona-pill-peek",""),t.setAttribute("aria-label","Show conversation"),t.setAttribute("tabindex","-1");let e=v("span","persona-pill-peek__icon"),r=Ie("message-square",16,"currentColor",1.5);r&&e.appendChild(r);let n=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=Ie("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,n,o),{root:t,textNode:n}},px=t=>{var y,A,E,T,S,k;let{config:e}=t,r=v("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=_l();n.style.display="none";let o=Ol(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Wl(e);s.style.maxHeight="100px",a();let i=Bl(e),d=Hl(e),l=Dl(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=v("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=v("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let u=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),p.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==(d==null?void 0:d.button)&&x.target!==(d==null?void 0:d.wrapper)&&x.target!==(l==null?void 0:l.button)&&x.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,u),l&&r.append(l.previewsContainer),r.append(p,n,o);let f=p;return{footer:r,suggestions:n,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(A=d==null?void 0:d.wrapper)!=null?A:null,statusText:o,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(S=l==null?void 0:l.input)!=null?S:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:m,rightActions:u,setSendButtonMode:i.setMode}};var ux=t=>{var p,m,u,f,y,A,E,T,S,k,x,b,h,M,W,R,B;let e=(m=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)!=null?m:!0,r=Ar(t);if(Bo(t)){let _=(f=(u=t==null?void 0:t.launcher)==null?void 0:u.composerBar)!=null?f:{},V=v("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(y=_.expandedSize)!=null?y:"anchored",V.style.zIndex=String((E=(A=t==null?void 0:t.launcher)==null?void 0:A.zIndex)!=null?E:zr);let oe=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let be=v("div","persona-widget-pill-root");return be.setAttribute("data-persona-composer-bar",""),be.dataset.state="collapsed",be.dataset.expandedSize=(T=_.expandedSize)!=null?T:"anchored",be.style.zIndex=String((k=(S=t==null?void 0:t.launcher)==null?void 0:S.zIndex)!=null?k:zr),{wrapper:V,panel:oe,pillRoot:be}}if(r){let _=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(V),{wrapper:_,panel:V}}if(!e){let _=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(b=(x=t==null?void 0:t.launcher)==null?void 0:x.width)!=null?b:"100%";return _.style.width=oe,V.style.width="100%",_.appendChild(V),{wrapper:_,panel:V}}let o=(h=t==null?void 0:t.launcher)!=null?h:{},s=o.position&&$n[o.position]?$n[o.position]:$n["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((W=(M=t==null?void 0:t.launcher)==null?void 0:M.zIndex)!=null?W:zr);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(B=(R=t==null?void 0:t.launcher)==null?void 0:R.width)!=null?B:t==null?void 0:t.launcherWidth,l=d!=null?d:yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Dw=(t,e)=>{var x,b,h,M,W,R,B,_,V;let r=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Ll(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(h=(b=(x=t==null?void 0:t.launcher)==null?void 0:x.clearChat)==null?void 0:b.enabled)!=null?h:!0,a=null,i=null;if(s){let oe=Pl(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=v("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(W=(M=t==null?void 0:t.copy)==null?void 0:M.welcomeTitle)!=null?W:"Hello \u{1F44B}";let u=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(B=(R=t==null?void 0:t.copy)==null?void 0:R.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",p.append(m,u);let f=v("div","persona-flex persona-flex-col persona-gap-3"),y=(_=t==null?void 0:t.layout)==null?void 0:_.contentMaxWidth;y&&(f.style.maxWidth=y,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((V=t==null?void 0:t.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,f);let E=v("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let T=px({config:t}),{root:S,textNode:k}=cx();return r.append(d,o,l,E),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:f,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:m,introSubtitle:u,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:S,peekTextNode:k}},fx=(t,e=!0)=>{var E,T,S,k,x,b,h,M,W;if(Bo(t))return Dw(t,e);let r=v("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");r.setAttribute("data-persona-theme-zone","container");let n=(E=t==null?void 0:t.layout)==null?void 0:E.header,o=((T=t==null?void 0:t.layout)==null?void 0:T.showHeader)!==!1,s=n?Oa(t,n,{showClose:e}):go({config:t,showClose:e}),a=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Ar(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(S=t==null?void 0:t.copy)==null?void 0:S.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(b=(x=t==null?void 0:t.copy)==null?void 0:x.welcomeSubtitle)!=null?b:"Ask anything about your account or products.",i.append(d,l);let p=v("div","persona-flex persona-flex-col persona-gap-3"),m=(h=t==null?void 0:t.layout)==null?void 0:h.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((M=t==null?void 0:t.copy)==null?void 0:M.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let f=_a({config:t}),y=((W=t==null?void 0:t.layout)==null?void 0:W.showFooter)!==!1;o?pa(r,s,t):(s.header.style.display="none",pa(r,s,t)),r.append(a);let A=v("div","persona-composer-overlay persona-pointer-events-none");return A.setAttribute("data-persona-composer-overlay",""),A.style.position="absolute",A.style.left="0",A.style.right="0",A.style.bottom="0",A.style.zIndex="20",y||(f.footer.style.display="none"),r.append(f.footer),r.append(A),{container:r,body:a,messagesWrapper:p,composerOverlay:A,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Ow=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},_w=(t,e)=>{if(!t)return null;let r=Ow(t);if(r===null)return null;let n=e==null?void 0:e[t],o=n!==void 0?n:r;return o||null},Nw=(t,e)=>{let r=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",t),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=e,r},Fw=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},qp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Vp=320,gx=320,$w=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Uw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),zw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),qw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Vw=(t,e,r)=>{if(t.length===0)return null;try{let n=v("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),e&&(n.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,n.remove(),r==null||r())};return t.forEach((i,d)=>{var m;let l=v("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Vp}px`,l.style.maxHeight=`${gx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),Fw(i.image)?(l.src=i.image,n.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):n}catch{return r==null||r(),null}},jw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let r=0;return t.forEach(n=>{if(!qp(n.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vp}px`,e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Gw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let r=0;return t.forEach(n=>{if(!qp(n.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vp}px`,o.style.maxHeight=`${gx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Kw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let r=0;return t.forEach(n=>{if(!qp(n.data))return;let o=v("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},ua=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(r),t.appendChild(n),t.appendChild(o),t},jp=(t,e,r)=>{let n={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:ua};if(e){let o=e(n);if(o!==null)return o}return ua()},Xw=(t,e)=>{let r=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=e==="user"?t.userAvatar:t.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=v("img");o.src=n,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(o)}else r.textContent=n,r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},mx=(t,e)=>{let r=v("div","persona-text-xs persona-text-persona-muted"),n=new Date(t.createdAt);return e.format?r.textContent=e.format(n):r.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Jw=(t,e="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},Gp=(t,e,r)=>{var f,y,A,E,T,S;let n=(f=e.showCopy)!=null?f:!0,o=(y=e.showUpvote)!=null?y:!0,s=(A=e.showDownvote)!=null?A:!0;if(!n&&!o&&!s){let k=v("div");return k.style.display="none",k.id=`actions-${t.id}`,k.setAttribute("data-actions-for",t.id),k}let a=(E=e.visibility)!=null?E:"hover",i=(T=e.align)!=null?T:"right",d=(S=e.layout)!=null?S:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id);let u=(k,x,b)=>{let h=Er({icon:k,label:x,size:14,className:"persona-message-action-btn"});return h.setAttribute("data-action",b),h};return n&&m.appendChild(u("copy","Copy message","copy")),o&&m.appendChild(u("thumbs-up","Upvote","upvote")),s&&m.appendChild(u("thumbs-down","Downvote","downvote")),m},Na=(t,e,r,n,o,s)=>{var X,Ue,K,Te,ae,xe,Me,Ke,ce,re,le,ut,Ce,he,tt,Ne,me;let a=r!=null?r:{},i=(X=a.layout)!=null?X:"bubble",d=a.avatar,l=a.timestamp,p=(Ue=d==null?void 0:d.show)!=null?Ue:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,u=(Te=d==null?void 0:d.position)!=null?Te:"left",f=(ae=l==null?void 0:l.position)!=null?ae:"below",y=Jw(t.role,i),A=v("div",y.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=$w(t),T=(Me=(xe=t.content)==null?void 0:xe.trim())!=null?Me:"",k=E.length>0&&T===Zi,x=Tl((ce=(Ke=s==null?void 0:s.widgetConfig)==null?void 0:Ke.features)==null?void 0:ce.streamAnimation),b=(ut=(le=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:le.streamAnimation)==null?void 0:ut.plugins,h=t.role==="assistant"&&x.type!=="none"?$s(x.type,b):null,M=t.role==="assistant"&&((Ce=h==null?void 0:h.isAnimating)==null?void 0:Ce.call(h,t))===!0,W=t.role==="assistant"&&h!==null&&(!!t.streaming||M);W&&(h!=null&&h.bubbleClass)&&A.classList.add(h.bubbleClass);let R=document.createElement("div");R.classList.add("persona-message-content"),W&&h&&(h.containerClass&&R.classList.add(h.containerClass),R.style.setProperty("--persona-stream-step",`${x.speed}ms`),R.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let B=W?Ml((he=t.content)!=null?he:"",x.buffer,h,t,!!t.streaming):(tt=t.content)!=null?tt:"",_=e({text:B,message:t,streaming:!!t.streaming,raw:t.rawContent}),V=_;W&&(h==null?void 0:h.wrap)==="char"?V=Us(_,"char",t.id,{skipTags:h.skipTags}):W&&(h==null?void 0:h.wrap)==="word"&&(V=Us(_,"word",t.id,{skipTags:h.skipTags}));let oe=null;if(k?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",R.appendChild(oe)):R.innerHTML=V,W&&(h!=null&&h.useCaret)&&!k&&T){let J=kl(),qe=R.querySelectorAll(".persona-stream-char, .persona-stream-word"),Z=qe[qe.length-1];if(Z!=null&&Z.parentNode)Z.parentNode.insertBefore(J,Z.nextSibling);else{let ge=R.lastElementChild;ge?ge.appendChild(J):R.appendChild(J)}}if(m&&f==="inline"&&t.createdAt){let J=mx(t,l);J.classList.add("persona-ml-2","persona-inline"),R.appendChild(J)}if(E.length>0){let J=Vw(E,!k&&!!T,()=>{k&&oe&&(oe.style.display="")});J?A.appendChild(J):k&&oe&&(oe.style.display="")}let be=Uw(t);if(be.length>0){let J=jw(be);J&&A.appendChild(J)}let Qe=zw(t);if(Qe.length>0){let J=Gw(Qe);J&&A.appendChild(J)}let je=qw(t);if(je.length>0){let J=Kw(je);J&&A.appendChild(J)}if(A.appendChild(R),m&&f==="below"&&t.createdAt){let J=mx(t,l);J.classList.add("persona-mt-1"),A.appendChild(J)}let ve=t.role==="assistant"?_w(t.stopReason,(me=(Ne=s==null?void 0:s.widgetConfig)==null?void 0:Ne.copy)==null?void 0:me.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let J=!!(B&&B.trim()),qe=x.placeholder==="skeleton",Z=qe&&x.buffer==="line"&&J;if(J)Z&&A.appendChild(zs());else if(qe)A.appendChild(zs());else{let ge=jp("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ge&&A.appendChild(ge)}}if(ve&&t.stopReason&&!t.streaming&&(T||(R.style.display="none"),A.appendChild(Nw(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let J=Gp(t,n,o);A.appendChild(J)}if(!p||t.role==="system")return A;let Ge=v("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),_e=Xw(d,t.role);return u==="right"||u==="left"&&t.role==="user"?Ge.append(A,_e):Ge.append(_e,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ge},hx=(t,e,r,n,o,s)=>{let a=r!=null?r:{};return t.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:t,config:{},streaming:!!t.streaming}):t.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:t,config:{},streaming:!!t.streaming}):Na(t,e,r,n,o,s)};var Fa=new Set,Qw=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Yw=(t,e)=>{var n,o;let r=(o=(n=t.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
74
+ `):""},xx=(t,e)=>{let r=Fa.has(t),n=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",r?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ie(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none",s&&(s.style.display=r?"none":s.textContent||s.childNodes.length?"":"none")},Kp=(t,e)=>{var Qe,je,ve,Ee,Ge,_e,X,Ue,K,Te,ae;let r=t.reasoning,n=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${t.id}`,n.setAttribute("data-message-id",t.id),!r)return n;let o=(je=(Qe=e==null?void 0:e.features)==null?void 0:Qe.reasoningDisplay)!=null?je:{},s=o.expandable!==!1,a=s&&Fa.has(t.id),i=r.status!=="complete",d=Yw(t,(ve=o.previewMaxLines)!=null?ve:3),l=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",f=(Ee=e==null?void 0:e.reasoning)!=null?Ee:{},y=String((Ge=r.startedAt)!=null?Ge:Date.now()),A=()=>{let xe=v("span","");return xe.setAttribute("data-tool-elapsed",y),xe.textContent=Vi(r),xe},E=(_e=f.renderCollapsedSummary)==null?void 0:_e.call(f,{message:t,reasoning:r,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Vi(r),createElapsedElement:A});typeof E=="string"&&E.trim()?(m.textContent=E,p.appendChild(m)):E instanceof HTMLElement?p.appendChild(E):(m.textContent=u,p.appendChild(m));let T=v("span","persona-text-xs persona-text-persona-primary");T.textContent=Ih(r),p.appendChild(T);let S=(X=o.loadingAnimation)!=null?X:"none",k=f.activeTextTemplate,x=f.completeTextTemplate,b=i?k:x,h=E instanceof HTMLElement,M=(xe,Me,Ke)=>{let ce=Ke;for(let re of Me){let le=v("span","persona-tool-char");le.style.setProperty("--char-index",String(ce)),le.textContent=re===" "?"\xA0":re,xe.appendChild(le),ce++}return ce},W=(xe,Me)=>{m.textContent="";let Ke=ji(xe,""),ce=0;for(let re of Ke){let le=re.styles.length>0?(()=>{let ut=v("span",re.styles.map(Ce=>`persona-tool-text-${Ce}`).join(" "));return m.appendChild(ut),ut})():m;if(re.isDuration&&i)le.appendChild(A());else{let ut=re.isDuration?Vi(r):re.text;Me?ce=M(le,ut,ce):le.appendChild(document.createTextNode(ut))}}};if(!h&&b)if(T.style.display="none",m.style.display="",i&&S!=="none"){let xe=(Ue=f.loadingAnimationDuration)!=null?Ue:2e3;m.setAttribute("data-preserve-animation","true"),S==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),W(b,!1)):(m.classList.add(`persona-tool-loading-${S}`),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),S==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),W(b,!0))}else W(b,!1);else if(!h&&i&&S!=="none"){m.style.display="";let xe=(K=f.loadingAnimationDuration)!=null?K:2e3;if(m.setAttribute("data-preserve-animation","true"),S==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`);else{m.classList.add(`persona-tool-loading-${S}`),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),S==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Me=m.textContent||u;m.textContent="",M(m,Me,0)}r.status==="complete"&&(m.style.display="none")}else h||(r.status==="complete"?m.style.display="none":m.style.display="");let R=null;if(s){R=v("div","persona-flex persona-items-center");let Me=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?R.appendChild(Me):R.textContent=a?"Hide":"Show";let Ke=v("div","persona-flex persona-items-center persona-ml-auto");Ke.append(R),l.append(p,Ke)}else l.append(p);let B=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","reasoning"),B.style.display="none",B.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let xe=(ae=(Te=e==null?void 0:e.reasoning)==null?void 0:Te.renderCollapsedPreview)==null?void 0:ae.call(Te,{message:t,reasoning:r,defaultPreview:d,isActive:i,config:e!=null?e:{}});Qw(B,xe)||(B.textContent=d),B.style.display=""}if(!a&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!s)return n.append(l,B),n;let _=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let V=r.chunks.join(""),oe=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=V||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),R){R.innerHTML="";let Me=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?R.appendChild(Me):R.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",B.style.display=a?"none":B.textContent||B.childNodes.length?"":"none"})(),n.append(l,B,_),n};var $a=new Set,Zw=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ev=(t,e)=>{var s;let r=t.toolCall;if(!r)return"";let n=((s=r.chunks)!=null?s:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
75
+ `);let o=Ia(r.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
76
+ `):""},tv=(t,e)=>{var p,m,u,f,y;let r=t.toolCall,n=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(m=n==null?void 0:n.collapsedMode)!=null?m:"tool-call",s=ev(t,(u=n==null?void 0:n.previewMaxLines)!=null?u:3),a=r?Rh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((y=r.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Rd(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Rd(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},yx=(t,e,r)=>{var p;let n=$a.has(t),o=(p=r==null?void 0:r.toolCall)!=null?p:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",n?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=o.toggleTextColor||o.headerTextColor||"currentColor",u=Ie(n?"chevron-up":"chevron-down",16,m,2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Xp=(t,e)=>{var V,oe,be,Qe,je,ve,Ee,Ge,_e;let r=t.toolCall,n=(V=e==null?void 0:e.toolCall)!=null?V:{},o=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!r)return o;let s=(be=(oe=e==null?void 0:e.features)==null?void 0:oe.toolCallDisplay)!=null?be:{},a=s.expandable!==!1,i=a&&$a.has(t.id),{summary:d,previewText:l,isActive:p}=tv(t,e),m=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let u=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let y=String((Qe=r.startedAt)!=null?Qe:Date.now()),A=()=>{let X=v("span","");return X.setAttribute("data-tool-elapsed",y),X.textContent=Is(r),X},E=(ve=n.renderCollapsedSummary)==null?void 0:ve.call(n,{message:t,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(je=s.collapsedMode)!=null?je:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Is(r),createElapsedElement:A});typeof E=="string"&&E.trim()?(f.textContent=E,u.appendChild(f)):E instanceof HTMLElement?u.appendChild(E):(f.textContent=d,u.appendChild(f));let T=(Ee=s.loadingAnimation)!=null?Ee:"none",S=n.activeTextTemplate,k=n.completeTextTemplate,x=p?S:k,b=E instanceof HTMLElement,h=(X,Ue,K)=>{let Te=K;for(let ae of Ue){let xe=v("span","persona-tool-char");xe.style.setProperty("--char-index",String(Te)),xe.textContent=ae===" "?"\xA0":ae,X.appendChild(xe),Te++}return Te},M=(X,Ue)=>{var xe;f.textContent="";let K=((xe=r.name)==null?void 0:xe.trim())||"tool",Te=ji(X,K),ae=0;for(let Me of Te){let Ke=Me.styles.length>0?(()=>{let ce=v("span",Me.styles.map(re=>`persona-tool-text-${re}`).join(" "));return f.appendChild(ce),ce})():f;if(Me.isDuration&&p)Ke.appendChild(A());else{let ce=Me.isDuration?Is(r):Me.text;Ue?ae=h(Ke,ce,ae):Ke.appendChild(document.createTextNode(ce))}}};if(!b)if(p&&T!=="none"){let X=(Ge=n.loadingAnimationDuration)!=null?Ge:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),x&&M(x,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),T==="shimmer-color"&&(n.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),x)M(x,!0);else{let Ue=f.textContent||d;f.textContent="",h(f,Ue,0)}}else x&&M(x,!1);let W=null;if(a){W=v("div","persona-flex persona-items-center");let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?W.appendChild(Ue):W.textContent=i?"Hide":"Show";let K=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(W),m.append(u,K)}else m.append(u);let R=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","tool"),R.style.display="none",R.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let X=(_e=n.renderCollapsedPreview)==null?void 0:_e.call(n,{message:t,toolCall:r,defaultPreview:l,isActive:p,config:e!=null?e:{}});Zw(R,X)||(R.textContent=l),R.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(m,R),o;let B=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=i?"":"none",n.contentBackgroundColor&&(B.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(B.style.color=n.contentTextColor),n.contentPaddingX&&(B.style.paddingLeft=n.contentPaddingX,B.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(B.style.paddingTop=n.contentPaddingY,B.style.paddingBottom=n.contentPaddingY),r.name){let X=v("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?X.style.color=n.contentTextColor:n.headerTextColor&&(X.style.color=n.headerTextColor),X.textContent=r.name,B.appendChild(X)}if(r.args!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Arguments";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ia(r.args),X.append(Ue,K),B.appendChild(X)}if(r.chunks&&r.chunks.length){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Activity";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=r.chunks.join(""),X.append(Ue,K),B.appendChild(X)}if(r.status==="complete"&&r.result!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Result";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ia(r.result),X.append(Ue,K),B.appendChild(X)}if(r.status==="complete"&&typeof r.duration=="number"){let X=v("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(X.style.color=n.contentTextColor),X.textContent=`Duration: ${r.duration}ms`,B.appendChild(X)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?W.appendChild(Ue):W.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",R.style.display=i?"none":R.textContent||R.childNodes.length?"":"none"})(),o.append(m,R,B),o};var Do=od(Ui(),1);var Qp="ask_user_question",Jp=8,Ua="data-persona-ask-sheet-for",rv="Other",nv="Other\u2026",wx="Type your own answer here",vx="Send",ov="Next",av="Back",sv="Submit all",iv="Skip",lv=3,Yp="data-ask-current-index",Zp="data-ask-question-count",Cx="data-ask-answers",eu="data-ask-grouped",Ax="data-ask-layout",dv=t=>t.layout==="pills"?"pills":"rows",cv=t=>t.getAttribute(Ax)==="pills"?"pills":"rows",bx=!1,Sx=t=>t.replace(/["\\]/g,"\\$&"),ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Qp,Nl=t=>{var e,r;return(r=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?r:{}},xo=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let r=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:r};let n=e.chunks;if(!n||n.length===0)return{payload:null,complete:r};try{let o=n.join(""),s=(0,Do.parse)(o,Do.STR|Do.OBJ|Do.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},Gs=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Jp&&!bx&&(bx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Jp}.`)),e.slice(0,Jp)},pv=t=>{var e;return(e=Gs(t)[0])!=null?e:null},uv=(t,e)=>{var r;return(r=Gs(t)[e])!=null?r:null},Tx=(t,e)=>{let r=e.styles;r&&(r.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Mx=(t,e,r)=>{if(t!=="rows")return null;let n=v("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");n.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},fv=(t,e,r,n)=>{let s=v("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",n?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),r==="rows"){let a=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let l=v("span","persona-ask-row-description");l.textContent=t.description,a.appendChild(l)}s.appendChild(a);let d=Mx(r,n,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},mv=t=>{let r=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},gv=(t,e,r,n)=>{var p,m,u;let s=v("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!r){for(let f=0;f<lv;f++)s.appendChild(mv(n));return s}if(d.forEach((f,y)=>{s.appendChild(fv(f,y,n,a))}),(t==null?void 0:t.allowFreeText)!==!1){let f=n==="rows"?rv:nv;if(n==="rows"){let y=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let A=v("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=e.freeTextPlaceholder)!=null?p:wx,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),A.appendChild(E),y.appendChild(A);let T=Mx(n,a,d.length);T&&y.appendChild(T),s.appendChild(y)}else{let y=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(u=e.freeTextLabel)!=null?u:f,s.appendChild(y)}}return s},kx=(t,e)=>{var s,a;let n=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:wx,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),e!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:vx,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},hv=t=>{var n;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let r=v("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=t.submitLabel)!=null?n:vx,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,e.appendChild(r),e},xv=(t,e,r)=>{var l,p,m,u;let n=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:av,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,n.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:iv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(m=r.submitAllLabel)!=null?m:sv:(u=r.nextLabel)!=null?u:ov,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},fa=t=>{let e=t.getAttribute(Cx);if(!e)return{};try{let r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}},Ex=(t,e)=>{t.setAttribute(Cx,JSON.stringify(e))},En=t=>{var r;let e=Number((r=t.getAttribute(Yp))!=null?r:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},yv=(t,e)=>{t.setAttribute(Yp,String(Math.max(0,Math.floor(e))))},za=t=>{var r;let e=Number((r=t.getAttribute(Zp))!=null?r:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Oo=t=>t.getAttribute(eu)==="true",bv=(t,e)=>{var o;let r=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let n={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let d=r[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},wv=(t,e)=>{var n;let r=(n=t.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(e-1,Math.floor(r)))},Fl=(t,e)=>{let{payload:r}=xo(e),n=Gs(r),o=fa(t),s={},a=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Lx=t=>{let e=fa(t),r=En(t),n=e[r],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!a.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Px=t=>{if(!Oo(t))return;let e=fa(t),r=En(t),n=e[r],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},tu=(t,e,r)=>{let n=Nl(r),o=cv(t),{payload:s,complete:a}=xo(e),i=Oo(t),d=En(t),l=za(t),p=i?uv(s,d):pv(s),m=!!(p!=null&&p.multiSelect),u=t.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${l}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let y=t.querySelector('[data-ask-question="true"]');if(y){let S=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=S,y.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let A=t.querySelector('[data-ask-pill-list="true"]');if(A){let S=gv(p,n,a,o);A.replaceWith(S)}if(o!=="rows"){let S=t.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(kx(n,o))}let E=t.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!E?t.appendChild(hv(n)):(!m||i)&&E&&E.remove(),t.setAttribute("data-multi-select",m?"true":"false");let T=t.querySelector('[data-ask-nav-row="true"]');if(i){let S=xv(d,l,n);T?T.replaceWith(S):t.appendChild(S)}else T&&T.remove();Lx(t),Px(t)},vv=(t,e,r)=>{let n=Nl(e),o=dv(n),s=t.toolCall.id,a=Gs(r),i=Math.max(1,a.length),d=i>1,l=bv(t,a),p=d?wv(t,i):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ua,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Zp,String(i)),m.setAttribute(Yp,String(p)),m.setAttribute(eu,d?"true":"false"),m.setAttribute(Ax,o),Ex(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Tx(m,n);let u=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=v("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",u.appendChild(f);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",u.appendChild(y),m.appendChild(u);let E=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),m.appendChild(E),o!=="rows"&&m.appendChild(kx(n,o)),tu(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Cv=(t,e,r)=>{let{payload:n}=xo(e),o=Math.max(1,Gs(n).length);o>za(t)&&(t.setAttribute(Zp,String(o)),o>1&&!Oo(t)&&t.setAttribute(eu,"true")),tu(t,e,r)},Ix=(t,e)=>{let r=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Nl(e);Tx(r,n);let o=v("span","persona-ask-stub-label"),{complete:s}=xo(t);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},qa=(t,e,r)=>{if(!r||!ho(t)||Nl(e).enabled===!1)return;let o=t.toolCall.id;r.querySelectorAll(`[${Ua}]`).forEach(l=>{l.getAttribute(Ua)!==o&&l.remove()});let a=r.querySelector(`[${Ua}="${Sx(o)}"]`);if(a){Cv(a,t,e);return}let{payload:i}=xo(t),d=vv(t,e,i);r.appendChild(d)},_o=(t,e)=>{if(!t)return;let r=e?`[${Ua}="${Sx(e)}"]`:`[${Ua}]`;t.querySelectorAll(r).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},ru=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),No=(t,e)=>{let r=fa(t),n=En(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete r[n]:r[n]=e,Ex(t,r),Lx(t),Px(t)},$l=(t,e,r,n)=>{let o=za(t),s=Math.max(0,Math.min(o-1,n));yv(t,s),tu(t,e,r)};var nu=(t,e)=>{var A,E,T,S,k,x,b,h,M,W,R,B;let r=t.approval,n=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(A=n==null?void 0:n.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=n==null?void 0:n.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!r)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=v("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(T=n==null?void 0:n.titleColor)!=null?T:"currentColor",p=Ie(d,20,l,2);p&&i.appendChild(p);let m=v("div","persona-flex-1 persona-min-w-0"),u=v("div","persona-flex persona-items-center persona-gap-2"),f=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(S=n==null?void 0:n.title)!=null?S:"Approval Required",u.appendChild(f),!o){let _=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",r.status),r.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):r.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):r.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),u.appendChild(_)}m.appendChild(u);let y=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(y.style.color=n.descriptionColor),y.textContent=r.description,m.appendChild(y),r.parameters){let _=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(_.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(_.style.color=n.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=Ia(r.parameters),m.appendChild(_)}if(o){let _=v("div","persona-flex persona-gap-2 persona-mt-2");_.setAttribute("data-approval-buttons","true");let V=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=(k=n==null?void 0:n.approveButtonColor)!=null?k:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(x=n==null?void 0:n.approveButtonTextColor)!=null?x:"#ffffff",V.setAttribute("data-approval-action","approve");let oe=Ie("shield-check",14,(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",2);oe&&(oe.style.marginRight="4px",V.appendChild(oe));let be=document.createTextNode((h=n==null?void 0:n.approveLabel)!=null?h:"Approve");V.appendChild(be);let Qe=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Qe.type="button",Qe.style.backgroundColor=(M=n==null?void 0:n.denyButtonColor)!=null?M:"transparent",Qe.style.color=(W=n==null?void 0:n.denyButtonTextColor)!=null?W:"var(--persona-feedback-error, #dc2626)",Qe.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Qe.setAttribute("data-approval-action","deny");let je=Ie("shield-x",14,(R=n==null?void 0:n.denyButtonTextColor)!=null?R:"var(--persona-feedback-error, #dc2626)",2);je&&(je.style.marginRight="4px",Qe.appendChild(je));let ve=document.createTextNode((B=n==null?void 0:n.denyLabel)!=null?B:"Deny");Qe.appendChild(ve),_.append(V,Qe),m.appendChild(_)}return a.append(i,m),s.appendChild(a),s};var Rx=t=>{let e=[];return{buttons:e,render:(n,o,s,a,i)=>{if(t.innerHTML="",e.length=0,!n||!n.length||(a!=null?a:o?o.getMessages():[]).some(f=>f.role==="user"))return;let p=document.createDocumentFragment(),m=o?o.isStreaming():!1,u=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let y=v("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");y.type="button",y.textContent=f,y.disabled=m,i!=null&&i.fontFamily&&(y.style.fontFamily=u(i.fontFamily)),i!=null&&i.fontWeight&&(y.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(y.style.paddingLeft=i.paddingX,y.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(y.style.paddingTop=i.paddingY,y.style.paddingBottom=i.paddingY),y.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),p.appendChild(y),e.push(y)}),t.appendChild(p)}}};var Ks=class{constructor(e=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=r}push(e){var r;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(r=this.store)==null||r.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let r=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let n of r)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=e.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let r=this.getAll();return e>=r.length?r:r.slice(r.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(e="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=r}open(){return new Promise((e,r)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}getAll(){return new Promise((e,r)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{r(a.error)}}catch(n){r(n)}})}getCount(){return new Promise((e,r)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}clear(){return new Promise((e,r)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,r)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}};var Av=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Sv=new Set(["step_start","execution_start"]),Tv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Mv=new Set(["step_complete","agent_turn_complete"]),kv=new Set(["flow_complete","agent_complete"]),Wx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ma=(t,e)=>{let r=t[e];return Hx(r)?r:void 0};function ou(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ul(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Ev(t,e){return typeof e.type=="string"?e.type:t}function Lv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Pv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Bx(t){var n,o,s,a,i;let e=ma(t,"result"),r=[ma(t,"tokens"),ma(t,"totalTokens"),e?ma(e,"tokens"):void 0,ma(t,"usage"),e?ma(e,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=bn(d.output))!=null?n:bn(d.outputTokens))!=null?o:bn(d.completionTokens);if(l!==void 0)return l}return(i=(s=bn(t.outputTokens))!=null?s:bn(t.completionTokens))!=null?i:e?(a=bn(e.outputTokens))!=null?a:bn(e.completionTokens):void 0}function Iv(t){var r,n,o,s,a;let e=ma(t,"result");return(a=(o=(n=(r=bn(t.executionTime))!=null?r:bn(t.executionTimeMs))!=null?n:bn(t.execution_time))!=null?o:bn(t.duration))!=null?a:e?(s=bn(e.executionTime))!=null?s:bn(e.executionTimeMs):void 0}function Rv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Js=class{constructor(e=Rv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Ul(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,r){var s;if(!Hx(r)){Wx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=Ev(e,r),o=this.now();if(Av.has(n)){this.startRun(o);return}if(Sv.has(n)){this.run||this.startRun(o);return}if(Tv.has(n)){if(!Pv(n,r))return;let a=Lv(r);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+ou(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ul(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Mv.has(n)){if(!this.run)return;let a=this.run,i=Bx(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+ou(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:Ul(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(kv.has(n)){if(!this.run)return;let a=this.run,i=Bx(r),d=i!=null?i:a.exactOutputTokens+ou(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:Ul(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Wx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,r,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Iv(r);return s!=null?s:n-e.startedAt}};function Va(t,e){e&&e.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Wv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Bv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Hv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Dv=100;function Ov(t,e){let r={...Wv,...e};if(r[t])return r[t];for(let n of Object.keys(r))if(n.endsWith("_")&&t.startsWith(n))return r[n];return Bv}function _v(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Nv(t){let e=new Date(t),r=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${r}:${n}:${o}.${s}`}function Fv(t,e){try{let r=JSON.parse(t);if(typeof r!="object"||r===null)return null;for(let n of e){let o=n.split("."),s=r;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function $v(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(r=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),r()})}function Uv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function zv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function qv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Vv(t,e,r){let n,o;try{o=JSON.parse(t.payload),n=JSON.stringify(o,null,2)}catch{o=t.payload,n=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let i=s.renderEventStreamPayload({event:t,config:r,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function au(t,e,r,n,o,s,a,i){var u;let d=o.has(t.id),l=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Va(l,(u=n.classNames)==null?void 0:u.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(f)return l.appendChild(f),l}return l.appendChild(m()),l;function m(){var V,oe;let f=v("div",""),y=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");y.setAttribute("data-event-id",t.id);let A=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Ie(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&A.appendChild(E);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(V=n.timestampFormat)!=null?V:"relative";T.textContent=S==="relative"?_v(t.timestamp,r):Nv(t.timestamp);let k=null;n.showSequenceNumbers!==!1&&(k=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let x=Ov(t.type,n.badgeColors),b=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");b.style.backgroundColor=x.bg,b.style.color=x.text,b.style.borderColor=x.text+"50",b.textContent=t.type;let h=(oe=n.descriptionFields)!=null?oe:Hv,M=Fv(t.payload,h),W=null;M&&(W=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=M);let R=v("div","persona-flex-1 persona-min-w-0"),B=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),_=Ie("clipboard","12px","currentColor",1.5);return _&&B.appendChild(_),B.addEventListener("click",async be=>{be.stopPropagation(),await $v(Uv(t)),B.innerHTML="";let Qe=Ie("check","12px","currentColor",1.5);Qe&&B.appendChild(Qe),setTimeout(()=>{B.innerHTML="";let je=Ie("clipboard","12px","currentColor",1.5);je&&B.appendChild(je)},1500)}),y.appendChild(A),y.appendChild(T),k&&y.appendChild(k),y.appendChild(b),W&&y.appendChild(W),y.appendChild(R),y.appendChild(B),f.appendChild(y),d&&f.appendChild(Vv(t,a,i)),f}}function Dx(t){var y,A,E,T,S;let{buffer:e,getFullHistory:r,onClose:n,config:o,plugins:s=[],getThroughput:a}=t,i=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(A=i==null?void 0:i.iconName)!=null?A:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",m=(S=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?S:{},u=s.find(k=>k.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let k=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=m.classNames,x=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Va(x,k==null?void 0:k.panel);let b=[],h="",M="",W=null,R=[],B={},_=0,V=Cl(),oe=0,be=0,Qe=!1,je=null,ve=!1,Ee=0,Ge=new Set,_e=new Map,X="",Ue="",K=null,Te,ae,xe,Me,Ke,ce=null,re=null,le=null;function ut(){let de=v("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ye=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Va(ye,k==null?void 0:k.headerBar);let Rt=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Rt.textContent="Events",Te=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Te.textContent="0",a){re=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),re.style.cursor="help";let dr=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");dr.textContent="Throughput",ce=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ce.textContent="-- tok/s",le=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let wr=re,Lr=le,Or=()=>{if(!Lr.textContent)return;let sn=wr.getBoundingClientRect(),fr=de.getBoundingClientRect();Lr.style.left=`${sn.left-fr.left}px`,Lr.style.top=`${sn.bottom-fr.top+4}px`,Lr.style.display="block"},xt=()=>{Lr.style.display="none"};re.addEventListener("mouseenter",Or),re.addEventListener("mouseleave",xt),re.appendChild(dr),re.appendChild(ce)}let ar=v("div","persona-flex-1");ae=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let kt=v("option","");kt.value="",kt.textContent="All events",ae.appendChild(kt),xe=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),xe.type="button",xe.title="Copy All";let Ot=Ie("clipboard-copy","12px","currentColor",1.5);Ot&&xe.appendChild(Ot);let Wt=v("span","persona-text-xs");Wt.textContent="Copy All",xe.appendChild(Wt),ye.appendChild(Rt),ye.appendChild(Te),re&&ye.appendChild(re),ye.appendChild(ar),ye.appendChild(ae),ye.appendChild(xe);let St=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Va(St,k==null?void 0:k.searchBar);let Et=Ie("search","14px","var(--persona-muted, #9ca3af)",1.5),sr=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Et&&sr.appendChild(Et),Me=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Va(Me,k==null?void 0:k.searchInput),Me.type="text",Me.placeholder="Search event payloads...",Ke=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ke.type="button",Ke.style.display="none";let ft=Ie("x","12px","currentColor",2);return ft&&Ke.appendChild(ft),St.appendChild(sr),St.appendChild(Me),St.appendChild(Ke),de.appendChild(ye),de.appendChild(St),le&&de.appendChild(le),de}let Ce,he=s.find(de=>de.renderEventStreamToolbar);if(he!=null&&he.renderEventStreamToolbar&&o){let de=he.renderEventStreamToolbar({config:o,defaultRenderer:()=>ut(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ye=>{h=ye,pe(),N()},onSearchChange:ye=>{M=ye,pe(),N()}});Ce=de!=null?de:ut()}else Ce=ut();let tt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");tt.style.display="none";function Ne(){if(!a||!ce||!re)return;let de=a();ce.textContent=zv(de);let ye=qv(de);le&&(le.textContent=ye,ye||(le.style.display="none")),ye?re.setAttribute("aria-label",ye):re.removeAttribute("aria-label")}let me=v("div","persona-flex-1 persona-min-h-0 persona-relative"),J=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let qe=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Va(qe,k==null?void 0:k.scrollIndicator),qe.style.display="none",qe.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Z=Ie(l,"14px","currentColor",2);Z&&qe.appendChild(Z);let ge=v("span","");ge.textContent=p,qe.appendChild(ge);let q=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");q.style.display="none",me.appendChild(J),me.appendChild(q),me.appendChild(qe),x.setAttribute("tabindex","0"),x.appendChild(Ce),x.appendChild(tt),x.appendChild(me);function Re(){let de=e.getAll(),ye={};for(let Wt of de)ye[Wt.type]=(ye[Wt.type]||0)+1;let Rt=Object.keys(ye).sort(),ar=Rt.length!==R.length||!Rt.every((Wt,St)=>Wt===R[St]),kt=!ar&&Rt.some(Wt=>ye[Wt]!==B[Wt]),mr=de.length!==Object.values(B).reduce((Wt,St)=>Wt+St,0);if(!ar&&!kt&&!mr||(R=Rt,B=ye,!ae))return;let Ot=ae.value;if(ae.options[0].textContent="All events",ar){for(;ae.options.length>1;)ae.remove(1);for(let Wt of Rt){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${ye[Wt]||0})`,ae.appendChild(St)}Ot&&Rt.includes(Ot)?ae.value=Ot:Ot&&(ae.value="",h="")}else for(let Wt=1;Wt<ae.options.length;Wt++){let St=ae.options[Wt];St.textContent=`${St.value} (${ye[St.value]||0})`}}function Ae(){let de=e.getAll();if(h&&(de=de.filter(ye=>ye.type===h)),M){let ye=M.toLowerCase();de=de.filter(Rt=>Rt.type.toLowerCase().includes(ye)||Rt.payload.toLowerCase().includes(ye))}return de}function fe(){return h!==""||M!==""}function pe(){_=0,oe=0,V.resume(),qe.style.display="none"}function Be(de){Ge.has(de)?Ge.delete(de):Ge.add(de),K=de;let ye=J.scrollTop,Rt=V.isFollowing();ve=!0,V.pause(),N(),J.scrollTop=ye,Rt&&V.resume(),ve=!1}function Q(){return _s(J,50)}function N(){be=Date.now(),Qe=!1,Ne(),Re();let de=e.getEvictedCount();de>0?(tt.textContent=`${de.toLocaleString()} older events truncated`,tt.style.display=""):tt.style.display="none",b=Ae();let ye=b.length,Rt=e.getSize()>0;Te&&(Te.textContent=String(e.getSize())),ye===0&&Rt&&fe()?(q.textContent=M?`No events matching '${M}'`:"No events matching filter",q.style.display="",J.style.display="none"):(q.style.display="none",J.style.display=""),xe&&(xe.title=fe()?`Copy Filtered (${ye})`:"Copy All"),d&&!V.isFollowing()&&ye>_&&(oe+=ye-_,ge.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",qe.style.display=""),_=ye;let ar=e.getAll(),kt=ar.length>0?ar[0].timestamp:0,mr=new Set(b.map(St=>St.id));for(let St of Ge)mr.has(St)||Ge.delete(St);let Ot=h!==X||M!==Ue,Wt=_e.size===0&&b.length>0;if(Ot||Wt||b.length===0){J.innerHTML="",_e.clear();let St=document.createDocumentFragment();for(let Et=0;Et<b.length;Et++){let sr=au(b[Et],Et,kt,m,Ge,Be,s,o);_e.set(b[Et].id,sr),St.appendChild(sr)}J.appendChild(St),X=h,Ue=M,K=null}else{if(K!==null){let Et=_e.get(K);if(Et&&Et.parentNode===J){let sr=b.findIndex(ft=>ft.id===K);if(sr>=0){let ft=au(b[sr],sr,kt,m,Ge,Be,s,o);J.insertBefore(ft,Et),Et.remove(),_e.set(K,ft)}}K=null}let St=new Set(b.map(Et=>Et.id));for(let[Et,sr]of _e)St.has(Et)||(sr.remove(),_e.delete(Et));for(let Et=0;Et<b.length;Et++){let sr=b[Et];if(!_e.has(sr.id)){let ft=au(sr,Et,kt,m,Ge,Be,s,o);_e.set(sr.id,ft),J.appendChild(ft)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function ke(){if(Date.now()-be>=Dv){je!==null&&(cancelAnimationFrame(je),je=null),N();return}Qe||(Qe=!0,je=requestAnimationFrame(()=>{je=null,N()}))}let He=(de,ye)=>{if(!xe)return;xe.innerHTML="";let Rt=Ie(de,"12px","currentColor",1.5);Rt&&xe.appendChild(Rt);let ar=v("span","persona-text-xs");ar.textContent="Copy All",xe.appendChild(ar),setTimeout(()=>{xe.innerHTML="";let kt=Ie("clipboard-copy","12px","currentColor",1.5);kt&&xe.appendChild(kt);let mr=v("span","persona-text-xs");mr.textContent="Copy All",xe.appendChild(mr),xe.disabled=!1},ye)},Ve=async()=>{if(xe){xe.disabled=!0;try{let de;fe()?de=b:r?(de=await r(),de.length===0&&(de=e.getAll())):de=e.getAll();let ye=de.map(Rt=>{try{return JSON.parse(Rt.payload)}catch{return Rt.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),He("check",1500)}catch{He("x",1500)}}},Xe=()=>{ae&&(h=ae.value,pe(),N())},gt=()=>{!Me||!Ke||(Ke.style.display=Me.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{M=Me.value,pe(),N()},150))},ot=()=>{!Me||!Ke||(Me.value="",M="",Ke.style.display="none",W&&clearTimeout(W),pe(),N())},Mt=()=>{if(ve)return;let de=J.scrollTop,{action:ye,nextLastScrollTop:Rt}=Al({following:V.isFollowing(),currentScrollTop:de,lastScrollTop:Ee,nearBottom:Q(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ee=Rt,ye==="resume"?(V.resume(),oe=0,qe.style.display="none"):ye==="pause"&&(V.pause(),d&&(ge.textContent=p,qe.style.display=""))},Xt=de=>{let ye=Sl({following:V.isFollowing(),deltaY:de.deltaY,nearBottom:Q(),resumeWhenNearBottom:!0});ye==="pause"?(V.pause(),d&&(ge.textContent=p,qe.style.display="")):ye==="resume"&&(V.resume(),oe=0,qe.style.display="none")},G=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),oe=0,qe.style.display="none")},Jt=de=>{let ye=de.target;if(!ye||ye.closest("button"))return;let Rt=ye.closest("[data-event-id]");if(!Rt)return;let ar=Rt.getAttribute("data-event-id");ar&&Be(ar)},at=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),Me==null||Me.focus(),Me==null||Me.select();return}de.key==="Escape"&&(Me&&document.activeElement===Me?(ot(),Me.blur(),x.focus()):n&&n())};xe&&xe.addEventListener("click",Ve),ae&&ae.addEventListener("change",Xe),Me&&Me.addEventListener("input",gt),Ke&&Ke.addEventListener("click",ot),J.addEventListener("scroll",Mt),J.addEventListener("wheel",Xt,{passive:!0}),J.addEventListener("click",Jt),qe.addEventListener("click",G),x.addEventListener("keydown",at);function Nt(){W&&clearTimeout(W),je!==null&&(cancelAnimationFrame(je),je=null),Qe=!1,_e.clear(),xe&&xe.removeEventListener("click",Ve),ae&&ae.removeEventListener("change",Xe),Me&&Me.removeEventListener("input",gt),Ke&&Ke.removeEventListener("click",ot),J.removeEventListener("scroll",Mt),J.removeEventListener("wheel",Xt),J.removeEventListener("click",Jt),qe.removeEventListener("click",G),x.removeEventListener("keydown",at)}return{element:x,update:ke,destroy:Nt}}}function Ox(t,e){let r=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",n=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(u);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(l.append(p,m),i.append(d,l),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",n),i.append(u)}return i}var _x=(t,e)=>{var n,o,s;let r=(s=(o=(n=e==null?void 0:e.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(r){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=r({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:e.config,defaultRenderer:()=>Ox(t,e)});if(p)return p}return Ox(t,e)};var su=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,n])=>{this.register(r,n)})}},yo=new su;yo.register("PersonaArtifactCard",_x);function jv(t){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=v("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=t.component?`Component: ${t.component}`:"Component";let n=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(r),e.appendChild(n),e}function Nx(t,e){var ae,xe,Me,Ke;let r=(xe=(ae=t.features)==null?void 0:ae.artifacts)==null?void 0:xe.layout,o=((Me=r==null?void 0:r.toolbarPreset)!=null?Me:"default")==="document",s=(Ke=r==null?void 0:r.panePadding)==null?void 0:Ke.trim(),a=t.markdown?ra(t.markdown):null,i=ka(t.sanitize),d=ce=>{let re=a?a(ce):na(ce);return i?i(re):re},l=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let m=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),o&&m.classList.add("persona-artifact-pane-document");let u=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let f=v("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let y=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let A="rendered",E=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Er({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Er({icon:"eye",label:"Rendered view"}),S=o?Er({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Er({icon:"code-2",label:"Source"}),k=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),x=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,b=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,h=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(b&&h&&h.length>0),W=null,R,B=null,_=null;if(o&&(x||b)&&!M){if(R=x?js({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),b){let ce=Ie("chevron-down",14,"currentColor",2);ce&&R.appendChild(ce)}}else o&&M?(W=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),R=x?js({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=Er({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),W.append(R,B)):o?R=Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):R=Er({icon:"copy",label:"Copy"});let V=o?Er({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Er({icon:"refresh-cw",label:"Refresh"}),oe=o?Er({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Er({icon:"x",label:"Close"}),be=()=>{var Ce,he,tt;let ce=(Ce=_e.find(Ne=>Ne.id===X))!=null?Ce:_e[_e.length-1],re=(he=ce==null?void 0:ce.id)!=null?he:null,le=(ce==null?void 0:ce.artifactType)==="markdown"&&(tt=ce.markdown)!=null?tt:"",ut=ce?JSON.stringify({component:ce.component,props:ce.props},null,2):"";return{markdown:le,jsonPayload:ut,id:re}},Qe=async()=>{var Ce;let{markdown:ce,jsonPayload:re}=be(),le=(Ce=_e.find(he=>he.id===X))!=null?Ce:_e[_e.length-1],ut=(le==null?void 0:le.artifactType)==="markdown"?ce:le?re:"";try{await navigator.clipboard.writeText(ut)}catch{}};if(R.addEventListener("click",async()=>{let ce=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ce&&M){let{markdown:re,jsonPayload:le,id:ut}=be();try{await ce({actionId:"primary",artifactId:ut,markdown:re,jsonPayload:le})}catch{}return}await Qe()}),B&&(h!=null&&h.length)){let ce=()=>{var le;return(le=m.closest("[data-persona-root]"))!=null?le:document.body},re=()=>{_=Ho({items:h.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:ut,jsonPayload:Ce,id:he}=be(),tt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{tt?await tt({actionId:le,artifactId:he,markdown:ut,jsonPayload:Ce}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(ut):le==="json"||le==="source"?await navigator.clipboard.writeText(Ce):await navigator.clipboard.writeText(ut||Ce)}catch{}},anchor:W!=null?W:B,position:"bottom-right",portal:ce()})};m.isConnected?re():requestAnimationFrame(re),B.addEventListener("click",le=>{le.stopPropagation(),_==null||_.toggle()})}V.addEventListener("click",async()=>{var ce;try{await((ce=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ce.call(r))}catch{}K()}),oe.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let je=()=>{o&&(T.setAttribute("aria-pressed",A==="rendered"?"true":"false"),S.setAttribute("aria-pressed",A==="source"?"true":"false"))};T.addEventListener("click",()=>{A="rendered",je(),K()}),S.addEventListener("click",()=>{A="source",je(),K()});let ve=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),E.append(T,S),W?k.append(W,V,oe):k.append(R,V,oe),u.append(E,ve,k),je()):(u.appendChild(f),u.appendChild(y)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Ee=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Ge=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ee.style.paddingLeft=s,Ee.style.paddingRight=s,Ge.style.padding=s),m.appendChild(u),m.appendChild(Ee),m.appendChild(Ge);let _e=[],X=null,Ue=!1,K=()=>{var ut,Ce,he,tt;let ce=o&&_e.length<=1;Ee.classList.toggle("persona-hidden",ce),Ee.replaceChildren();for(let Ne of _e){let me=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");me.type="button",me.textContent=Ne.title||Ne.id.slice(0,8),Ne.id===X&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>e.onSelect(Ne.id)),Ee.appendChild(me)}Ge.replaceChildren();let re=X&&_e.find(Ne=>Ne.id===X)||_e[_e.length-1];if(!re)return;if(o){let Ne=re.artifactType==="markdown"?"MD":(ut=re.component)!=null?ut:"Component",J=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${J} \xB7 ${Ne}`}else f.textContent="Artifacts";if(re.artifactType==="markdown"){if(o&&A==="source"){let me=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(Ce=re.markdown)!=null?Ce:"",Ge.appendChild(me);return}let Ne=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ne.innerHTML=d((he=re.markdown)!=null?he:""),Ge.appendChild(Ne);return}let le=re.component?yo.get(re.component):void 0;if(le){let me={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let J=le((tt=re.props)!=null?tt:{},me);if(J){Ge.appendChild(J);return}}catch{}}Ge.appendChild(jv(re))},Te=()=>{var re;let ce=_e.length>0;if(m.classList.toggle("persona-hidden",!ce),l){let le=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ce=((re=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ce&&Ce&&Ue?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(ce){var re,le,ut;_e=ce.artifacts,X=(ut=(le=ce.selectedId)!=null?le:(re=ce.artifacts[ce.artifacts.length-1])==null?void 0:re.id)!=null?ut:null,_e.length>0&&(Ue=!0),K(),Te()},setMobileOpen(ce){Ue=ce,!ce&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Te()}}}function Ln(t){var e,r;return((r=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:r.enabled)===!0}function Fx(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Ln(e))return;let r=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,n=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),o=(d=r==null?void 0:r.paneBorderLeft)==null?void 0:d.trim();n?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",n)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function Gv(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function zl(t,e){var d,l,p,m,u,f,y,A,E,T;if(!Ln(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Gv(t),Fx(t,e);return}let r=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;t.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(m=r==null?void 0:r.paneWidth)!=null?m:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=r==null?void 0:r.paneBackground)==null?void 0:f.trim();n?t.style.setProperty("--persona-artifact-pane-bg",n):t.style.removeProperty("--persona-artifact-pane-bg");let o=(y=r==null?void 0:r.panePadding)==null?void 0:y.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(A=r==null?void 0:r.documentToolbarIconColor)==null?void 0:A.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Fx(t,e)}var $x=["panel","seamless"];function ql(t,e){var i,d,l,p,m,u;for(let f of $x)t.classList.remove(`persona-artifact-appearance-${f}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!Ln(e))return;let r=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",o=$x.includes(n)?n:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=r==null?void 0:r.paneShadow)==null?void 0:m.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(r==null?void 0:r.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let f=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;f&&t.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Ux(t,e){var r,n,o;return!e||!Ln(t)?!1:((o=(n=(r=t.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Kv(t,e){if(!(t!=null&&t.trim()))return e;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return r?Math.max(0,Number(r[1])):e}function Xv(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Jv(t,e,r){return r<e?e:Math.min(r,Math.max(e,t))}function Qv(t,e,r,n){let o=t-n-2*e-r;return Math.max(0,o)}function zx(t,e){var a;let n=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(n);return s?Number(s[1]):8}function qx(t,e,r,n,o,s){let a=Kv(o,200),i=Qv(e,r,n,200);i=Math.max(a,i);let d=Xv(s);return d!==null&&(i=Math.min(i,d)),Jv(t,a,i)}var Vx={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},iu=(t,e,r,n)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,A,E;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(A=Vx[a])!=null?A:Vx.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),l=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=v("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var h,M;let S=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${e.id}-${a}-${T.name}`;let k=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,S.appendChild(k);let x=(h=T.type)!=null?h:"text",b;x==="textarea"?(b=document.createElement("textarea"),b.rows=3):(b=document.createElement("input"),b.type=x),b.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",b.id=`${e.id}-${a}-${T.name}`,b.name=T.name,b.placeholder=(M=T.placeholder)!=null?M:"",T.required&&(b.required=!0),S.appendChild(b),p.appendChild(S)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(E=i.submitLabel)!=null?E:"Submit",m.appendChild(u),m.appendChild(f),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var b,h;T.preventDefault();let S=(b=r.formEndpoint)!=null?b:"/form",k=new FormData(p),x={};k.forEach((M,W)=>{x[W]=M}),x.type=a,f.disabled=!0,u.textContent="Submitting\u2026";try{let M=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let W=await M.json();u.textContent=(h=W.message)!=null?h:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await n.sendMessage(String(W.nextPrompt))}catch(M){u.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var lu=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var n;let r=this.plugins.get(e);r&&((n=r.onUnregister)==null||n.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var n,o;return((n=r.priority)!=null?n:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let n=new Set(e.map(s=>s.id));return[...r.filter(s=>!n.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},Qs=new lu;var jx=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Yv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Zv=t=>{let e=t.trim(),r=e.indexOf("{");if(r===-1)return null;let n=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(n+=1),s==="}"&&(n-=1,n===0))return e.slice(r,o+1)}return null},Ys=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Yv(t),r=Zv(e);if(!r)return null;let n=JSON.parse(r);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...s}=n;return{type:String(o),payload:s,raw:n}}catch{return null}},du=t=>typeof t=="string"?t:t==null?"":String(t),ga={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:du(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,n=du(r.element);if(n&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(n);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:du(r.text)}}},Gx=t=>Array.isArray(t)?t.map(e=>String(e)):[],Zs=t=>{let e=new Set(Gx(t.getSessionMetadata().processedActionMessageIds)),r=()=>{e=new Set(Gx(t.getSessionMetadata().processedActionMessageIds))},n=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),n();let d={action:i,message:s.message};t.emit("action:detected",d);for(let l of t.handlers)if(l)try{let p=()=>{t.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let u=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:u,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var eC=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},tC=t=>t.map(e=>({...e,streaming:!1})),rC=t=>t.map(e=>({...e,status:"complete"})),Vl=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?eC(r.getItem(t)):null},save:r=>{let n=e();if(n)try{let o={...r,messages:r.messages?tC(r.messages):void 0,artifacts:r.artifacts?rC(r.artifacts):void 0};n.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(t)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var ja=od(Ui(),1);function nC(t){if(!t||typeof t!="object"||!("component"in t))return!1;let e=t.component;return typeof e=="string"&&e.length>0}function oC(t,e){if(!nC(t))return null;let r=t.props&&typeof t.props=="object"&&t.props!==null?t.props:{};return{component:t.component,props:r,raw:e}}function jl(){let t=null,e=0;return{getExtractedDirective:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t;try{let o=(0,ja.parse)(r,ja.STR|ja.OBJ),s=oC(o,r);s&&(t=s)}catch{}return e=r.length,t},reset:()=>{t=null,e=0}}}function Kx(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function Gl(t,e){let{config:r,message:n,onPropsUpdate:o}=e,s=yo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:r,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Xx(){let t=jl();return{processChunk:e=>t.processChunk(e),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function Jx(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Kl(t){let e=Jx(t);if(!e)return!1;try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Xl(t){let e=Jx(t);if(!e)return null;try{let r=JSON.parse(e);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let n=r;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e}}}catch{}return null}var aC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Jl(t){let{onSubmit:e,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=aC}=t,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,u=document.createElement("div");u.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=n,f.appendChild(y);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=o,f.appendChild(A),u.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let h=1;h<=5;h++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${h} star${h>1?"s":""}: ${l[h-1]}`),M.title=l[h-1],M.dataset.rating=String(h),M.innerHTML=`
77
77
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
78
78
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
79
79
  </svg>
80
- `,k.addEventListener("click",()=>{u=h,T.forEach((B,H)=>{let W=H<h;B.classList.toggle("selected",W),B.setAttribute("aria-checked",H===h-1?"true":"false")})}),T.push(k),E.appendChild(k)}f.appendChild(E);let A=null;if(d){let h=document.createElement("div");h.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),h.appendChild(A),f.appendChild(h)}let M=document.createElement("div");M.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=i,b.addEventListener("click",()=>{r==null||r(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=a,w.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let h=(A==null?void 0:A.value.trim())||void 0;await t(u,h),p.remove()}catch(h){w.disabled=!1,w.textContent=a,console.error("[CSAT Feedback] Failed to submit:",h)}}),M.appendChild(b),M.appendChild(w),f.appendChild(M),p.appendChild(f),p}function ed(e){let{onSubmit:t,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,y.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,y.appendChild(E),m.appendChild(y);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,A.appendChild(M),A.appendChild(b);let w=document.createElement("div");w.className="persona-feedback-numbers";let h=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("persona-feedback-detractor"):N<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{f=N,h.forEach((se,ve)=>{se.classList.toggle("selected",ve===N),se.setAttribute("aria-checked",ve===N?"true":"false")})}),h.push(q),w.appendChild(q)}T.appendChild(A),T.appendChild(w),m.appendChild(T);let k=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),N.appendChild(k),m.appendChild(N)}let B=document.createElement("div");B.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{r==null||r(),u.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let N=(k==null?void 0:k.value.trim())||void 0;await t(f,N),u.remove()}catch(N){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),B.appendChild(H),B.appendChild(W),m.appendChild(B),u.appendChild(m),u}var Xs="persona-chat-history",Ev=30*1e3,Lv={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Pv(e){var n,o,s;if(!e)return[];let t=[],r=Array.from((n=e.items)!=null?n:[]);for(let a of r){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Lv[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function td(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Iv(e){var t,r,n,o,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(n=e.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Rv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var yu=e=>!e||typeof e!="object"?{}:{...e},iy=e=>e.map(t=>({...t,streaming:!1})),ly=(e,t,r)=>{let n=e!=null&&e.markdown?ns(e.markdown):null,o=Ps(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,u;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&r&&r())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):n?d=n(a):d=os(a),o?o(d):d}};function dy(e){var i,d,l,p;let t=x("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Pe(r,n,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=x("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var rd=(e,t,r)=>{var qu,ju,Vu,Gu,Ku,Ju,Xu,Yu,Qu,Zu,ef,tf,rf,nf,of,sf,af,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,wf,Cf,vf,Sf,Af,Tf,Mf,kf,Ef,Lf,Pf,If,Rf,Wf,Hf,Bf,Df,Of,_f;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=bl(t),o=ti.getForInstance(n.plugins);n.components&&yo.registerAll(n.components);let s=ry(),i=n.persistState===!1?null:(qu=n.storageAdapter)!=null?qu:Kl(),d={},l=null,p=!1,u=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:C,open:S}=g;return S&&(p=!0),C}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let C=g!=null?g:{messages:[],metadata:{}};return u(C)});else{let g=c!=null?c:{messages:[],metadata:{}},C=u(g);C.metadata&&(d=yu(C.metadata)),(ju=C.messages)!=null&&ju.length&&(n={...n,initialMessages:C.messages}),(Vu=C.artifacts)!=null&&Vu.length&&(n={...n,initialArtifacts:C.artifacts,initialSelectedArtifactId:(Gu=C.selectedArtifactId)!=null?Gu:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=u({messages:[],metadata:{}});(Ku=c.messages)!=null&&Ku.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var C;d=(C=c({...d}))!=null?C:{},bs()},y=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ri],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[hs.message,hs.messageAndClick],E=ni({parsers:y,handlers:v,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let T=(Xu=(Ju=n.launcher)==null?void 0:Ju.enabled)!=null?Xu:!0,A=(Qu=(Yu=n.launcher)==null?void 0:Yu.autoExpand)!=null?Qu:!1,M=(Zu=n.autoFocusInput)!=null?Zu:!1,b=A,w=T,h=(tf=(ef=n.layout)==null?void 0:ef.header)==null?void 0:tf.layout,k=!1,B=()=>Ho(n),H=()=>T||B(),W=B()?!1:T?A:!0,N=!1,q=null,se=()=>{N=!0,q&&clearTimeout(q),q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},ve=ly(n,E,se),Ue=(nf=(rf=n.features)==null?void 0:rf.showReasoning)!=null?nf:!0,je=(sf=(of=n.features)==null?void 0:of.showToolCalls)!=null?sf:!0,we=(lf=(af=n.features)==null?void 0:af.showEventStreamToggle)!=null?lf:!1,Te=(cf=(df=n.features)==null?void 0:df.scrollToBottom)!=null?cf:{},Oe=`${(uf=typeof n.persistState=="object"?(pf=n.persistState)==null?void 0:pf.keyPrefix:void 0)!=null?uf:"persona-"}event-stream`,K=we?new Za(Oe):null,He=(gf=(mf=(ff=n.features)==null?void 0:ff.eventStream)==null?void 0:mf.maxEvents)!=null?gf:2e3,j=we?new Qa(He,K):null,Ce=we?new ei:null,Z=null,he=!1,xe=null,Ve=0;K==null||K.open().then(()=>j==null?void 0:j.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let G={onCopy:c=>{var g,C;s.emit("message:copy",c),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(c.id,"copy").catch(S=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(C=(g=n.messageActions)==null?void 0:g.onCopy)==null||C.call(g,c)},onFeedback:c=>{var g,C;s.emit("message:feedback",c),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(c.messageId,c.type).catch(S=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(C=(g=n.messageActions)==null?void 0:g.onFeedback)==null||C.call(g,c)}},ee=(hf=n.statusIndicator)!=null?hf:{},Ie=c=>{var g,C,S,_;return c==="idle"?(g=ee.idleText)!=null?g:zr.idle:c==="connecting"?(C=ee.connectingText)!=null?C:zr.connecting:c==="connected"?(S=ee.connectedText)!=null?S:zr.connected:c==="error"?(_=ee.errorText)!=null?_:zr.error:zr[c]};function ye(c,g,C,S){if(S==="idle"&&C.idleLink){c.textContent="";let _=document.createElement("a");_.href=C.idleLink,_.target="_blank",_.rel="noopener noreferrer",_.textContent=g,_.style.color="inherit",_.style.textDecoration="none",c.appendChild(_)}else c.textContent=g}let{wrapper:pe,panel:le,pillRoot:Ye}=vx(n),Me=Sx(n,H()),{container:be,body:J,messagesWrapper:Ke,suggestions:ne,textarea:Y,sendButton:Q,sendButtonWrapper:Be,composerForm:ke,statusText:ge,introTitle:ue,introSubtitle:_e,closeButton:I,iconHolder:te,headerTitle:qe,headerSubtitle:tt,header:Xe,footer:Je,actionsRow:pt,leftActions:ht,rightActions:zt}=Me,or=Me.setSendButtonMode,X=Me.micButton,kt=Me.micButtonWrapper,ct=Me.attachmentButton,Jt=Me.attachmentButtonWrapper,fe=Me.attachmentInput,Se=Me.attachmentPreviewsContainer;be.classList.add("persona-relative"),J.classList.add("persona-relative");let Wt=12,sr=()=>{var c;return(c=Te.label)!=null?c:""},Et=()=>{var c;return(c=Te.iconName)!=null?c:"arrow-down"},gr=()=>Te.enabled!==!1,_t=x("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");_t.type="button",_t.style.display="none",_t.setAttribute("data-persona-scroll-to-bottom","true");let Ht=x("span","persona-flex persona-items-center"),Tt=x("span","");_t.append(Ht,Tt),be.appendChild(_t);let Lt=()=>{let g=Je.style.display==="none"?0:Je.offsetHeight;_t.style.bottom=`${g+Wt}px`};Lt();let ar=()=>{let c=!!sr();_t.setAttribute("aria-label",sr()||"Jump to latest"),_t.title=sr(),_t.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Ht.innerHTML="";let g=Pe(Et(),"14px","currentColor",2);g?(Ht.appendChild(g),Ht.style.display=""):Ht.style.display="none",Tt.textContent=sr(),Tt.style.display=c?"":"none"};ar();let mt=null,cr=null,Cr=o.find(c=>c.renderHeader);if(Cr!=null&&Cr.renderHeader){let c=Cr.renderHeader({config:n,defaultRenderer:()=>{let g=go({config:n,showClose:H()});return us(be,g,n),g.header},onClose:()=>Kt(!1,"user")});if(c){let g=be.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Xe=c)}}let Lr=()=>{var g,C,S,_;if(!j)return;if(he=!0,!Z&&j&&(Z=Vx({buffer:j,getFullHistory:()=>j.getAllFromStore(),onClose:()=>_r(),config:n,plugins:o,getThroughput:()=>{var F;return(F=Ce==null?void 0:Ce.getMetric())!=null?F:{status:"idle"}}})),Z&&(J.style.display="none",(g=Je.parentNode)==null||g.insertBefore(Z.element,Je),Z.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${en.actionIconColor}`;let F=(_=(S=(C=n.features)==null?void 0:C.eventStream)==null?void 0:S.classNames)==null?void 0:_.toggleButtonActive;F&&F.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!he)return;let F=Date.now();F-Ve>=200&&(Z==null||Z.update(),Ve=F),xe=requestAnimationFrame(c)};Ve=0,xe=requestAnimationFrame(c),oo(),s.emit("eventStream:opened",{timestamp:Date.now()})},_r=()=>{var c,g,C;if(he){if(he=!1,Z&&Z.element.remove(),J.style.display="",xt){xt.style.boxShadow="";let S=(C=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:C.toggleButtonActive;S&&S.split(/\s+/).forEach(_=>_&&xt.classList.remove(_))}xe!==null&&(cancelAnimationFrame(xe),xe=null),oo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(we){let c=(yf=(xf=n.features)==null?void 0:xf.eventStream)==null?void 0:yf.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=x("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let C=Pe("activity","18px","currentColor",1.5);C&&xt.appendChild(C);let S=Me.clearChatButtonWrapper,_=Me.closeButtonWrapper,F=S||_;F&&F.parentNode===Xe?Xe.insertBefore(xt,F):Xe.appendChild(xt),xt.addEventListener("click",()=>{he?_r():Lr()})}let an=c=>{var S,_,F;let g=n.attachments;if(!(g!=null&&g.enabled))return;let C=c.querySelector(".persona-attachment-previews");if(!C){C=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),C.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(C,U):c.insertBefore(C,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=x("input");U.type="file",U.accept=((S=g.allowedTypes)!=null?S:mo).join(","),U.multiple=((_=g.maxFiles)!=null?_:4)>1,U.style.display="none",U.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(U)}},mr=o.find(c=>c.renderComposer);if(mr!=null&&mr.renderComposer){let c=n.composer,g=mr.renderComposer({config:n,defaultRenderer:()=>Fs({config:n}).footer,onSubmit:C=>{var U;if(!R||R.isStreaming())return;let S=C.trim(),_=(U=mt==null?void 0:mt.hasAttachments())!=null?U:!1;if(!S&&!_)return;ia();let F;_&&(F=[],F.push(...mt.getContentParts()),S&&F.push(Ba(S))),R.sendMessage(S,{contentParts:F}),_&&mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{fe==null||fe.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:C=>{n.composer={...n.composer,selectedModelId:C},n.agent&&(n.agent={...n.agent,model:C})},onVoiceToggle:((bf=n.voiceRecognition)==null?void 0:bf.enabled)===!0?()=>{cr==null||cr()}:void 0});g&&(Je.replaceWith(g),Je=g)}let Un=c=>{let g=c.querySelector("[data-persona-composer-form]"),C=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),_=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&(ke=g),C&&(Y=C),S&&(Q=S),_&&(X=_,kt=_.parentElement),F&&(ge=F);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(ne=U);let V=c.querySelector(".persona-attachment-button");V&&(ct=V,Jt=V.parentElement),fe=c.querySelector('input[type="file"]'),Se=c.querySelector(".persona-attachment-previews");let $=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");$&&(pt=$)};an(Je),Un(Je);let Rr=(Af=(wf=n.layout)==null?void 0:wf.contentMaxWidth)!=null?Af:B()?(Sf=(vf=(Cf=n.launcher)==null?void 0:Cf.composerBar)==null?void 0:vf.contentMaxWidth)!=null?Sf:"720px":void 0;if(Rr&&(Ke.style.maxWidth=Rr,Ke.style.marginLeft="auto",Ke.style.marginRight="auto",Ke.style.width="100%"),Rr&&ke&&!B()&&(ke.style.maxWidth=Rr,ke.style.marginLeft="auto",ke.style.marginRight="auto"),Rr&&ne&&!B()&&(ne.style.maxWidth=Rr,ne.style.marginLeft="auto",ne.style.marginRight="auto"),Rr&&Se&&!B()&&(Se.style.maxWidth=Rr,Se.style.marginLeft="auto",Se.style.marginRight="auto"),(Tf=n.attachments)!=null&&Tf.enabled&&fe&&Se){mt=cs.fromConfig(n.attachments),mt.setPreviewsContainer(Se),fe.addEventListener("change",C=>{let S=C.target;mt==null||mt.handleFileSelect(S.files),S.value=""});let c=n.attachments.dropOverlay,g=dy(c);be.appendChild(g)}(()=>{var S,_;let c=(_=(S=n.layout)==null?void 0:S.slots)!=null?_:{},g=F=>{switch(F){case"body-top":return be.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ke;case"footer-top":return ne;case"composer":return ke;case"footer-bottom":return ge;default:return null}},C=(F,U)=>{var V;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")Xe.insertBefore(U,Xe.firstChild);else if(F==="header-right")Xe.appendChild(U);else{let $=Xe.querySelector(".persona-flex-col");$?(V=$.parentNode)==null||V.insertBefore(U,$.nextSibling):Xe.appendChild(U)}break;case"body-top":{let $=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");$?$.replaceWith(U):J.insertBefore(U,J.firstChild);break}case"body-bottom":J.appendChild(U);break;case"footer-top":ne.replaceWith(U);break;case"footer-bottom":ge.replaceWith(U);break;default:break}};for(let[F,U]of Object.entries(c))if(U)try{let V=U({config:n,defaultContent:()=>g(F)});V&&C(F,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,V)}})();let Pn=c=>{let C=c.target.closest('button[data-expand-header="true"]');if(!C)return;let S=C.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!S)return;let _=S.getAttribute("data-message-id");if(!_)return;let F=C.getAttribute("data-bubble-type");F==="reasoning"?(zs.has(_)?zs.delete(_):zs.add(_),kx(_,S)):F==="tool"&&(qs.has(_)?qs.delete(_):qs.add(_),Ex(_,S,n)),Hn.delete(_)};Ke.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))}),Ke.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))});let In=new Map;Ke.addEventListener("click",c=>{var U;let C=c.target.closest(".persona-message-action-btn[data-action]");if(!C)return;c.preventDefault(),c.stopPropagation();let S=C.closest("[data-actions-for]");if(!S)return;let _=S.getAttribute("data-actions-for");if(!_)return;let F=C.getAttribute("data-action");if(F==="copy"){let $=R.getMessages().find(De=>De.id===_);if($&&G.onCopy){let De=$.content||"";navigator.clipboard.writeText(De).then(()=>{C.classList.add("persona-message-action-success");let Ae=Pe("check",14,"currentColor",2);Ae&&(C.innerHTML="",C.appendChild(Ae)),setTimeout(()=>{C.classList.remove("persona-message-action-success");let ce=Pe("copy",14,"currentColor",2);ce&&(C.innerHTML="",C.appendChild(ce))},2e3)}).catch(Ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ae)}),G.onCopy($)}}else if(F==="upvote"||F==="downvote"){let $=((U=In.get(_))!=null?U:null)===F,De=F==="upvote"?"thumbs-up":"thumbs-down";if($){In.delete(_),C.classList.remove("persona-message-action-active");let Ae=Pe(De,14,"currentColor",2);Ae&&(C.innerHTML="",C.appendChild(Ae))}else{let Ae=F==="upvote"?"downvote":"upvote",ce=S.querySelector(`[data-action="${Ae}"]`);if(ce){ce.classList.remove("persona-message-action-active");let dt=Pe(Ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(ce.innerHTML="",ce.appendChild(dt))}In.set(_,F),C.classList.add("persona-message-action-active");let Le=Pe(De,14,"currentColor",2);Le&&(Le.setAttribute("fill","currentColor"),C.innerHTML="",C.appendChild(Le)),C.classList.remove("persona-message-action-pop"),C.offsetWidth,C.classList.add("persona-message-action-pop");let Qe=R.getMessages().find(gt=>gt.id===_);Qe&&G.onFeedback&&G.onFeedback({type:F,messageId:Qe.id,message:Qe})}}}),Ke.addEventListener("click",c=>{let C=c.target.closest("button[data-approval-action]");if(!C)return;c.preventDefault(),c.stopPropagation();let S=C.closest(".persona-approval-bubble");if(!S)return;let _=S.getAttribute("data-message-id");if(!_)return;let F=C.getAttribute("data-approval-action");if(!F)return;let U=F==="approve"?"approved":"denied",$=R.getMessages().find(Ae=>Ae.id===_);if(!($!=null&&$.approval))return;let De=S.querySelector("[data-approval-buttons]");De&&De.querySelectorAll("button").forEach(ce=>{ce.disabled=!0,ce.style.opacity="0.5",ce.style.cursor="not-allowed"}),$.approval.toolType==="webmcp"?R.resolveWebMcpApproval(_,U):R.resolveApproval($.approval,U)});let me=null,P=null,oe={artifacts:[],selectedId:null},Ee=!1,rt={current:null};Ke.addEventListener("click",c=>{var ce,Le,Ne,Qe,gt;let C=c.target.closest("[data-download-artifact]");if(!C)return;c.preventDefault(),c.stopPropagation();let S=C.getAttribute("data-download-artifact");if(!S||((Ne=(Le=(ce=n.features)==null?void 0:ce.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:Ne.call(Le,{type:"download",artifactId:S}))===!0)return;let F=R.getArtifactById(S),U=F==null?void 0:F.markdown,V=(F==null?void 0:F.title)||"artifact";if(!U){let dt=C.closest("[data-open-artifact]"),Ct=dt==null?void 0:dt.closest("[data-message-id]"),vt=Ct==null?void 0:Ct.getAttribute("data-message-id");if(vt){let Fe=R.getMessages().find(nt=>nt.id===vt);if(Fe!=null&&Fe.rawContent)try{let nt=JSON.parse(Fe.rawContent);U=(Qe=nt==null?void 0:nt.props)==null?void 0:Qe.markdown,V=((gt=nt==null?void 0:nt.props)==null?void 0:gt.title)||V}catch{}}}if(!U)return;let $=new Blob([U],{type:"text/markdown"}),De=URL.createObjectURL($),Ae=document.createElement("a");Ae.href=De,Ae.download=`${V}.md`,Ae.click(),URL.revokeObjectURL(De)}),Ke.addEventListener("click",c=>{var F,U,V;let C=c.target.closest("[data-open-artifact]");if(!C)return;let S=C.getAttribute("data-open-artifact");!S||((V=(U=(F=n.features)==null?void 0:F.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:V.call(U,{type:"open",artifactId:S}))===!0||(c.preventDefault(),c.stopPropagation(),Ee=!1,R.selectArtifact(S),ln())}),Ke.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Xt=Me.composerOverlay,$t=(c,g,C)=>{var V,$,De,Ae;let S=g.trim();if(!S||!rt.current)return;let _=(V=c.getAttribute("data-tool-call-id"))!=null?V:"",F=C.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:_,answer:S,answers:C.structured,values:($=C.values)!=null?$:C.source==="multi"?S.split(", "):[S],isFreeText:F,source:C.source},bubbles:!0,composed:!0})),_o(Xt,_);let U=rt.current.getMessages().find(ce=>{var Le;return((Le=ce.toolCall)==null?void 0:Le.id)===_});(De=U==null?void 0:U.agentMetadata)!=null&&De.awaitingLocalTool?rt.current.resolveAskUserQuestion(U,(Ae=C.structured)!=null?Ae:S):rt.current.sendMessage(S)},er=c=>{var _;let g=rt.current;if(!g)return;let C=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",S=g.getMessages().find(F=>{var U;return((U=F.toolCall)==null?void 0:U.id)===C});S&&g.persistAskUserQuestionProgress(S,{answers:zl(c,S),currentIndex:En(c)})},Pr=c=>Object.entries(c).map(([g,C])=>`${g}: ${Array.isArray(C)?C.join(", "):C}`).join(" | "),Nr=c=>{var _,F,U;if(((F=(_=n.features)==null?void 0:_.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=En(c),C=Vs(c);if(g>=C-1)return;let S=(U=rt.current)==null?void 0:U.getMessages().find(V=>{var $;return(($=V.toolCall)==null?void 0:$.id)===c.getAttribute("data-tool-call-id")});S&&(ql(c,S,n,g+1),er(c))};Xt.addEventListener("click",c=>{var F,U,V,$,De,Ae,ce,Le,Ne,Qe,gt,dt,Ct,vt;let C=c.target.closest("[data-ask-user-action]");if(!C)return;let S=C.closest("[data-persona-ask-sheet-for]");if(!S)return;let _=C.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),_==="dismiss"){let ze=(F=S.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ze},bubbles:!0,composed:!0})),_o(Xt,ze);let Fe=(U=rt.current)==null?void 0:U.getMessages().find(nt=>{var D;return((D=nt.toolCall)==null?void 0:D.id)===ze});(V=Fe==null?void 0:Fe.agentMetadata)!=null&&V.awaitingLocalTool&&(($=rt.current)==null||$.markAskUserQuestionResolved(Fe),(De=rt.current)==null||De.resolveAskUserQuestion(Fe,"(dismissed)"));return}if(_==="pick"){let ze=C.getAttribute("data-option-label");if(!ze)return;let Fe=S.getAttribute("data-multi-select")==="true",nt=Oo(S);if(nt&&Fe){let D=ms(S)[En(S)],$e=new Set(Array.isArray(D)?D:[]);$e.has(ze)?$e.delete(ze):$e.add(ze),No(S,Array.from($e)),er(S);return}if(nt){No(S,ze),er(S),Nr(S);return}if(Fe){let D=C.getAttribute("aria-pressed")==="true";C.setAttribute("aria-pressed",D?"false":"true"),C.classList.toggle("persona-ask-pill-selected",!D);let $e=S.querySelector('[data-ask-user-action="submit-multi"]');$e&&($e.disabled=cu(S).length===0);return}$t(S,ze,{source:"pick",values:[ze]});return}if(_==="submit-multi"){let ze=cu(S);if(ze.length===0)return;$t(S,ze.join(", "),{source:"multi",values:ze});return}if(_==="open-free-text"){let ze=S.querySelector('[data-ask-free-text-row="true"]');if(ze){ze.classList.remove("persona-hidden");let Fe=ze.querySelector('[data-ask-free-text-input="true"]');Fe==null||Fe.focus()}return}if(_==="focus-free-text"){let ze=S.querySelector('[data-ask-free-text-input="true"]');ze==null||ze.focus();return}if(_==="submit-free-text"){let ze=S.querySelector('[data-ask-free-text-input="true"]'),Fe=(Ae=ze==null?void 0:ze.value)!=null?Ae:"";if(!Fe.trim())return;if(Oo(S)){No(S,Fe.trim()),er(S),Nr(S);return}$t(S,Fe,{source:"free-text"});return}if(_==="next"||_==="back"){if(!rt.current)return;let ze=(ce=S.getAttribute("data-tool-call-id"))!=null?ce:"",Fe=rt.current.getMessages().find(at=>{var Re;return((Re=at.toolCall)==null?void 0:Re.id)===ze});if(!Fe)return;let nt=S.querySelector('[data-ask-free-text-input="true"]'),D=(Ne=(Le=nt==null?void 0:nt.value)==null?void 0:Le.trim())!=null?Ne:"";if(D){let at=ms(S)[En(S)];(typeof at!="string"||at!==D)&&No(S,D)}let $e=_==="next"?1:-1,Ge=En(S)+$e;ql(S,Fe,n,Ge),er(S);return}if(_==="submit-all"){if(!rt.current)return;let ze=(Qe=S.getAttribute("data-tool-call-id"))!=null?Qe:"",Fe=rt.current.getMessages().find(at=>{var Re;return((Re=at.toolCall)==null?void 0:Re.id)===ze});if(!Fe)return;let nt=S.querySelector('[data-ask-free-text-input="true"]'),D=(dt=(gt=nt==null?void 0:nt.value)==null?void 0:gt.trim())!=null?dt:"";D&&No(S,D);let $e=zl(S,Fe);rt.current.persistAskUserQuestionProgress(Fe,{answers:$e,currentIndex:En(S)});let Ge=Pr($e);$t(S,Ge||"(submitted)",{source:"submit-all",structured:$e});return}if(_==="skip"){if(!rt.current)return;let ze=(Ct=S.getAttribute("data-tool-call-id"))!=null?Ct:"",Fe=rt.current.getMessages().find(Re=>{var jt;return((jt=Re.toolCall)==null?void 0:jt.id)===ze});if(!Fe)return;let nt=Oo(S),D=En(S),$e=Vs(S),Ge=D>=$e-1;if(!nt){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ze},bubbles:!0,composed:!0})),_o(Xt,ze),(vt=Fe.agentMetadata)!=null&&vt.awaitingLocalTool&&(rt.current.markAskUserQuestionResolved(Fe),rt.current.resolveAskUserQuestion(Fe,"(dismissed)"));return}No(S,"");let at=S.querySelector('[data-ask-free-text-input="true"]');if(at&&(at.value=""),Ge){let Re=zl(S,Fe),jt=Pr(Re);$t(S,jt||"(skipped)",{source:"submit-all",structured:Re});return}ql(S,Fe,n,D+1),er(S);return}}),Xt.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let C=c.target;if(!((F=C.matches)!=null&&F.call(C,'[data-ask-free-text-input="true"]')))return;let S=C.closest("[data-persona-ask-sheet-for]");if(!S)return;c.preventDefault();let _=C.value;if(_.trim()){if(Oo(S)){No(S,_.trim()),er(S),Nr(S);return}$t(S,_,{source:"free-text"})}});let wn=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let C=Xt.querySelector("[data-persona-ask-sheet-for]");if(!C||C.getAttribute("data-ask-layout")!=="rows"||C.getAttribute("data-multi-select")==="true")return;let S=Number(c.key),F=C.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[S-1];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",wn);let Vt=null,Ft=null,Ir=null,Cn=null,wo=()=>{};function eo(){Cn==null||Cn(),Cn=null}let Co=()=>{var U;if(!Vt||!Ft)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),C=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||C){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let S=Vt.firstElementChild;if(!S||S===Ft)return;let _=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${_}px`,Ft.style.zIndex="5";let F=S.offsetWidth-_/2;Ft.style.left=`${Math.max(0,F)}px`},zn=()=>{},ln=()=>{var C,S,_,F,U;if(!me||!Ln(n))return;Vl(e,n),Gl(e,n),zn();let c=(F=(_=(S=(C=n.features)==null?void 0:C.artifacts)==null?void 0:S.layout)==null?void 0:_.narrowHostMaxWidth)!=null?F:520,g=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),me.update(oe),Ee?(me.setMobileOpen(!1),me.element.classList.add("persona-hidden"),(U=me.backdrop)==null||U.classList.add("persona-hidden")):oe.artifacts.length>0&&(me.element.classList.remove("persona-hidden"),me.setMobileOpen(!0)),wo()};if(Ln(n)){le.style.position="relative";let c=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(be),me=Jx(n,{onSelect:C=>{var S;return(S=rt.current)==null?void 0:S.selectArtifact(C)},onDismiss:()=>{Ee=!0,ln()}}),me.element.classList.add("persona-hidden"),Vt=g,g.appendChild(c),g.appendChild(me.element),me.backdrop&&le.appendChild(me.backdrop),le.appendChild(g),wo=()=>{var S,_,F,U;if(!Vt||!me)return;if(!(((F=(_=(S=n.features)==null?void 0:S.artifacts)==null?void 0:_.layout)==null?void 0:F.resizable)===!0)){Ir==null||Ir(),Ir=null,eo(),Ft&&(Ft.remove(),Ft=null),me.element.style.removeProperty("width"),me.element.style.removeProperty("maxWidth");return}if(!Ft){let V=x("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let $=e.ownerDocument,De=(U=$.defaultView)!=null?U:window,Ae=ce=>{var Ct,vt;if(!me||ce.button!==0||e.classList.contains("persona-artifact-narrow-host")||De.innerWidth<=640)return;ce.preventDefault(),eo();let Le=ce.clientX,Ne=me.element.getBoundingClientRect().width,Qe=(vt=(Ct=n.features)==null?void 0:Ct.artifacts)==null?void 0:vt.layout,gt=ze=>{let Fe=Vt.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-appearance-seamless"),D=nt?0:Zx(Vt,De),$e=nt?0:V.getBoundingClientRect().width||6,Ge=Ne-(ze.clientX-Le),at=ey(Ge,Fe,D,$e,Qe==null?void 0:Qe.resizableMinWidth,Qe==null?void 0:Qe.resizableMaxWidth);me.element.style.width=`${at}px`,me.element.style.maxWidth="none",Co()},dt=()=>{$.removeEventListener("pointermove",gt),$.removeEventListener("pointerup",dt),$.removeEventListener("pointercancel",dt),Cn=null;try{V.releasePointerCapture(ce.pointerId)}catch{}};Cn=dt,$.addEventListener("pointermove",gt),$.addEventListener("pointerup",dt),$.addEventListener("pointercancel",dt);try{V.setPointerCapture(ce.pointerId)}catch{}};V.addEventListener("pointerdown",Ae),Ft=V,Vt.insertBefore(V,me.element),Ir=()=>{V.removeEventListener("pointerdown",Ae)}}if(Ft){let V=oe.artifacts.length>0&&!Ee;Ft.classList.toggle("persona-hidden",!V),Co()}},zn=()=>{var De,Ae,ce,Le,Ne,Qe,gt,dt,Ct,vt,ze,Fe,nt,D;if(!T||!me||((Ae=(De=n.launcher)==null?void 0:De.sidebarMode)!=null?Ae:!1)||Tr(n)&&kn(n).reveal==="emerge")return;let S=(ce=e.ownerDocument.defaultView)!=null?ce:window,_=(Ne=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?Ne:!0,F=(gt=(Qe=n.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?gt:640;if(_&&S.innerWidth<=F||!Qx(n,T))return;let U=(vt=(Ct=(dt=n.launcher)==null?void 0:dt.width)!=null?Ct:n.launcherWidth)!=null?vt:yn,V=(D=(nt=(Fe=(ze=n.features)==null?void 0:ze.artifacts)==null?void 0:Fe.layout)==null?void 0:nt.expandedPanelWidth)!=null?D:"min(720px, calc(100vw - 24px))";oe.artifacts.length>0&&!Ee?(le.style.width=V,le.style.maxWidth=V):(le.style.width=U,le.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(P=new ResizeObserver(()=>{ln()}),P.observe(le))}else le.appendChild(be),B()&&Ye&&(Me.peekBanner&&Ye.appendChild(Me.peekBanner),Ye.appendChild(Je));e.appendChild(pe),Ye&&e.appendChild(Ye);let Rn=()=>{var at,Re,jt,bt,br,Hr,Gt,Vr,Br,ft,St,Gr,Fr,Vo,Go,Ko,Ms,ks,pr,Jo,Po,Bt,rn,io,Kr,nn,Yt,lr;if(B()){le.style.width="100%",le.style.maxWidth="100%";let Qt=(Re=(at=n.launcher)==null?void 0:at.composerBar)!=null?Re:{},ur=pe.dataset.state==="expanded",on=(jt=Qt.expandedSize)!=null?jt:"anchored";if(!(ur&&on!=="fullscreen")){be.style.background="",be.style.border="",be.style.borderRadius="",be.style.overflow="",be.style.boxShadow="";return}let Ar=(br=(bt=n.theme)==null?void 0:bt.components)==null?void 0:br.panel,Vn=Ns(n),lo=(Xo,Ti)=>{var ga;return Xo==null||Xo===""?Ti:(ga=Os(Vn,Xo))!=null?ga:Xo},vi="1px solid var(--persona-border)",Si="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ai="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";be.style.background="var(--persona-surface, #ffffff)",be.style.border=lo(Ar==null?void 0:Ar.border,vi),be.style.borderRadius=lo(Ar==null?void 0:Ar.borderRadius,Ai),be.style.boxShadow=lo(Ar==null?void 0:Ar.shadow,Si),be.style.overflow="hidden";return}let c=Tr(n),g=(Gt=(Hr=n.launcher)==null?void 0:Hr.sidebarMode)!=null?Gt:!1,C=c||g||((Br=(Vr=n.launcher)==null?void 0:Vr.fullHeight)!=null?Br:!1),S=((ft=n.launcher)==null?void 0:ft.enabled)===!1,_=(Gr=(St=n.theme)==null?void 0:St.components)==null?void 0:Gr.panel,F=Ns(n),U=(Qt,ur)=>{var on;return Qt==null||Qt===""?ur:(on=Os(F,Qt))!=null?on:Qt},V=(Fr=e.ownerDocument.defaultView)!=null?Fr:window,$=(Go=(Vo=n.launcher)==null?void 0:Vo.mobileFullscreen)!=null?Go:!0,De=(Ms=(Ko=n.launcher)==null?void 0:Ko.mobileBreakpoint)!=null?Ms:640,Ae=V.innerWidth<=De,ce=$&&Ae&&T,Le=(pr=(ks=n.launcher)==null?void 0:ks.position)!=null?pr:"bottom-left",Ne=Le==="bottom-left"||Le==="top-left",Qe=(Po=(Jo=n.launcher)==null?void 0:Jo.zIndex)!=null?Po:qr,gt=g||ce?"none":"1px solid var(--persona-border)",dt=ce?"none":g?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ce&&(dt="none",gt="none");let Ct=g||ce?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=U(_==null?void 0:_.border,gt),ze=U(_==null?void 0:_.shadow,dt),Fe=U(_==null?void 0:_.borderRadius,Ct),nt=J.scrollTop;e.style.cssText="",pe.style.cssText="",le.style.cssText="",be.style.cssText="",J.style.cssText="",Je.style.cssText="";let D=()=>{var ur;if(nt<=0)return;((ur=J.ownerDocument.defaultView)!=null?ur:window).requestAnimationFrame(()=>{if(J.scrollTop===nt)return;let on=J.scrollHeight-J.clientHeight;on<=0||(J.scrollTop=Math.min(nt,on))})};if(ce){pe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),pe.style.cssText=`
80
+ `,M.addEventListener("click",()=>{m=h,T.forEach((W,R)=>{let B=R<h;W.classList.toggle("selected",B),W.setAttribute("aria-checked",R===h-1?"true":"false")})}),T.push(M),E.appendChild(M)}u.appendChild(E);let S=null;if(d){let h=document.createElement("div");h.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),h.appendChild(S),u.appendChild(h)}let k=document.createElement("div");k.className="persona-feedback-actions";let x=document.createElement("button");x.type="button",x.className="persona-feedback-btn persona-feedback-btn-skip",x.textContent=i,x.addEventListener("click",()=>{r==null||r(),p.remove()});let b=document.createElement("button");return b.type="button",b.className="persona-feedback-btn persona-feedback-btn-submit",b.textContent=a,b.addEventListener("click",async()=>{if(m===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}b.disabled=!0,b.textContent="Submitting...";try{let h=(S==null?void 0:S.value.trim())||void 0;await e(m,h),p.remove()}catch(h){b.disabled=!1,b.textContent=a,console.error("[CSAT Feedback] Failed to submit:",h)}}),k.appendChild(x),k.appendChild(b),u.appendChild(k),p.appendChild(u),p}function Ql(t){let{onSubmit:e,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,y.appendChild(A);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,y.appendChild(E),f.appendChild(y);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=p,S.appendChild(k),S.appendChild(x);let b=document.createElement("div");b.className="persona-feedback-numbers";let h=[];for(let _=0;_<=10;_++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${_} out of 10`),V.textContent=String(_),V.dataset.rating=String(_),_<=6?V.classList.add("persona-feedback-detractor"):_<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{u=_,h.forEach((oe,be)=>{oe.classList.toggle("selected",be===_),oe.setAttribute("aria-checked",be===_?"true":"false")})}),h.push(V),b.appendChild(V)}T.appendChild(S),T.appendChild(b),f.appendChild(T);let M=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),_.appendChild(M),f.appendChild(_)}let W=document.createElement("div");W.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=i,R.addEventListener("click",()=>{r==null||r(),m.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(u===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let _=(M==null?void 0:M.value.trim())||void 0;await e(u,_),m.remove()}catch(_){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),W.appendChild(R),W.appendChild(B),f.appendChild(W),m.appendChild(f),m}var Ga="persona-chat-history",sC=30*1e3,iC={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function lC(t){var n,o,s;if(!t)return[];let e=[],r=Array.from((n=t.items)!=null?n:[]);for(let a of r){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=iC[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function Yl(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function dC(t){var e,r,n,o,s,a,i,d,l;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(r=t.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(n=t.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=t.clearOnChatClear)!=null?l:!0}:null}function cC(t){try{let e=t==="local"?localStorage:sessionStorage,r="__persist_test__";return e.setItem(r,"1"),e.removeItem(r),e}catch{return null}}var cu=t=>!t||typeof t!="object"?{}:{...t},Qx=t=>t.map(e=>({...e,streaming:!1})),Yx=(t,e,r)=>{let n=t!=null&&t.markdown?ra(t.markdown):null,o=ka(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&r&&r())}let d;return t!=null&&t.postprocessMessage?d=t.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):n?d=n(a):d=na(a),o?o(d):d}};function Zx(t){var i,d,l,p;let e=v("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let r=(i=t==null?void 0:t.iconName)!=null?i:"upload",n=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(l=t==null?void 0:t.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=t==null?void 0:t.iconStrokeWidth)!=null?p:.5,a=Ie(r,n,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let m=v("span","persona-drop-overlay-label");m.textContent=t.label,e.appendChild(m)}return e}var Zl=(t,e,r)=>{var Wu,Bu,Hu,Du,Ou,_u,Nu,Fu,$u,Uu,zu,qu,Vu,ju,Gu,Ku,Xu,Ju,Qu,Yu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,wf,vf,Cf,Af,Sf,Tf,Mf,kf;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let n=hl(e),o=Qs.getForInstance(n.plugins);n.components&&yo.registerAll(n.components);let s=jx(),i=n.persistState===!1?null:(Wu=n.storageAdapter)!=null?Wu:Vl(),d={},l=null,p=!1,m=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:w,open:C}=g;return C&&(p=!0),w}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let w=g!=null?g:{messages:[],metadata:{}};return m(w)});else{let g=c!=null?c:{messages:[],metadata:{}},w=m(g);w.metadata&&(d=cu(w.metadata)),(Bu=w.messages)!=null&&Bu.length&&(n={...n,initialMessages:w.messages}),(Hu=w.artifacts)!=null&&Hu.length&&(n={...n,initialArtifacts:w.artifacts,initialSelectedArtifactId:(Du=w.selectedArtifactId)!=null?Du:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=m({messages:[],metadata:{}});(Ou=c.messages)!=null&&Ou.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let u=()=>d,f=c=>{var w;d=(w=c({...d}))!=null?w:{},xa()},y=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ys],A=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ga.message,ga.messageAndClick],E=Zs({parsers:y,handlers:A,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let T=(Nu=(_u=n.launcher)==null?void 0:_u.enabled)!=null?Nu:!0,S=($u=(Fu=n.launcher)==null?void 0:Fu.autoExpand)!=null?$u:!1,k=(Uu=n.autoFocusInput)!=null?Uu:!1,x=S,b=T,h=(qu=(zu=n.layout)==null?void 0:zu.header)==null?void 0:qu.layout,M=!1,W=()=>Bo(n),R=()=>T||W(),B=W()?!1:T?S:!0,_=!1,V=null,oe=()=>{_=!0,V&&clearTimeout(V),V=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},be=Yx(n,E,oe),Qe=(ju=(Vu=n.features)==null?void 0:Vu.showReasoning)!=null?ju:!0,je=(Ku=(Gu=n.features)==null?void 0:Gu.showToolCalls)!=null?Ku:!0,ve=(Ju=(Xu=n.features)==null?void 0:Xu.showEventStreamToggle)!=null?Ju:!1,Ee=(Yu=(Qu=n.features)==null?void 0:Qu.scrollToBottom)!=null?Yu:{},_e=`${(ef=typeof n.persistState=="object"?(Zu=n.persistState)==null?void 0:Zu.keyPrefix:void 0)!=null?ef:"persona-"}event-stream`,X=ve?new Xs(_e):null,Ue=(nf=(rf=(tf=n.features)==null?void 0:tf.eventStream)==null?void 0:rf.maxEvents)!=null?nf:2e3,K=ve?new Ks(Ue,X):null,Te=ve?new Js:null,ae=null,xe=!1,Me=null,Ke=0;X==null||X.open().then(()=>K==null?void 0:K.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ce={onCopy:c=>{var g,w;s.emit("message:copy",c),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(c.id,"copy").catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(w=(g=n.messageActions)==null?void 0:g.onCopy)==null||w.call(g,c)},onFeedback:c=>{var g,w;s.emit("message:feedback",c),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(c.messageId,c.type).catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(w=(g=n.messageActions)==null?void 0:g.onFeedback)==null||w.call(g,c)}},re=(of=n.statusIndicator)!=null?of:{},le=c=>{var g,w,C,D;return c==="idle"?(g=re.idleText)!=null?g:Ur.idle:c==="connecting"?(w=re.connectingText)!=null?w:Ur.connecting:c==="connected"?(C=re.connectedText)!=null?C:Ur.connected:c==="error"?(D=re.errorText)!=null?D:Ur.error:Ur[c]};function ut(c,g,w,C){if(C==="idle"&&w.idleLink){c.textContent="";let D=document.createElement("a");D.href=w.idleLink,D.target="_blank",D.rel="noopener noreferrer",D.textContent=g,D.style.color="inherit",D.style.textDecoration="none",c.appendChild(D)}else c.textContent=g}let{wrapper:Ce,panel:he,pillRoot:tt}=ux(n),Ne=fx(n,R()),{container:me,body:J,messagesWrapper:qe,suggestions:Z,textarea:ge,sendButton:q,sendButtonWrapper:Re,composerForm:Ae,statusText:fe,introTitle:pe,introSubtitle:Be,closeButton:Q,iconHolder:N,headerTitle:ke,headerSubtitle:He,header:Ve,footer:Xe,actionsRow:gt,leftActions:ot,rightActions:Mt}=Ne,Xt=Ne.setSendButtonMode,G=Ne.micButton,Jt=Ne.micButtonWrapper,at=Ne.attachmentButton,Nt=Ne.attachmentButtonWrapper,de=Ne.attachmentInput,ye=Ne.attachmentPreviewsContainer;me.classList.add("persona-relative"),J.classList.add("persona-relative");let Rt=12,ar=()=>{var c;return(c=Ee.label)!=null?c:""},kt=()=>{var c;return(c=Ee.iconName)!=null?c:"arrow-down"},mr=()=>Ee.enabled!==!1,Ot=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let Wt=v("span","persona-flex persona-items-center"),St=v("span","");Ot.append(Wt,St),me.appendChild(Ot);let Et=()=>{let g=Xe.style.display==="none"?0:Xe.offsetHeight;Ot.style.bottom=`${g+Rt}px`};Et();let sr=()=>{let c=!!ar();Ot.setAttribute("aria-label",ar()||"Jump to latest"),Ot.title=ar(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Wt.innerHTML="";let g=Ie(kt(),"14px","currentColor",2);g?(Wt.appendChild(g),Wt.style.display=""):Wt.style.display="none",St.textContent=ar(),St.style.display=c?"":"none"};sr();let ft=null,dr=null,wr=o.find(c=>c.renderHeader);if(wr!=null&&wr.renderHeader){let c=wr.renderHeader({config:n,defaultRenderer:()=>{let g=go({config:n,showClose:R()});return pa(me,g,n),g.header},onClose:()=>Kt(!1,"user")});if(c){let g=me.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ve=c)}}let Lr=()=>{var g,w,C,D;if(!K)return;if(xe=!0,!ae&&K&&(ae=Dx({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Or(),config:n,plugins:o,getThroughput:()=>{var $;return($=Te==null?void 0:Te.getMetric())!=null?$:{status:"idle"}}})),ae&&(J.style.display="none",(g=Xe.parentNode)==null||g.insertBefore(ae.element,Xe),ae.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${en.actionIconColor}`;let $=(D=(C=(w=n.features)==null?void 0:w.eventStream)==null?void 0:C.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!xe)return;let $=Date.now();$-Ke>=200&&(ae==null||ae.update(),Ke=$),Me=requestAnimationFrame(c)};Ke=0,Me=requestAnimationFrame(c),oo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Or=()=>{var c,g,w;if(xe){if(xe=!1,ae&&ae.element.remove(),J.style.display="",xt){xt.style.boxShadow="";let C=(w=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:w.toggleButtonActive;C&&C.split(/\s+/).forEach(D=>D&&xt.classList.remove(D))}Me!==null&&(cancelAnimationFrame(Me),Me=null),oo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(ve){let c=(sf=(af=n.features)==null?void 0:af.eventStream)==null?void 0:sf.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=v("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let w=Ie("activity","18px","currentColor",1.5);w&&xt.appendChild(w);let C=Ne.clearChatButtonWrapper,D=Ne.closeButtonWrapper,$=C||D;$&&$.parentNode===Ve?Ve.insertBefore(xt,$):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}let sn=c=>{var C,D,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let w=c.querySelector(".persona-attachment-previews");if(!w){w=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),w.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(w,U):c.insertBefore(w,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=v("input");U.type="file",U.accept=((C=g.allowedTypes)!=null?C:mo).join(","),U.multiple=((D=g.maxFiles)!=null?D:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},fr=o.find(c=>c.renderComposer);if(fr!=null&&fr.renderComposer){let c=n.composer,g=fr.renderComposer({config:n,defaultRenderer:()=>_a({config:n}).footer,onSubmit:w=>{var U;if(!I||I.isStreaming())return;let C=w.trim(),D=(U=ft==null?void 0:ft.hasAttachments())!=null?U:!1;if(!C&&!D)return;os();let $;D&&($=[],$.push(...ft.getContentParts()),C&&$.push(Rs(C))),I.sendMessage(C,{contentParts:$}),D&&ft.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{de==null||de.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:w=>{n.composer={...n.composer,selectedModelId:w},n.agent&&(n.agent={...n.agent,model:w})},onVoiceToggle:((lf=n.voiceRecognition)==null?void 0:lf.enabled)===!0?()=>{dr==null||dr()}:void 0});g&&(Xe.replaceWith(g),Xe=g)}let Un=c=>{let g=c.querySelector("[data-persona-composer-form]"),w=c.querySelector("[data-persona-composer-input]"),C=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ae=g),w&&(ge=w),C&&(q=C),D&&(G=D,Jt=D.parentElement),$&&(fe=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Z=U);let j=c.querySelector(".persona-attachment-button");j&&(at=j,Nt=j.parentElement),de=c.querySelector('input[type="file"]'),ye=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(gt=F)};sn(Xe),Un(Xe);let Rr=(ff=(df=n.layout)==null?void 0:df.contentMaxWidth)!=null?ff:W()?(uf=(pf=(cf=n.launcher)==null?void 0:cf.composerBar)==null?void 0:pf.contentMaxWidth)!=null?uf:"720px":void 0;if(Rr&&(qe.style.maxWidth=Rr,qe.style.marginLeft="auto",qe.style.marginRight="auto",qe.style.width="100%"),Rr&&Ae&&!W()&&(Ae.style.maxWidth=Rr,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Rr&&Z&&!W()&&(Z.style.maxWidth=Rr,Z.style.marginLeft="auto",Z.style.marginRight="auto"),Rr&&ye&&!W()&&(ye.style.maxWidth=Rr,ye.style.marginLeft="auto",ye.style.marginRight="auto"),(mf=n.attachments)!=null&&mf.enabled&&de&&ye){ft=da.fromConfig(n.attachments),ft.setPreviewsContainer(ye),de.addEventListener("change",w=>{let C=w.target;ft==null||ft.handleFileSelect(C.files),C.value=""});let c=n.attachments.dropOverlay,g=Zx(c);me.appendChild(g)}(()=>{var C,D;let c=(D=(C=n.layout)==null?void 0:C.slots)!=null?D:{},g=$=>{switch($){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return qe;case"footer-top":return Z;case"composer":return Ae;case"footer-bottom":return fe;default:return null}},w=($,U)=>{var j;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ve.insertBefore(U,Ve.firstChild);else if($==="header-right")Ve.appendChild(U);else{let F=Ve.querySelector(".persona-flex-col");F?(j=F.parentNode)==null||j.insertBefore(U,F.nextSibling):Ve.appendChild(U)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(U):J.insertBefore(U,J.firstChild);break}case"body-bottom":J.appendChild(U);break;case"footer-top":Z.replaceWith(U);break;case"footer-bottom":fe.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let j=U({config:n,defaultContent:()=>g($)});j&&w($,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,j)}})();let Pn=c=>{let w=c.target.closest('button[data-expand-header="true"]');if(!w)return;let C=w.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=w.getAttribute("data-bubble-type");$==="reasoning"?(Fa.has(D)?Fa.delete(D):Fa.add(D),xx(D,C)):$==="tool"&&($a.has(D)?$a.delete(D):$a.add(D),yx(D,C,n)),Bn.delete(D)};qe.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))}),qe.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))});let In=new Map;qe.addEventListener("click",c=>{var U;let w=c.target.closest(".persona-message-action-btn[data-action]");if(!w)return;c.preventDefault(),c.stopPropagation();let C=w.closest("[data-actions-for]");if(!C)return;let D=C.getAttribute("data-actions-for");if(!D)return;let $=w.getAttribute("data-action");if($==="copy"){let F=I.getMessages().find(We=>We.id===D);if(F&&ce.onCopy){let We=F.content||"";navigator.clipboard.writeText(We).then(()=>{w.classList.add("persona-message-action-success");let we=Ie("check",14,"currentColor",2);we&&(w.innerHTML="",w.appendChild(we)),setTimeout(()=>{w.classList.remove("persona-message-action-success");let ie=Ie("copy",14,"currentColor",2);ie&&(w.innerHTML="",w.appendChild(ie))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),ce.onCopy(F)}}else if($==="upvote"||$==="downvote"){let F=((U=In.get(D))!=null?U:null)===$,We=$==="upvote"?"thumbs-up":"thumbs-down";if(F){In.delete(D),w.classList.remove("persona-message-action-active");let we=Ie(We,14,"currentColor",2);we&&(w.innerHTML="",w.appendChild(we))}else{let we=$==="upvote"?"downvote":"upvote",ie=C.querySelector(`[data-action="${we}"]`);if(ie){ie.classList.remove("persona-message-action-active");let dt=Ie(we==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(ie.innerHTML="",ie.appendChild(dt))}In.set(D,$),w.classList.add("persona-message-action-active");let Le=Ie(We,14,"currentColor",2);Le&&(Le.setAttribute("fill","currentColor"),w.innerHTML="",w.appendChild(Le)),w.classList.remove("persona-message-action-pop"),w.offsetWidth,w.classList.add("persona-message-action-pop");let Ye=I.getMessages().find(ht=>ht.id===D);Ye&&ce.onFeedback&&ce.onFeedback({type:$,messageId:Ye.id,message:Ye})}}}),qe.addEventListener("click",c=>{let w=c.target.closest("button[data-approval-action]");if(!w)return;c.preventDefault(),c.stopPropagation();let C=w.closest(".persona-approval-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=w.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",F=I.getMessages().find(we=>we.id===D);if(!(F!=null&&F.approval))return;let We=C.querySelector("[data-approval-buttons]");We&&We.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?I.resolveWebMcpApproval(D,U):I.resolveApproval(F.approval,U)});let ue=null,P=null,ee={artifacts:[],selectedId:null},Se=!1,rt={current:null};qe.addEventListener("click",c=>{var ie,Le,De,Ye,ht;let w=c.target.closest("[data-download-artifact]");if(!w)return;c.preventDefault(),c.stopPropagation();let C=w.getAttribute("data-download-artifact");if(!C||((De=(Le=(ie=n.features)==null?void 0:ie.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:De.call(Le,{type:"download",artifactId:C}))===!0)return;let $=I.getArtifactById(C),U=$==null?void 0:$.markdown,j=($==null?void 0:$.title)||"artifact";if(!U){let dt=w.closest("[data-open-artifact]"),wt=dt==null?void 0:dt.closest("[data-message-id]"),vt=wt==null?void 0:wt.getAttribute("data-message-id");if(vt){let $e=I.getMessages().find(nt=>nt.id===vt);if($e!=null&&$e.rawContent)try{let nt=JSON.parse($e.rawContent);U=(Ye=nt==null?void 0:nt.props)==null?void 0:Ye.markdown,j=((ht=nt==null?void 0:nt.props)==null?void 0:ht.title)||j}catch{}}}if(!U)return;let F=new Blob([U],{type:"text/markdown"}),We=URL.createObjectURL(F),we=document.createElement("a");we.href=We,we.download=`${j}.md`,we.click(),URL.revokeObjectURL(We)}),qe.addEventListener("click",c=>{var $,U,j;let w=c.target.closest("[data-open-artifact]");if(!w)return;let C=w.getAttribute("data-open-artifact");!C||((j=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:j.call(U,{type:"open",artifactId:C}))===!0||(c.preventDefault(),c.stopPropagation(),Se=!1,I.selectArtifact(C),ln())}),qe.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Qt=Ne.composerOverlay,Ft=(c,g,w)=>{var j,F,We,we;let C=g.trim();if(!C||!rt.current)return;let D=(j=c.getAttribute("data-tool-call-id"))!=null?j:"",$=w.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:C,answers:w.structured,values:(F=w.values)!=null?F:w.source==="multi"?C.split(", "):[C],isFreeText:$,source:w.source},bubbles:!0,composed:!0})),_o(Qt,D);let U=rt.current.getMessages().find(ie=>{var Le;return((Le=ie.toolCall)==null?void 0:Le.id)===D});(We=U==null?void 0:U.agentMetadata)!=null&&We.awaitingLocalTool?rt.current.resolveAskUserQuestion(U,(we=w.structured)!=null?we:C):rt.current.sendMessage(C)},tr=c=>{var D;let g=rt.current;if(!g)return;let w=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",C=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===w});C&&g.persistAskUserQuestionProgress(C,{answers:Fl(c,C),currentIndex:En(c)})},Pr=c=>Object.entries(c).map(([g,w])=>`${g}: ${Array.isArray(w)?w.join(", "):w}`).join(" | "),_r=c=>{var D,$,U;if((($=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=En(c),w=za(c);if(g>=w-1)return;let C=(U=rt.current)==null?void 0:U.getMessages().find(j=>{var F;return((F=j.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});C&&($l(c,C,n,g+1),tr(c))};Qt.addEventListener("click",c=>{var $,U,j,F,We,we,ie,Le,De,Ye,ht,dt,wt,vt;let w=c.target.closest("[data-ask-user-action]");if(!w)return;let C=w.closest("[data-persona-ask-sheet-for]");if(!C)return;let D=w.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let ze=($=C.getAttribute("data-tool-call-id"))!=null?$:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ze},bubbles:!0,composed:!0})),_o(Qt,ze);let $e=(U=rt.current)==null?void 0:U.getMessages().find(nt=>{var H;return((H=nt.toolCall)==null?void 0:H.id)===ze});(j=$e==null?void 0:$e.agentMetadata)!=null&&j.awaitingLocalTool&&((F=rt.current)==null||F.markAskUserQuestionResolved($e),(We=rt.current)==null||We.resolveAskUserQuestion($e,"(dismissed)"));return}if(D==="pick"){let ze=w.getAttribute("data-option-label");if(!ze)return;let $e=C.getAttribute("data-multi-select")==="true",nt=Oo(C);if(nt&&$e){let H=fa(C)[En(C)],Oe=new Set(Array.isArray(H)?H:[]);Oe.has(ze)?Oe.delete(ze):Oe.add(ze),No(C,Array.from(Oe)),tr(C);return}if(nt){No(C,ze),tr(C),_r(C);return}if($e){let H=w.getAttribute("aria-pressed")==="true";w.setAttribute("aria-pressed",H?"false":"true"),w.classList.toggle("persona-ask-pill-selected",!H);let Oe=C.querySelector('[data-ask-user-action="submit-multi"]');Oe&&(Oe.disabled=ru(C).length===0);return}Ft(C,ze,{source:"pick",values:[ze]});return}if(D==="submit-multi"){let ze=ru(C);if(ze.length===0)return;Ft(C,ze.join(", "),{source:"multi",values:ze});return}if(D==="open-free-text"){let ze=C.querySelector('[data-ask-free-text-row="true"]');if(ze){ze.classList.remove("persona-hidden");let $e=ze.querySelector('[data-ask-free-text-input="true"]');$e==null||$e.focus()}return}if(D==="focus-free-text"){let ze=C.querySelector('[data-ask-free-text-input="true"]');ze==null||ze.focus();return}if(D==="submit-free-text"){let ze=C.querySelector('[data-ask-free-text-input="true"]'),$e=(we=ze==null?void 0:ze.value)!=null?we:"";if(!$e.trim())return;if(Oo(C)){No(C,$e.trim()),tr(C),_r(C);return}Ft(C,$e,{source:"free-text"});return}if(D==="next"||D==="back"){if(!rt.current)return;let ze=(ie=C.getAttribute("data-tool-call-id"))!=null?ie:"",$e=rt.current.getMessages().find(it=>{var Pe;return((Pe=it.toolCall)==null?void 0:Pe.id)===ze});if(!$e)return;let nt=C.querySelector('[data-ask-free-text-input="true"]'),H=(De=(Le=nt==null?void 0:nt.value)==null?void 0:Le.trim())!=null?De:"";if(H){let it=fa(C)[En(C)];(typeof it!="string"||it!==H)&&No(C,H)}let Oe=D==="next"?1:-1,Je=En(C)+Oe;$l(C,$e,n,Je),tr(C);return}if(D==="submit-all"){if(!rt.current)return;let ze=(Ye=C.getAttribute("data-tool-call-id"))!=null?Ye:"",$e=rt.current.getMessages().find(it=>{var Pe;return((Pe=it.toolCall)==null?void 0:Pe.id)===ze});if(!$e)return;let nt=C.querySelector('[data-ask-free-text-input="true"]'),H=(dt=(ht=nt==null?void 0:nt.value)==null?void 0:ht.trim())!=null?dt:"";H&&No(C,H);let Oe=Fl(C,$e);rt.current.persistAskUserQuestionProgress($e,{answers:Oe,currentIndex:En(C)});let Je=Pr(Oe);Ft(C,Je||"(submitted)",{source:"submit-all",structured:Oe});return}if(D==="skip"){if(!rt.current)return;let ze=(wt=C.getAttribute("data-tool-call-id"))!=null?wt:"",$e=rt.current.getMessages().find(Pe=>{var qt;return((qt=Pe.toolCall)==null?void 0:qt.id)===ze});if(!$e)return;let nt=Oo(C),H=En(C),Oe=za(C),Je=H>=Oe-1;if(!nt){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ze},bubbles:!0,composed:!0})),_o(Qt,ze),(vt=$e.agentMetadata)!=null&&vt.awaitingLocalTool&&(rt.current.markAskUserQuestionResolved($e),rt.current.resolveAskUserQuestion($e,"(dismissed)"));return}No(C,"");let it=C.querySelector('[data-ask-free-text-input="true"]');if(it&&(it.value=""),Je){let Pe=Fl(C,$e),qt=Pr(Pe);Ft(C,qt||"(skipped)",{source:"submit-all",structured:Pe});return}$l(C,$e,n,H+1),tr(C);return}}),Qt.addEventListener("keydown",c=>{var $;if(c.key!=="Enter")return;let w=c.target;if(!(($=w.matches)!=null&&$.call(w,'[data-ask-free-text-input="true"]')))return;let C=w.closest("[data-persona-ask-sheet-for]");if(!C)return;c.preventDefault();let D=w.value;if(D.trim()){if(Oo(C)){No(C,D.trim()),tr(C),_r(C);return}Ft(C,D,{source:"free-text"})}});let wn=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let w=Qt.querySelector("[data-persona-ask-sheet-for]");if(!w||w.getAttribute("data-ask-layout")!=="rows"||w.getAttribute("data-multi-select")==="true")return;let C=Number(c.key),$=w.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[C-1];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",wn);let Vt=null,$t=null,Ir=null,vn=null,bo=()=>{};function eo(){vn==null||vn(),vn=null}let wo=()=>{var U;if(!Vt||!$t)return;let c=t.classList.contains("persona-artifact-appearance-seamless"),w=((U=t.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||t.classList.contains("persona-artifact-narrow-host")||w){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let C=Vt.firstElementChild;if(!C||C===$t)return;let D=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${D}px`,$t.style.zIndex="5";let $=C.offsetWidth-D/2;$t.style.left=`${Math.max(0,$)}px`},zn=()=>{},ln=()=>{var w,C,D,$,U;if(!ue||!Ln(n))return;zl(t,n),ql(t,n),zn();let c=($=(D=(C=(w=n.features)==null?void 0:w.artifacts)==null?void 0:C.layout)==null?void 0:D.narrowHostMaxWidth)!=null?$:520,g=he.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),ue.update(ee),Se?(ue.setMobileOpen(!1),ue.element.classList.add("persona-hidden"),(U=ue.backdrop)==null||U.classList.add("persona-hidden")):ee.artifacts.length>0&&(ue.element.classList.remove("persona-hidden"),ue.setMobileOpen(!0)),bo()};if(Ln(n)){he.style.position="relative";let c=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(me),ue=Nx(n,{onSelect:w=>{var C;return(C=rt.current)==null?void 0:C.selectArtifact(w)},onDismiss:()=>{Se=!0,ln()}}),ue.element.classList.add("persona-hidden"),Vt=g,g.appendChild(c),g.appendChild(ue.element),ue.backdrop&&he.appendChild(ue.backdrop),he.appendChild(g),bo=()=>{var C,D,$,U;if(!Vt||!ue)return;if(!((($=(D=(C=n.features)==null?void 0:C.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue.element.style.removeProperty("width"),ue.element.style.removeProperty("maxWidth");return}if(!$t){let j=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let F=t.ownerDocument,We=(U=F.defaultView)!=null?U:window,we=ie=>{var wt,vt;if(!ue||ie.button!==0||t.classList.contains("persona-artifact-narrow-host")||We.innerWidth<=640)return;ie.preventDefault(),eo();let Le=ie.clientX,De=ue.element.getBoundingClientRect().width,Ye=(vt=(wt=n.features)==null?void 0:wt.artifacts)==null?void 0:vt.layout,ht=ze=>{let $e=Vt.getBoundingClientRect().width,nt=t.classList.contains("persona-artifact-appearance-seamless"),H=nt?0:zx(Vt,We),Oe=nt?0:j.getBoundingClientRect().width||6,Je=De-(ze.clientX-Le),it=qx(Je,$e,H,Oe,Ye==null?void 0:Ye.resizableMinWidth,Ye==null?void 0:Ye.resizableMaxWidth);ue.element.style.width=`${it}px`,ue.element.style.maxWidth="none",wo()},dt=()=>{F.removeEventListener("pointermove",ht),F.removeEventListener("pointerup",dt),F.removeEventListener("pointercancel",dt),vn=null;try{j.releasePointerCapture(ie.pointerId)}catch{}};vn=dt,F.addEventListener("pointermove",ht),F.addEventListener("pointerup",dt),F.addEventListener("pointercancel",dt);try{j.setPointerCapture(ie.pointerId)}catch{}};j.addEventListener("pointerdown",we),$t=j,Vt.insertBefore(j,ue.element),Ir=()=>{j.removeEventListener("pointerdown",we)}}if($t){let j=ee.artifacts.length>0&&!Se;$t.classList.toggle("persona-hidden",!j),wo()}},zn=()=>{var We,we,ie,Le,De,Ye,ht,dt,wt,vt,ze,$e,nt,H;if(!T||!ue||((we=(We=n.launcher)==null?void 0:We.sidebarMode)!=null?we:!1)||Ar(n)&&kn(n).reveal==="emerge")return;let C=(ie=t.ownerDocument.defaultView)!=null?ie:window,D=(De=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?De:!0,$=(ht=(Ye=n.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?ht:640;if(D&&C.innerWidth<=$||!Ux(n,T))return;let U=(vt=(wt=(dt=n.launcher)==null?void 0:dt.width)!=null?wt:n.launcherWidth)!=null?vt:yn,j=(H=(nt=($e=(ze=n.features)==null?void 0:ze.artifacts)==null?void 0:$e.layout)==null?void 0:nt.expandedPanelWidth)!=null?H:"min(720px, calc(100vw - 24px))";ee.artifacts.length>0&&!Se?(he.style.width=j,he.style.maxWidth=j):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(P=new ResizeObserver(()=>{ln()}),P.observe(he))}else he.appendChild(me),W()&&tt&&(Ne.peekBanner&&tt.appendChild(Ne.peekBanner),tt.appendChild(Xe));t.appendChild(Ce),tt&&t.appendChild(tt);let Rn=()=>{var it,Pe,qt,bt,yr,Wr,Gt,jr,Br,pt,Ct,Gr,Fr,Vo,jo,Go,Aa,Sa,cr,Ko,Po,Bt,rn,io,Kr,nn,Yt,ir;if(W()){he.style.width="100%",he.style.maxWidth="100%";let Zt=(Pe=(it=n.launcher)==null?void 0:it.composerBar)!=null?Pe:{},pr=Ce.dataset.state==="expanded",on=(qt=Zt.expandedSize)!=null?qt:"anchored";if(!(pr&&on!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let Cr=(yr=(bt=n.theme)==null?void 0:bt.components)==null?void 0:yr.panel,jn=Da(n),lo=(Xo,Ci)=>{var us;return Xo==null||Xo===""?Ci:(us=Ba(jn,Xo))!=null?us:Xo},bi="1px solid var(--persona-border)",wi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",vi="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=lo(Cr==null?void 0:Cr.border,bi),me.style.borderRadius=lo(Cr==null?void 0:Cr.borderRadius,vi),me.style.boxShadow=lo(Cr==null?void 0:Cr.shadow,wi),me.style.overflow="hidden";return}let c=Ar(n),g=(Gt=(Wr=n.launcher)==null?void 0:Wr.sidebarMode)!=null?Gt:!1,w=c||g||((Br=(jr=n.launcher)==null?void 0:jr.fullHeight)!=null?Br:!1),C=((pt=n.launcher)==null?void 0:pt.enabled)===!1,D=(Gr=(Ct=n.theme)==null?void 0:Ct.components)==null?void 0:Gr.panel,$=Da(n),U=(Zt,pr)=>{var on;return Zt==null||Zt===""?pr:(on=Ba($,Zt))!=null?on:Zt},j=(Fr=t.ownerDocument.defaultView)!=null?Fr:window,F=(jo=(Vo=n.launcher)==null?void 0:Vo.mobileFullscreen)!=null?jo:!0,We=(Aa=(Go=n.launcher)==null?void 0:Go.mobileBreakpoint)!=null?Aa:640,we=j.innerWidth<=We,ie=F&&we&&T,Le=(cr=(Sa=n.launcher)==null?void 0:Sa.position)!=null?cr:"bottom-left",De=Le==="bottom-left"||Le==="top-left",Ye=(Po=(Ko=n.launcher)==null?void 0:Ko.zIndex)!=null?Po:zr,ht=g||ie?"none":"1px solid var(--persona-border)",dt=ie?"none":g?De?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ie&&(dt="none",ht="none");let wt=g||ie?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=U(D==null?void 0:D.border,ht),ze=U(D==null?void 0:D.shadow,dt),$e=U(D==null?void 0:D.borderRadius,wt),nt=J.scrollTop;t.style.cssText="",Ce.style.cssText="",he.style.cssText="",me.style.cssText="",J.style.cssText="",Xe.style.cssText="";let H=()=>{var pr;if(nt<=0)return;((pr=J.ownerDocument.defaultView)!=null?pr:window).requestAnimationFrame(()=>{if(J.scrollTop===nt)return;let on=J.scrollHeight-J.clientHeight;on<=0||(J.scrollTop=Math.min(nt,on))})};if(ie){Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ce.style.cssText=`
81
81
  position: fixed !important;
82
82
  inset: 0 !important;
83
83
  width: 100% !important;
@@ -87,9 +87,9 @@ _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this
87
87
  padding: 0 !important;
88
88
  display: flex !important;
89
89
  flex-direction: column !important;
90
- z-index: ${Qe} !important;
90
+ z-index: ${Ye} !important;
91
91
  background-color: var(--persona-surface, #ffffff) !important;
92
- `,le.style.cssText=`
92
+ `,he.style.cssText=`
93
93
  position: relative !important;
94
94
  display: flex !important;
95
95
  flex-direction: column !important;
@@ -102,7 +102,7 @@ _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this
102
102
  padding: 0 !important;
103
103
  box-shadow: none !important;
104
104
  border-radius: 0 !important;
105
- `,be.style.cssText=`
105
+ `,me.style.cssText=`
106
106
  display: flex !important;
107
107
  flex-direction: column !important;
108
108
  flex: 1 1 0% !important;
@@ -113,20 +113,20 @@ _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this
113
113
  overflow: hidden !important;
114
114
  border-radius: 0 !important;
115
115
  border: none !important;
116
- `,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0",k=!0,D();return}let $e=(rn=(Bt=n==null?void 0:n.launcher)==null?void 0:Bt.width)!=null?rn:n==null?void 0:n.launcherWidth,Ge=$e!=null?$e:yn;if(!g&&!c)S&&C?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=Ge,le.style.maxWidth=Ge);else if(c)if(kn(n).reveal==="emerge"){let ur=kn(n).width;le.style.width=ur,le.style.maxWidth=ur}else le.style.width="100%",le.style.maxWidth="100%";if(zn(),le.style.boxShadow=ze,le.style.borderRadius=Fe,be.style.border=vt,be.style.borderRadius=Fe,c&&!ce&&(_==null?void 0:_.border)===void 0&&(be.style.border="none",kn(n).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),C&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",S&&(e.style.width="100%"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.height="100%",S&&(pe.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",le.style.overflow="hidden",be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0"),pe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!S&&!c&&((io=Fn[Le])!=null?io:Fn["bottom-right"]).split(" ").forEach(ur=>pe.classList.add(ur)),g){let Qt=(nn=(Kr=n.launcher)==null?void 0:Kr.sidebarWidth)!=null?nn:"420px";pe.style.cssText=`
116
+ `,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Xe.style.flexShrink="0",M=!0,H();return}let Oe=(rn=(Bt=n==null?void 0:n.launcher)==null?void 0:Bt.width)!=null?rn:n==null?void 0:n.launcherWidth,Je=Oe!=null?Oe:yn;if(!g&&!c)C&&w?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=Je,he.style.maxWidth=Je);else if(c)if(kn(n).reveal==="emerge"){let pr=kn(n).width;he.style.width=pr,he.style.maxWidth=pr}else he.style.width="100%",he.style.maxWidth="100%";if(zn(),he.style.boxShadow=ze,he.style.borderRadius=$e,me.style.border=vt,me.style.borderRadius=$e,c&&!ie&&(D==null?void 0:D.border)===void 0&&(me.style.border="none",kn(n).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),w&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",C&&(t.style.width="100%"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.height="100%",C&&(Ce.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Xe.style.flexShrink="0"),Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!C&&!c&&((io=$n[Le])!=null?io:$n["bottom-right"]).split(" ").forEach(pr=>Ce.classList.add(pr)),g){let Zt=(nn=(Kr=n.launcher)==null?void 0:Kr.sidebarWidth)!=null?nn:"420px";Ce.style.cssText=`
117
117
  position: fixed !important;
118
118
  top: 0 !important;
119
119
  bottom: 0 !important;
120
- width: ${Qt} !important;
120
+ width: ${Zt} !important;
121
121
  height: 100vh !important;
122
122
  max-height: 100vh !important;
123
123
  margin: 0 !important;
124
124
  padding: 0 !important;
125
125
  display: flex !important;
126
126
  flex-direction: column !important;
127
- z-index: ${Qe} !important;
128
- ${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
129
- `,le.style.cssText=`
127
+ z-index: ${Ye} !important;
128
+ ${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
129
+ `,he.style.cssText=`
130
130
  position: relative !important;
131
131
  display: flex !important;
132
132
  flex-direction: column !important;
@@ -138,8 +138,8 @@ _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this
138
138
  margin: 0 !important;
139
139
  padding: 0 !important;
140
140
  box-shadow: ${ze} !important;
141
- border-radius: ${Fe} !important;
142
- `,le.style.setProperty("width","100%","important"),le.style.setProperty("max-width","100%","important"),be.style.cssText=`
141
+ border-radius: ${$e} !important;
142
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),me.style.cssText=`
143
143
  display: flex !important;
144
144
  flex-direction: column !important;
145
145
  flex: 1 1 0% !important;
@@ -148,349 +148,29 @@ _Details: ${r.message}_`:n}var Ds=class e{constructor(t={},r){this.config=t;this
148
148
  min-height: 0 !important;
149
149
  max-height: 100% !important;
150
150
  overflow: hidden !important;
151
- border-radius: ${Fe} !important;
151
+ border-radius: ${$e} !important;
152
152
  border: ${vt} !important;
153
- `,Je.style.cssText=`
153
+ `,Xe.style.cssText=`
154
154
  flex-shrink: 0 !important;
155
155
  border-top: none !important;
156
156
  padding: 8px 16px 12px 16px !important;
157
- `}if(!S&&!c){let Qt="max-height: -moz-available !important; max-height: stretch !important;",ur=g?"":"padding-top: 1.25em !important;",on=g?"":`z-index: ${(lr=(Yt=n.launcher)==null?void 0:Yt.zIndex)!=null?lr:qr} !important;`;pe.style.cssText+=Qt+ur+on}D()};Rn(),Io(e,n),Vl(e,n),Gl(e,n);let It=[];It.push(()=>{document.removeEventListener("keydown",wn)});let hr=null,xr=null;It.push(()=>{hr==null||hr(),hr=null,xr==null||xr(),xr=null}),P&&It.push(()=>{P==null||P.disconnect(),P=null}),It.push(()=>{Ir==null||Ir(),Ir=null,eo(),Ft&&(Ft.remove(),Ft=null),me==null||me.element.style.removeProperty("width"),me==null||me.element.style.removeProperty("maxWidth")}),we&&It.push(()=>{xe!==null&&(cancelAnimationFrame(xe),xe=null),Z==null||Z.destroy(),Z=null,j==null||j.destroy(),j=null,K=null});let dn=null,vo=()=>{dn&&(dn(),dn=null),n.colorScheme==="auto"&&(dn=vl(()=>{Io(e,n)}))};vo(),It.push(()=>{dn&&(dn(),dn=null)});let vn=(Mf=n.features)==null?void 0:Mf.streamAnimation;if(vn!=null&&vn.type&&vn.type!=="none"){let c=qa(vn.type,vn.plugins);c&&(Vp(c,e),It.push(()=>bx(e)))}let Wn=Ux(ne),cn=null,R,pn=!1,Hn=fx(),to=new Map,qn=new Map,Qs=0,Bn=Tl(),Dn=0,On=null,ro=!1,Fo=!1,ai=4,Zs=24,ii=80,ys=new Map,Pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ea=(Ef=(kf=n.voiceRecognition)==null?void 0:kf.autoResume)!=null?Ef:!1,Sn=c=>{s.emit("voice:state",{active:Pt.active,source:c,timestamp:Date.now()})},tn=()=>{m(c=>({...c,voiceState:{active:Pt.active,timestamp:Date.now(),manuallyDeactivated:Pt.manuallyDeactivated}}))},li=()=>{var S,_;if(((S=n.voiceRecognition)==null?void 0:S.enabled)===!1)return;let c=yu(d.voiceState),g=!!c.active,C=Number((_=c.timestamp)!=null?_:0);Pt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-C<Ev&&setTimeout(()=>{var F,U;Pt.active||(Pt.manuallyDeactivated=!1,((U=(F=n.voiceRecognition)==null?void 0:F.provider)==null?void 0:U.type)==="runtype"?R.toggleVoice().then(()=>{Pt.active=R.isVoiceActive(),Sn("restore"),R.isVoiceActive()&&O()}):jo("restore"))},1e3)},di=()=>R?iy(R.getMessages()).filter(c=>!c.__skipPersist):[];function bs(c){if(!(i!=null&&i.save))return;let C={messages:c?iy(c):R?di():[],metadata:d,artifacts:oe.artifacts,selectedArtifactId:oe.selectedId};try{let S=i.save(C);S instanceof Promise&&S.catch(_=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",_)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let no=null,ci=()=>pe.querySelector("#persona-scroll-container")||J,Uo=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ro=!1},ta=()=>{On!==null&&(cancelAnimationFrame(On),On=null),Fo=!1,Uo()},oo=()=>{if(!gr()||he){_t.parentNode&&_t.remove(),_t.style.display="none";return}_t.parentNode!==be&&be.appendChild(_t),Lt();let c=$a(J)>0;_t.style.display=Bn.isFollowing()||!c?"none":""},ra=()=>{Bn.pause()&&(ta(),oo())},So=()=>{Bn.resume(),oo()},Ao=(c=!1)=>{Bn.isFollowing()&&(!c&&!pn||(On!==null&&(cancelAnimationFrame(On),On=null),Fo=!0,On=requestAnimationFrame(()=>{On=null,Fo=!1,Bn.isFollowing()&&pi(ci(),c?220:140)})))},pi=(c,g=500)=>{let C=c.scrollTop,S=$a(c),_=S-C;if(Math.abs(_)<1){Dn=c.scrollTop;return}if(Math.abs(_)>=ii){Uo(),ro=!0,c.scrollTop=S,Dn=c.scrollTop,ro=!1;return}Uo();let F=performance.now();ro=!0;let U=$=>1-Math.pow(1-$,3),V=$=>{if(!Bn.isFollowing()){Uo();return}let De=$a(c);De!==S&&(S=De,_=S-C);let Ae=$-F,ce=Math.min(Ae/g,1),Le=U(ce),Ne=C+_*Le;c.scrollTop=Ne,Dn=c.scrollTop,ce<1?no=requestAnimationFrame(V):(c.scrollTop=S,Dn=c.scrollTop,no=null,ro=!1)};no=requestAnimationFrame(V)},ui=c=>{let g=new Map;c.forEach(C=>{let S=ys.get(C.id);g.set(C.id,{streaming:C.streaming,role:C.role}),!S&&C.role==="assistant"&&s.emit("assistant:message",C),C.role==="assistant"&&(S!=null&&S.streaming)&&C.streaming===!1&&s.emit("assistant:complete",C),C.variant==="approval"&&C.approval&&(S?C.approval.status!=="pending"&&s.emit("approval:resolved",{approval:C.approval,decision:C.approval.status}):s.emit("approval:requested",{approval:C.approval,message:C}))}),ys.clear(),g.forEach((C,S)=>{ys.set(S,C)})},zo=(c,g,C)=>{var dt,Ct,vt,ze,Fe,nt;let S=document.createElement("div"),F=(()=>{var $e;let D=o.find(Ge=>Ge.renderLoadingIndicator);if(D!=null&&D.renderLoadingIndicator)return D.renderLoadingIndicator;if(($e=n.loadingIndicator)!=null&&$e.render)return n.loadingIndicator.render})(),U=(D,$e)=>$e==null?!1:typeof $e=="string"?(D.textContent=$e,!0):(D.appendChild($e),!0),V=new Set,$=new Set,De=o.some(D=>D.renderAskUserQuestion),Ae=[],ce=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(D=>{var Vr,Br,ft,St,Gr,Fr,Vo,Go,Ko,Ms,ks,pr,Jo,Po;V.add(D.id);let $e=De&&ho(D),Ge=!$e&&D.role==="assistant"&&!D.variant&&Le&&Yl(D);if(!Ge&&qn.has(D.id)){let Bt=c.querySelector(`#wrapper-${D.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime"),qn.delete(D.id)}let at=ho(D)?`:${(Vr=D.agentMetadata)!=null&&Vr.askUserQuestionAnswered?"a":"u"}:${(Br=D.agentMetadata)!=null&&Br.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Re=ux(D,Qs)+at,jt=$e||Ge?null:mx(Hn,D.id,Re);if(jt){S.appendChild(jt.cloneNode(!0)),ho(D)&&((ft=D.toolCall)!=null&&ft.id)&&((St=D.agentMetadata)==null?void 0:St.awaitingLocalTool)===!0&&!((Gr=D.agentMetadata)!=null&&Gr.askUserQuestionAnswered)&&($.add(D.toolCall.id),Gs(D,n,Me.composerOverlay));return}let bt=null,br=o.find(Bt=>!!(D.variant==="reasoning"&&Bt.renderReasoning||D.variant==="tool"&&Bt.renderToolCall||D.variant==="approval"&&Bt.renderApproval||!D.variant&&Bt.renderMessage)),Hr=(Fr=n.layout)==null?void 0:Fr.messages;if(ho(D)&&((Vo=D.agentMetadata)==null?void 0:Vo.askUserQuestionAnswered)===!0){to.delete(D.id);let Bt=c.querySelector(`#wrapper-${D.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime");return}if(ho(D)&&((Ko=(Go=n.features)==null?void 0:Go.askUserQuestion)==null?void 0:Ko.enabled)!==!1){let Bt=o.find(rn=>typeof rn.renderAskUserQuestion=="function");if(Bt&&rt.current){let rn=to.get(D.id),io=rn!==Re,Kr=null;if(io){let{payload:lr,complete:Qt}=xo(D),ur=D.id,on=()=>{var fn;return(fn=rt.current)==null?void 0:fn.getMessages().find(Ar=>Ar.id===ur)};Kr=Bt.renderAskUserQuestion({message:D,payload:lr,complete:Qt,resolve:fn=>{var Vn;let Ar=on();Ar&&((Vn=rt.current)==null||Vn.resolveAskUserQuestion(Ar,fn))},dismiss:()=>{var Ar,Vn,lo;let fn=on();(Ar=fn==null?void 0:fn.agentMetadata)!=null&&Ar.awaitingLocalTool&&((Vn=rt.current)==null||Vn.markAskUserQuestionResolved(fn),(lo=rt.current)==null||lo.resolveAskUserQuestion(fn,"(dismissed)"))},config:n})}let nn=rn!=null;if(io&&Kr===null&&!nn){((Ms=D.agentMetadata)==null?void 0:Ms.awaitingLocalTool)===!0&&!((ks=D.agentMetadata)!=null&&ks.askUserQuestionAnswered)&&($.add(D.toolCall.id),Gs(D,n,Me.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${D.id}`,Yt.setAttribute("data-wrapper-id",D.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),S.appendChild(Yt),Ae.push({messageId:D.id,fingerprint:Re,bubble:Kr});return}else{((pr=D.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((Jo=D.agentMetadata)!=null&&Jo.askUserQuestionAnswered)&&($.add(D.toolCall.id),Gs(D,n,Me.composerOverlay));return}}else if(br)if(D.variant==="reasoning"&&D.reasoning&&br.renderReasoning){if(!Ue)return;bt=br.renderReasoning({message:D,defaultRenderer:()=>ru(D,n),config:n})}else if(D.variant==="tool"&&D.toolCall&&br.renderToolCall){if(!je)return;bt=br.renderToolCall({message:D,defaultRenderer:()=>nu(D,n),config:n})}else if(D.variant==="approval"&&D.approval&&br.renderApproval){if(n.approval===!1)return;bt=br.renderApproval({message:D,defaultRenderer:()=>pu(D,n),config:n})}else br.renderMessage&&(bt=br.renderMessage({message:D,defaultRenderer:()=>{let Bt=Us(D,C,Hr,n.messageActions,G,{loadingIndicatorRenderer:F,widgetConfig:n});return D.role!=="user"&&gu(Bt,D,n,R),Bt},config:n}));if(!bt&&Ge){let Bt=Ql(D);if(Bt){let rn=qn.get(D.id),io=rn!==Re,Kr=n.wrapComponentDirectiveInBubble!==!1,nn=null;if(io){let Yt=Xl(Bt,{config:n,message:D,transform:C});if(Yt)if(Kr){let lr=document.createElement("div");if(lr.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),lr.id=`bubble-${D.id}`,lr.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let Qt=document.createElement("div");Qt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Qt.innerHTML=C({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),lr.appendChild(Qt)}lr.appendChild(Yt),nn=lr}else{let lr=document.createElement("div");if(lr.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",lr.id=`bubble-${D.id}`,lr.setAttribute("data-message-id",D.id),lr.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let Qt=document.createElement("div");Qt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Qt.innerHTML=C({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),lr.appendChild(Qt)}lr.appendChild(Yt),nn=lr}}if(nn||rn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${D.id}`,Yt.setAttribute("data-wrapper-id",D.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),Kr||Yt.classList.add("persona-w-full"),S.appendChild(Yt),ce.push({messageId:D.id,fingerprint:Re,bubble:nn});return}}}if(!bt)if(D.variant==="reasoning"&&D.reasoning){if(!Ue)return;bt=ru(D,n)}else if(D.variant==="tool"&&D.toolCall){if(!je)return;bt=nu(D,n)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;bt=pu(D,n)}else{let Bt=(Po=n.layout)==null?void 0:Po.messages;Bt!=null&&Bt.renderUserMessage&&D.role==="user"?bt=Bt.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):Bt!=null&&Bt.renderAssistantMessage&&D.role==="assistant"?bt=Bt.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):bt=Us(D,C,Bt,n.messageActions,G,{loadingIndicatorRenderer:F,widgetConfig:n}),D.role!=="user"&&bt&&gu(bt,D,n,R)}let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-${D.id}`,Gt.setAttribute("data-wrapper-id",D.id),D.role==="user"&&Gt.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&Gt.classList.add("persona-w-full"),Gt.appendChild(bt),gx(Hn,D.id,Re,Gt),S.appendChild(Gt)}),Me.composerOverlay&&Me.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach($e=>{let Ge=$e.getAttribute("data-persona-ask-sheet-for");Ge&&!$.has(Ge)&&_o(Me.composerOverlay,Ge)}),(Ct=(dt=n.features)==null?void 0:dt.toolCallDisplay)!=null&&Ct.grouped){let D=[],$e=[];g.forEach(Ge=>{if(Ge.variant==="tool"&&Ge.toolCall&&je){$e.push(Ge);return}$e.length>1&&D.push($e),$e=[]}),$e.length>1&&D.push($e),D.forEach((Ge,at)=>{var Br,ft;let Re=Ge.map(St=>Array.from(S.children).find(Gr=>Gr instanceof HTMLElement&&Gr.getAttribute("data-wrapper-id")===St.id)).filter(St=>!!St);if(Re.length<2)return;let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-tool-group-${at}-${Ge[0].id}`,jt.setAttribute("data-wrapper-id",`tool-group-${at}-${Ge[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let br=document.createElement("div");br.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Hr=`Called ${Ge.length} tools`,Gt=(ft=(Br=n.toolCall)==null?void 0:Br.renderGroupedSummary)==null?void 0:ft.call(Br,{messages:Ge,toolCalls:Ge.map(St=>St.toolCall).filter(St=>!!St),defaultSummary:Hr,config:n});U(br,Gt)||(br.textContent=Hr);let Vr=document.createElement("div");Vr.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(br,Vr),jt.appendChild(bt),Re[0].before(jt),Re.forEach((St,Gr)=>{let Fr=document.createElement("div");Fr.className="persona-tool-group-item persona-relative",Fr.setAttribute("data-persona-tool-group-item","true"),Gr<Re.length-1&&Fr.setAttribute("data-persona-tool-group-connector","true"),Fr.appendChild(St),Vr.appendChild(Fr)})})}hx(Hn,V);let Ne=g.some(D=>D.role==="assistant"&&D.streaming),Qe=g[g.length-1],gt=(Qe==null?void 0:Qe.role)==="assistant"&&!Qe.streaming&&Qe.variant!=="approval";if(pn&&g.some(D=>D.role==="user")&&!Ne&&!gt){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:fs},$e=o.find(at=>at.renderLoadingIndicator),Ge=null;if($e!=null&&$e.renderLoadingIndicator&&(Ge=$e.renderLoadingIndicator(D)),Ge===null&&((vt=n.loadingIndicator)!=null&&vt.render)&&(Ge=n.loadingIndicator.render(D)),Ge===null&&(Ge=fs()),Ge){let at=document.createElement("div"),Re=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;at.className=Re?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),at.setAttribute("data-typing-indicator","true"),at.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",at.appendChild(Ge);let jt=document.createElement("div");jt.className="persona-flex",jt.id="wrapper-typing-indicator",jt.setAttribute("data-wrapper-id","typing-indicator"),jt.appendChild(at),S.appendChild(jt)}}if(!pn&&g.length>0){let D=g[g.length-1],$e={config:n,lastMessage:D,messageCount:g.length},Ge=o.find(Re=>Re.renderIdleIndicator),at=null;if(Ge!=null&&Ge.renderIdleIndicator&&(at=Ge.renderIdleIndicator($e)),at===null&&((Fe=n.loadingIndicator)!=null&&Fe.renderIdle)&&(at=n.loadingIndicator.renderIdle($e)),at){let Re=document.createElement("div"),jt=((nt=n.loadingIndicator)==null?void 0:nt.showBubble)!==!1;Re.className=jt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Re.setAttribute("data-idle-indicator","true"),Re.appendChild(at);let bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Re),S.appendChild(bt)}}if(Sl(c,S),Ae.length>0)for(let{messageId:D,fingerprint:$e,bubble:Ge}of Ae){let at=c.querySelector(`#wrapper-${D}`);at&&Ge!==null&&(at.replaceChildren(Ge),at.setAttribute("data-bubble-fp",$e),to.set(D,$e))}if(to.size>0)for(let D of to.keys())V.has(D)||to.delete(D);if(ce.length>0)for(let{messageId:D,fingerprint:$e,bubble:Ge}of ce){let at=c.querySelector(`#wrapper-${D}`);at&&Ge!==null&&(at.replaceChildren(Ge),at.setAttribute("data-bubble-fp",$e),qn.set(D,$e))}if(qn.size>0)for(let D of qn.keys())V.has(D)||qn.delete(D)},To=null,fi=()=>{var C;if(To)return;let c=S=>{let _=S.composedPath();_.includes(pe)||Ye&&_.includes(Ye)||Kt(!1,"user")};To=c,((C=e.ownerDocument)!=null?C:document).addEventListener("pointerdown",c,!0)},na=()=>{var g;if(!To)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",To,!0),To=null};It.push(()=>na());let Mo=null,mi=()=>{var C;if(Mo)return;let c=S=>{S.key==="Escape"&&(S.isComposing||Kt(!1,"user"))};Mo=c,((C=e.ownerDocument)!=null?C:document).addEventListener("keydown",c,!0)},oa=()=>{var g;if(!Mo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Mo,!0),Mo=null};It.push(()=>oa());let ko=!1,sa=new Set,gi=()=>{var g,C,S,_;let c=(S=(C=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:C.peek)==null?void 0:S.streamAnimation;return c||((_=n.features)==null?void 0:_.streamAnimation)},so=()=>{var Ct,vt,ze,Fe;if(!B())return;let c=Me.peekBanner,g=Me.peekTextNode;if(!c||!g)return;if(W){c.classList.remove("persona-pill-peek--visible");return}let C=(Ct=R==null?void 0:R.getMessages())!=null?Ct:[],S;for(let nt=C.length-1;nt>=0;nt--){let D=C[nt];if(D.role==="assistant"&&D.content){S=D;break}}if(!S){c.classList.remove("persona-pill-peek--visible");return}let _=S.content,F=!!S.streaming,U=gi(),V=El(U),$=V.type!=="none"?qa(V.type,U==null?void 0:U.plugins):null,De=((vt=$==null?void 0:$.isAnimating)==null?void 0:vt.call($,S))===!0,Ae=$!==null&&(F||De);Ae&&$&&!sa.has($.name)&&(Vp($,e),sa.add($.name));let ce=Ae&&($!=null&&$.containerClass)?$.containerClass:null,Le=(ze=g.dataset.personaPeekStreamClass)!=null?ze:null;Le&&Le!==ce&&(g.classList.remove(Le),delete g.dataset.personaPeekStreamClass),ce&&Le!==ce&&(g.classList.add(ce),g.dataset.personaPeekStreamClass=ce),Ae?(g.style.setProperty("--persona-stream-step",`${V.speed}ms`),g.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ne=Ae?Ll(_,V.buffer,$,S,F):_;if(Ae&&V.placeholder==="skeleton"&&F&&(!Ne||!Ne.trim())){let nt=document.createElement("div"),D=Va();D.classList.add("persona-pill-peek__skeleton"),nt.appendChild(D),Sl(g,nt)}else{let nt=Math.max(0,Ne.length-100),D=Ne.length>100?Ne.slice(-100):Ne,$e=os(D);if(!Ae||!$){let Ge=Ne.length>100?`\u2026${D}`:D;g.textContent!==Ge&&(g.textContent=Ge)}else{let Ge=$e;($.wrap==="char"||$.wrap==="word")&&(Ge=ja($e,$.wrap,`peek-${S.id}`,{skipTags:$.skipTags,startIndex:nt}));let at=document.createElement("div");if(at.innerHTML=Ge,$.useCaret&&D.length>0){let Re=Pl(),jt=at.querySelectorAll(".persona-stream-char, .persona-stream-word"),bt=jt[jt.length-1];bt!=null&&bt.parentNode?bt.parentNode.insertBefore(Re,bt.nextSibling):at.appendChild(Re)}Sl(g,at),(Fe=$.onAfterRender)==null||Fe.call($,{container:g,bubble:c,messageId:S.id,message:S,speed:V.speed,duration:V.duration})}}let dt=pn||ko;c.classList.toggle("persona-pill-peek--visible",dt)};if(B()){let c=Me.peekBanner;if(c){let S=_=>{_.preventDefault(),_.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",S),It.push(()=>{c.removeEventListener("pointerdown",S)})}let g=()=>{ko||(ko=!0,so())},C=()=>{ko&&(ko=!1,so())};le.addEventListener("pointerenter",g),le.addEventListener("pointerleave",C),It.push(()=>{le.removeEventListener("pointerenter",g),le.removeEventListener("pointerleave",C)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",C),It.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",C)}))}let hi=c=>{var Le,Ne,Qe,gt,dt,Ct,vt,ze;let g=(Ne=(Le=n.launcher)==null?void 0:Le.composerBar)!=null?Ne:{},C=(Qe=g.expandedSize)!=null?Qe:"anchored",S=(gt=g.bottomOffset)!=null?gt:"16px",_=g.collapsedMaxWidth,F=(dt=g.expandedMaxWidth)!=null?dt:"880px",U=(Ct=g.expandedTopOffset)!=null?Ct:"5vh",V=(vt=g.modalMaxWidth)!=null?vt:"880px",$=(ze=g.modalMaxHeight)!=null?ze:"min(90vh, 800px)",De="calc(100vw - 32px)",Ae="var(--persona-pill-area-height, 80px)",ce=pe.style;if(ce.left="",ce.right="",ce.top="",ce.bottom="",ce.transform="",ce.width="",ce.maxWidth="",ce.height="",ce.maxHeight="",Ye){let Fe=Ye.style;Fe.bottom=S,Fe.width=_!=null?_:""}if(c&&C!=="fullscreen"){if(C==="modal"){ce.top="50%",ce.left="50%",ce.transform="translate(-50%, -50%)",ce.bottom="auto",ce.right="auto",ce.width=V,ce.maxWidth=De,ce.maxHeight=$,ce.height=$;return}ce.left="50%",ce.transform="translateX(-50%)",ce.bottom=`calc(${S} + ${Ae})`,ce.top=U,ce.width=F,ce.maxWidth=De}},Eo=()=>{var $,De,Ae,ce,Le,Ne,Qe,gt;if(!H())return;if(B()){let Ct=(Ae=((De=($=n.launcher)==null?void 0:$.composerBar)!=null?De:{}).expandedSize)!=null?Ae:"anchored",vt=W?"expanded":"collapsed";pe.dataset.state=vt,pe.dataset.expandedSize=Ct,Ye&&(Ye.dataset.state=vt,Ye.dataset.expandedSize=Ct),pe.style.removeProperty("display"),pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),hi(W),be.style.display=W?"flex":"none",Rn(),W?(fi(),mi()):(na(),oa()),so();return}let c=Tr(n),g=(ce=e.ownerDocument.defaultView)!=null?ce:window,C=(Ne=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ne:640,S=(gt=(Qe=n.launcher)==null?void 0:Qe.mobileFullscreen)!=null?gt:!0,_=g.innerWidth<=C,F=S&&_&&T,U=kn(n).reveal;W?(pe.style.removeProperty("display"),pe.style.display=c?"flex":"",pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),lt?lt.element.style.display="none":ut&&(ut.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!F?(pe.style.removeProperty("display"),pe.style.display="flex",pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(pe.style.setProperty("display","none","important"),pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(pe.style.display="",pe.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),lt?lt.element.style.display=c?"none":"":ut&&(ut.style.display=c?"none":""))},Kt=(c,g="user")=>{var F,U;if(!H()||W===c)return;let C=W;W=c,Eo();let S=(()=>{var Qe,gt,dt,Ct,vt,ze,Fe,nt,D,$e;let V=(gt=(Qe=n.launcher)==null?void 0:Qe.sidebarMode)!=null?gt:!1,$=(dt=e.ownerDocument.defaultView)!=null?dt:window,De=(vt=(Ct=n.launcher)==null?void 0:Ct.mobileFullscreen)!=null?vt:!0,Ae=(Fe=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?Fe:640,ce=$.innerWidth<=Ae,Le=Tr(n)&&De&&ce,Ne=B()&&(($e=(D=(nt=n.launcher)==null?void 0:nt.composerBar)==null?void 0:D.expandedSize)!=null?$e:"fullscreen")==="fullscreen";return V||De&&ce&&T||Le||Ne})();if(W&&S){if(!hr){let V=e.getRootNode(),$=V instanceof ShadowRoot?V.host:e.closest(".persona-host");$&&(hr=Gp($,(U=(F=n.launcher)==null?void 0:F.zIndex)!=null?U:qr))}xr||(xr=Kp(e.ownerDocument))}else W||(hr==null||hr(),hr=null,xr==null||xr(),xr=null);W&&(yr(),Ao(!0));let _={open:W,source:g,timestamp:Date.now()};W&&!C?s.emit("widget:opened",_):!W&&C&&s.emit("widget:closed",_),s.emit("widget:state",{open:W,launcherEnabled:T,voiceActive:Pt.active,streaming:R.isStreaming()})},ws=c=>{or(c?"stop":"send"),X&&(X.disabled=c),Wn.buttons.forEach(g=>{g.disabled=c}),Je.dataset.personaComposerStreaming=c?"true":"false",Je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Cs=()=>{Pt.active||Y&&Y.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Cs(),200)});let aa=()=>{var C,S,_,F,U,V,$,De,Ae,ce,Le;ue.textContent=(S=(C=n.copy)==null?void 0:C.welcomeTitle)!=null?S:"Hello \u{1F44B}",_e.textContent=(F=(_=n.copy)==null?void 0:_.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",Y.placeholder=(V=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?V:"How can I help...";let c=J.querySelector("[data-persona-intro-card]");if(c){let Ne=(($=n.copy)==null?void 0:$.showWelcomeCard)!==!1;c.style.display=Ne?"":"none",Ne?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}!((Ae=(De=n.sendButton)==null?void 0:De.useIcon)!=null&&Ae)&&!(R!=null&&R.isStreaming())&&(Q.textContent=(Le=(ce=n.copy)==null?void 0:ce.sendButtonLabel)!=null?Le:"Send"),Y.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Y.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let jn=null,xi=()=>{jn==null&&(jn=setInterval(()=>{let c=Ke.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(jn),jn=null;return}let g=Date.now();c.forEach(C=>{let S=Number(C.getAttribute("data-tool-elapsed"));S&&(C.textContent=Gi(g-S))})},100))};if(R=new Ds(n,{onMessagesChanged(c){zo(Ke,c,ve),xi(),R&&(c.some(_=>_.role==="user")?Wn.render([],R,Y,c):Wn.render(n.suggestionChips,R,Y,c,n.suggestionChipsConfig)),Ao(!pn),ui(c);let g=[...c].reverse().find(S=>S.role==="user"),C=Pt.lastUserMessageId;g&&g.id!==C&&(Pt.lastUserMessageId=g.id,s.emit("user:message",g)),Pt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),bs(c),so()},onStatusChanged(c){var S;let g=(S=n.statusIndicator)!=null?S:{};ye(ge,(_=>{var F,U,V,$;return _==="idle"?(F=g.idleText)!=null?F:zr.idle:_==="connecting"?(U=g.connectingText)!=null?U:zr.connecting:_==="connected"?(V=g.connectedText)!=null?V:zr.connected:_==="error"?($=g.errorText)!=null?$:zr.error:zr[_]})(c),g,c)},onStreamingChanged(c){pn=c,ws(c),R&&zo(Ke,R.getMessages(),ve),c||Ao(!0),so()},onVoiceStatusChanged(c){var g,C;if(((C=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:C.type)==="runtype")switch(c){case"listening":break;case"processing":re(),ie();break;case"speaking":re(),de();break;default:c==="idle"&&R.isBargeInActive()?(re(),O(),X==null||X.setAttribute("aria-label","End voice session")):(Pt.active=!1,re(),Sn("system"),tn());break}},onArtifactsState(c){oe=c,ln(),bs()}}),rt.current=R,((Pf=(Lf=n.voiceRecognition)==null?void 0:Lf.provider)==null?void 0:Pf.type)==="runtype")try{R.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&R.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(j||n.onSSEEvent)&&R.setSSEEventCallback((c,g)=>{var C;(C=n.onSSEEvent)==null||C.call(n,c,g),Ce==null||Ce.processEvent(c,g),j==null||j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,C,S;c&&(c.metadata&&(d=yu(c.metadata),E.syncFromMetadata()),(g=c.messages)!=null&&g.length&&R.hydrateMessages(c.messages),(C=c.artifacts)!=null&&C.length&&R.hydrateArtifacts(c.artifacts,(S=c.selectedArtifactId)!=null?S:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ia=()=>{var g,C,S;!B()||W||!((S=(C=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:C.expandOnSubmit)==null||S)||Kt(!0,"auto")},la=c=>{var _;if(c.preventDefault(),R.isStreaming()){R.cancel(),Ce==null||Ce.reset(),Z==null||Z.update();return}let g=Y.value.trim(),C=(_=mt==null?void 0:mt.hasAttachments())!=null?_:!1;if(!g&&!C)return;ia();let S;C&&(S=[],S.push(...mt.getContentParts()),g&&S.push(Ba(g))),Y.value="",Y.style.height="auto",qo(),R.sendMessage(g,{contentParts:S}),C&&mt.clearAttachments()},yi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},vs={...Al},Ss=!1,qo=()=>{vs={...Al}},bi=()=>R.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),wi=c=>{if(!Y)return;Ss=!0,Y.value=c,Y.dispatchEvent(new Event("input",{bubbles:!0})),Ss=!1;let g=Y.value.length;Y.setSelectionRange(g,g)},da=()=>{Ss||qo()},ca=c=>{if(Y){if(yi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=Y.selectionStart===0&&Y.selectionEnd===0,C=px({direction:c.key==="ArrowUp"?"up":"down",history:bi(),currentValue:Y.value,atStart:g,state:vs});if(vs=C.state,C.handled){c.preventDefault(),C.value!==void 0&&wi(C.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(R.isStreaming()){c.preventDefault();return}qo(),c.preventDefault(),Q.click()}}},pa=c=>{c.key!=="Escape"||c.isComposing||R.isStreaming()&&c.composedPath().includes(be)&&(R.cancel(),Ce==null||Ce.reset(),Z==null||Z.update(),qo(),c.preventDefault(),c.stopImmediatePropagation())},ua=async c=>{var C;if(((C=n.attachments)==null?void 0:C.enabled)!==!0||!mt)return;let g=Pv(c.clipboardData);g.length!==0&&(c.preventDefault(),await mt.handleFiles(g))},jr=null,un=!1,ao=null,yt=null,fa=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,jo=(c="user")=>{var F,U,V,$,De,Ae,ce;if(un||R.isStreaming())return;let g=fa();if(!g)return;jr=new g;let S=(U=((F=n.voiceRecognition)!=null?F:{}).pauseDuration)!=null?U:2e3;jr.continuous=!0,jr.interimResults=!0,jr.lang="en-US";let _=Y.value;jr.onresult=Le=>{let Ne="",Qe="";for(let dt=0;dt<Le.results.length;dt++){let Ct=Le.results[dt],vt=Ct[0].transcript;Ct.isFinal?Ne+=vt+" ":Qe=vt}let gt=_+Ne+Qe;Y.value=gt,ao&&clearTimeout(ao),(Ne||Qe)&&(ao=window.setTimeout(()=>{let dt=Y.value.trim();dt&&jr&&un&&(_n(),Y.value="",Y.style.height="auto",R.sendMessage(dt,{viaVoice:!0}))},S))},jr.onerror=Le=>{Le.error!=="no-speech"&&_n()},jr.onend=()=>{if(un){let Le=Y.value.trim();Le&&Le!==_.trim()&&(Y.value="",Y.style.height="auto",R.sendMessage(Le,{viaVoice:!0})),_n()}};try{if(jr.start(),un=!0,Pt.active=!0,c!=="system"&&(Pt.manuallyDeactivated=!1),Sn(c),tn(),X){let Le=(V=n.voiceRecognition)!=null?V:{};yt={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:($=Le.iconName)!=null?$:"mic",iconSize:parseFloat((ce=(Ae=Le.iconSize)!=null?Ae:(De=n.sendButton)==null?void 0:De.size)!=null?ce:"40")||24};let Ne=Le.recordingBackgroundColor,Qe=Le.recordingIconColor,gt=Le.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",X.style.color=Qe!=null?Qe:"var(--persona-voice-recording-indicator, #ffffff)",Qe){let dt=X.querySelector("svg");dt&&dt.setAttribute("stroke",Qe)}gt&&(X.style.borderColor=gt),X.setAttribute("aria-label","Stop voice recognition")}}catch{_n("system")}},_n=(c="user")=>{if(un){if(un=!1,ao&&(clearTimeout(ao),ao=null),jr){try{jr.stop()}catch{}jr=null}if(Pt.active=!1,Sn(c),tn(),X){if(X.classList.remove("persona-voice-recording"),yt){X.style.backgroundColor=yt.backgroundColor,X.style.color=yt.color,X.style.borderColor=yt.borderColor;let g=X.querySelector("svg");g&&g.setAttribute("stroke",yt.color||"currentColor"),yt=null}X.setAttribute("aria-label","Start voice recognition")}}},As=(c,g)=>{var Ct,vt,ze,Fe,nt,D,$e,Ge;let C=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((Ct=c==null?void 0:c.provider)==null?void 0:Ct.type)==="runtype";if(!(C||S))return null;let F=x("div","persona-send-button-wrapper"),U=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let V=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",$=(ze=g==null?void 0:g.size)!=null?ze:"40px",De=(Fe=c==null?void 0:c.iconSize)!=null?Fe:$,Ae=parseFloat(De)||24,ce=(nt=c==null?void 0:c.backgroundColor)!=null?nt:g==null?void 0:g.backgroundColor,Le=(D=c==null?void 0:c.iconColor)!=null?D:g==null?void 0:g.textColor;U.style.width=De,U.style.height=De,U.style.minWidth=De,U.style.minHeight=De,U.style.fontSize="18px",U.style.lineHeight="1",Le?U.style.color=Le:U.style.color="var(--persona-text, #111827)";let Qe=Pe(V,Ae,Le||"currentColor",1.5);Qe?U.appendChild(Qe):U.textContent="\u{1F3A4}",ce?U.style.backgroundColor=ce:U.style.backgroundColor="",c!=null&&c.borderWidth&&(U.style.borderWidth=c.borderWidth,U.style.borderStyle="solid"),c!=null&&c.borderColor&&(U.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(U.style.paddingLeft=c.paddingX,U.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(U.style.paddingTop=c.paddingY,U.style.paddingBottom=c.paddingY),F.appendChild(U);let gt=($e=c==null?void 0:c.tooltipText)!=null?$e:"Start voice recognition";if(((Ge=c==null?void 0:c.showTooltip)!=null?Ge:!1)&&gt){let at=x("div","persona-send-button-tooltip");at.textContent=gt,F.appendChild(at)}return{micButton:U,micButtonWrapper:F}},ot=()=>{var g,C,S,_,F;if(!X||yt)return;let c=(g=n.voiceRecognition)!=null?g:{};yt={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:(C=c.iconName)!=null?C:"mic",iconSize:parseFloat((F=(_=c.iconSize)!=null?_:(S=n.sendButton)==null?void 0:S.size)!=null?F:"40")||24}},L=(c,g)=>{var F,U,V,$,De;if(!X)return;let C=X.querySelector("svg");C&&C.remove();let S=(De=yt==null?void 0:yt.iconSize)!=null?De:parseFloat(($=(V=(F=n.voiceRecognition)==null?void 0:F.iconSize)!=null?V:(U=n.sendButton)==null?void 0:U.size)!=null?$:"40")||24,_=Pe(c,S,g,1.5);_&&X.appendChild(_)},z=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},O=()=>{var _;if(!X)return;ot();let c=(_=n.voiceRecognition)!=null?_:{},g=c.recordingBackgroundColor,C=c.recordingIconColor,S=c.recordingBorderColor;if(z(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",X.style.color=C!=null?C:"var(--persona-voice-recording-indicator, #ffffff)",C){let F=X.querySelector("svg");F&&F.setAttribute("stroke",C)}S&&(X.style.borderColor=S),X.setAttribute("aria-label","Stop voice recognition")},ie=()=>{var V,$,De,Ae,ce,Le,Ne,Qe;if(!X)return;ot();let c=(V=n.voiceRecognition)!=null?V:{},g=R.getVoiceInterruptionMode(),C=($=c.processingIconName)!=null?$:"loader",S=(Ae=(De=c.processingIconColor)!=null?De:yt==null?void 0:yt.color)!=null?Ae:"",_=(Le=(ce=c.processingBackgroundColor)!=null?ce:yt==null?void 0:yt.backgroundColor)!=null?Le:"",F=(Qe=(Ne=c.processingBorderColor)!=null?Ne:yt==null?void 0:yt.borderColor)!=null?Qe:"";z(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=_,X.style.borderColor=F;let U=S||"currentColor";X.style.color=U,L(C,U),X.setAttribute("aria-label","Processing voice input"),g==="none"&&(X.style.cursor="default")},de=()=>{var De,Ae,ce,Le,Ne,Qe,gt,dt,Ct,vt,ze,Fe;if(!X)return;ot();let c=(De=n.voiceRecognition)!=null?De:{},g=R.getVoiceInterruptionMode(),C=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",S=(Ae=c.speakingIconName)!=null?Ae:C,_=(Qe=c.speakingIconColor)!=null?Qe:g==="barge-in"?(Le=(ce=c.recordingIconColor)!=null?ce:yt==null?void 0:yt.color)!=null?Le:"":(Ne=yt==null?void 0:yt.color)!=null?Ne:"",F=(Ct=c.speakingBackgroundColor)!=null?Ct:g==="barge-in"?(gt=c.recordingBackgroundColor)!=null?gt:"var(--persona-voice-recording-bg, #ef4444)":(dt=yt==null?void 0:yt.backgroundColor)!=null?dt:"",U=(Fe=c.speakingBorderColor)!=null?Fe:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(ze=yt==null?void 0:yt.borderColor)!=null?ze:"";z(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=F,X.style.borderColor=U;let V=_||"currentColor";X.style.color=V,L(S,V);let $=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",$),g==="none"&&(X.style.cursor="default"),g==="barge-in"&&X.classList.add("persona-voice-recording")},re=()=>{var c,g,C;X&&(z(),yt&&(X.style.backgroundColor=(c=yt.backgroundColor)!=null?c:"",X.style.color=(g=yt.color)!=null?g:"",X.style.borderColor=(C=yt.borderColor)!=null?C:"",L(yt.iconName,yt.color||"currentColor"),yt=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},st=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let C=R.getVoiceStatus(),S=R.getVoiceInterruptionMode();if(S==="none"&&(C==="processing"||C==="speaking"))return;if(S==="cancel"&&(C==="processing"||C==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{Pt.active=!1,Pt.manuallyDeactivated=!0,tn(),Sn("user"),re()});return}R.toggleVoice().then(()=>{Pt.active=R.isVoiceActive(),Pt.manuallyDeactivated=!R.isVoiceActive(),tn(),Sn("user"),R.isVoiceActive()?O():re()});return}if(un){let C=Y.value.trim();Pt.manuallyDeactivated=!0,tn(),_n("user"),C&&(Y.value="",Y.style.height="auto",R.sendMessage(C))}else Pt.manuallyDeactivated=!1,tn(),jo("user")};cr=st,X&&(X.addEventListener("click",st),It.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(R.isVoiceActive()&&R.toggleVoice(),re()):_n("system"),X&&X.removeEventListener("click",st)}));let et=s.on("assistant:complete",()=>{ea&&(Pt.active||Pt.manuallyDeactivated||ea==="assistant"&&!Pt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Pt.active&&!Pt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?R.toggleVoice().then(()=>{Pt.active=R.isVoiceActive(),Sn("auto"),R.isVoiceActive()&&O()}):jo("auto"))},600))});It.push(et);let wt=s.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});It.push(wt);let it=()=>{Kt(!W,"user")},lt=null,ut=null;if(T&&!B()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Ka(n,it).element,onToggle:it});g&&(ut=g)}ut||(lt=Ka(n,it))}lt?e.appendChild(lt.element):ut&&e.appendChild(ut),Eo(),Wn.render(n.suggestionChips,R,Y,void 0,n.suggestionChipsConfig),aa(),ws(R.isStreaming()),Ao(!0),li(),M&&(!T||B()?setTimeout(()=>Cs(),0):W&&setTimeout(()=>Cs(),200));let yr=()=>{var $,De,Ae,ce,Le,Ne,Qe,gt,dt,Ct,vt,ze,Fe,nt,D,$e,Ge,at,Re,jt,bt,br;if(B()){Lt(),Eo();return}let c=Tr(n),g=(De=($=n.launcher)==null?void 0:$.sidebarMode)!=null?De:!1,C=c||g||((ce=(Ae=n.launcher)==null?void 0:Ae.fullHeight)!=null?ce:!1),S=(Le=e.ownerDocument.defaultView)!=null?Le:window,_=(Qe=(Ne=n.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Qe:!0,F=(dt=(gt=n.launcher)==null?void 0:gt.mobileBreakpoint)!=null?dt:640,U=S.innerWidth<=F,V=_&&U&&T;try{if(V){Rn(),Io(e,n);return}if(k&&(k=!1,Rn(),Io(e,n)),!T&&!c){le.style.height="",le.style.width="";return}if(!g&&!c){let Hr=(vt=(Ct=n==null?void 0:n.launcher)==null?void 0:Ct.width)!=null?vt:n==null?void 0:n.launcherWidth,Gt=Hr!=null?Hr:yn;le.style.width=Gt,le.style.maxWidth=Gt}if(zn(),!C){let Hr=S.innerHeight,Gt=64,Vr=(Fe=(ze=n.launcher)==null?void 0:ze.heightOffset)!=null?Fe:0,Br=Math.max(200,Hr-Gt),ft=Math.min(640,Br),St=Math.max(200,ft-Vr);le.style.height=`${St}px`}}finally{if(Lt(),Eo(),W&&T){let Gt=((nt=e.ownerDocument.defaultView)!=null?nt:window).innerWidth<=(($e=(D=n.launcher)==null?void 0:D.mobileBreakpoint)!=null?$e:640),Vr=(at=(Ge=n.launcher)==null?void 0:Ge.sidebarMode)!=null?at:!1,Br=(jt=(Re=n.launcher)==null?void 0:Re.mobileFullscreen)!=null?jt:!0,ft=Tr(n)&&Br&&Gt,St=Vr||Br&&Gt&&T||ft;if(St&&!xr){let Gr=e.getRootNode(),Fr=Gr instanceof ShadowRoot?Gr.host:e.closest(".persona-host");Fr&&!hr&&(hr=Gp(Fr,(br=(bt=n.launcher)==null?void 0:bt.zIndex)!=null?br:qr)),xr=Kp(e.ownerDocument)}else St||(hr==null||hr(),hr=null,xr==null||xr(),xr=null)}}};yr();let Nt=(If=e.ownerDocument.defaultView)!=null?If:window;if(Nt.addEventListener("resize",yr),It.push(()=>Nt.removeEventListener("resize",yr)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Lt()});c.observe(Je),It.push(()=>c.disconnect())}Dn=J.scrollTop;let qt=J.scrollHeight,Mr=()=>{let c=J.scrollTop,g=J.scrollHeight,C=g<qt;qt=g;let{action:S,nextLastScrollTop:_}=Ml({following:Bn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:Fa(J,Zs),userScrollThreshold:ai,isAutoScrolling:ro||Fo||C,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=_,S==="resume"){So();return}S==="pause"&&ra()};J.addEventListener("scroll",Mr,{passive:!0}),It.push(()=>J.removeEventListener("scroll",Mr));let $r=c=>{let g=kl({following:Bn.isFollowing(),deltaY:c.deltaY,nearBottom:Fa(J,Zs),resumeWhenNearBottom:!0});g==="pause"?ra():g==="resume"&&So()};J.addEventListener("wheel",$r,{passive:!0}),It.push(()=>J.removeEventListener("wheel",$r)),_t.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,Dn=J.scrollTop,So(),Ao(!0)}),It.push(()=>_t.remove()),It.push(()=>{ta()});let Wr=()=>{I&&(cn&&(I.removeEventListener("click",cn),cn=null),H()?(I.style.display="",cn=()=>{Kt(!1,"user")},I.addEventListener("click",cn)):I.style.display="none")};Wr(),(()=>{let{clearChatButton:c}=Me;c&&c.addEventListener("click",()=>{R.clearMessages(),Hn.clear(),So(),_o(Me.composerOverlay);try{localStorage.removeItem(Xs),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(C){console.error("[AgentWidget] Failed to clear default localStorage:",C)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(C){console.error("[AgentWidget] Failed to clear custom localStorage:",C)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let C=i.clear();C instanceof Promise&&C.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)}d={},E.syncFromMetadata(),j==null||j.clear(),Ce==null||Ce.reset(),Z==null||Z.update()})})(),ke&&ke.addEventListener("submit",la),Y==null||Y.addEventListener("keydown",ca),Y==null||Y.addEventListener("input",da),Y==null||Y.addEventListener("paste",ua);let An=(Rf=e.ownerDocument)!=null?Rf:document;An.addEventListener("keydown",pa,!0);let Ou="persona-attachment-drop-active",ma=0,pd=()=>{ma=0,be.classList.remove(Ou)},Ts=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&mt!==null},_u=c=>{!td(c.dataTransfer)||!Ts()||(ma++,ma===1&&be.classList.add(Ou))},Nu=c=>{!td(c.dataTransfer)||!Ts()||(ma--,ma<=0&&pd())},$u=c=>{!td(c.dataTransfer)||!Ts()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Fu=c=>{var C;if(!td(c.dataTransfer)||!Ts())return;c.preventDefault(),c.stopPropagation(),pd();let g=Array.from((C=c.dataTransfer.files)!=null?C:[]);g.length!==0&&mt.handleFiles(g)},Lo=!0;be.addEventListener("dragenter",_u,Lo),be.addEventListener("dragleave",Nu,Lo),e.addEventListener("dragover",$u,Lo),e.addEventListener("drop",Fu,Lo);let Ci=e.ownerDocument,Uu=c=>{Ts()&&c.preventDefault()},zu=c=>{Ts()&&c.preventDefault()};Ci.addEventListener("dragover",Uu),Ci.addEventListener("drop",zu),It.push(()=>{ke&&ke.removeEventListener("submit",la),Y==null||Y.removeEventListener("keydown",ca),Y==null||Y.removeEventListener("input",da),Y==null||Y.removeEventListener("paste",ua),An.removeEventListener("keydown",pa,!0)}),It.push(()=>{be.removeEventListener("dragenter",_u,Lo),be.removeEventListener("dragleave",Nu,Lo),e.removeEventListener("dragover",$u,Lo),e.removeEventListener("drop",Fu,Lo),Ci.removeEventListener("dragover",Uu),Ci.removeEventListener("drop",zu),pd()}),It.push(()=>{R.cancel()}),lt?It.push(()=>{lt==null||lt.destroy()}):ut&&It.push(()=>{ut==null||ut.remove()});let Sr={update(c){var Ar,Vn,lo,vi,Si,Ai,Xo,Ti,ga,Nf,$f,Ff,Uf,zf,qf,jf,Vf,Gf,Kf,Jf,Xf,Yf,Qf,Zf,em,tm,rm,nm,om,sm,am,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,wm,Cm,vm,Sm,Am,Tm,Mm,km,Em,Lm,Pm,Im,Rm,Wm,Hm,Bm,Dm,Om,_m,Nm,$m,Fm,Um,zm,qm,jm,Vm,Gm,Km,Jm,Xm,Ym,Qm,Zm,eg,tg,rg,ng,og,sg,ag,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,wg,Cg,vg,Sg,Ag,Tg,Mg,kg,Eg,Lg,Pg,Ig,Rg,Wg,Hg;let g=n.toolCall,C=n.messageActions,S=(Ar=n.layout)==null?void 0:Ar.messages,_=n.colorScheme,F=n.loadingIndicator,U=n.iterationDisplay,V=(Vn=n.features)==null?void 0:Vn.showReasoning,$=(lo=n.features)==null?void 0:lo.showToolCalls,De=(vi=n.features)==null?void 0:vi.toolCallDisplay,Ae=(Si=n.features)==null?void 0:Si.reasoningDisplay;n={...n,...c},Rn(),Io(e,n),Vl(e,n),Gl(e,n),ln(),n.colorScheme!==_&&vo();let ce=ti.getForInstance(n.plugins);o.length=0,o.push(...ce),T=(Xo=(Ai=n.launcher)==null?void 0:Ai.enabled)!=null?Xo:!0,A=(ga=(Ti=n.launcher)==null?void 0:Ti.autoExpand)!=null?ga:!1,Ue=($f=(Nf=n.features)==null?void 0:Nf.showReasoning)!=null?$f:!0,je=(Uf=(Ff=n.features)==null?void 0:Ff.showToolCalls)!=null?Uf:!0,Te=(qf=(zf=n.features)==null?void 0:zf.scrollToBottom)!=null?qf:{},ar(),oo();let Le=we;if(we=(Vf=(jf=n.features)==null?void 0:jf.showEventStreamToggle)!=null?Vf:!1,we&&!Le){if(j||(K=new Za(Oe),j=new Qa(He,K),Ce=Ce!=null?Ce:new ei,K.open().then(()=>j==null?void 0:j.restore()).catch(()=>{}),R.setSSEEventCallback((ae,Ot)=>{var tr;(tr=n.onSSEEvent)==null||tr.call(n,ae,Ot),Ce==null||Ce.processEvent(ae,Ot),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ae,timestamp:Date.now(),payload:JSON.stringify(Ot)})})),!xt&&Xe){let ae=(Kf=(Gf=n.features)==null?void 0:Gf.eventStream)==null?void 0:Kf.classNames,Ot="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ae!=null&&ae.toggleButton?" "+ae.toggleButton:"");xt=x("button",Ot),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let tr=Pe("activity","18px","currentColor",1.5);tr&&xt.appendChild(tr);let At=Me.clearChatButtonWrapper,Ut=Me.closeButtonWrapper,kr=At||Ut;kr&&kr.parentNode===Xe?Xe.insertBefore(xt,kr):Xe.appendChild(xt),xt.addEventListener("click",()=>{he?_r():Lr()})}}else!we&&Le&&(_r(),xt&&(xt.remove(),xt=null),j==null||j.clear(),K==null||K.destroy(),j=null,K=null,Ce==null||Ce.reset(),Ce=null);if(((Jf=n.launcher)==null?void 0:Jf.enabled)===!1&&lt&&(lt.destroy(),lt=null),((Xf=n.launcher)==null?void 0:Xf.enabled)===!1&&ut&&(ut.remove(),ut=null),((Yf=n.launcher)==null?void 0:Yf.enabled)!==!1&&!lt&&!ut){let ae=o.find(Ot=>Ot.renderLauncher);if(ae!=null&&ae.renderLauncher){let Ot=ae.renderLauncher({config:n,defaultRenderer:()=>Ka(n,it).element,onToggle:it});Ot&&(ut=Ot,e.appendChild(ut))}ut||(lt=Ka(n,it),e.appendChild(lt.element))}lt&&lt.update(n),qe&&((Qf=n.launcher)==null?void 0:Qf.title)!==void 0&&(qe.textContent=n.launcher.title),tt&&((Zf=n.launcher)==null?void 0:Zf.subtitle)!==void 0&&(tt.textContent=n.launcher.subtitle);let Ne=(em=n.layout)==null?void 0:em.header;if((Ne==null?void 0:Ne.layout)!==h&&Xe){let ae=Ne?$s(n,Ne,{showClose:H(),onClose:()=>Kt(!1,"user")}):go({config:n,showClose:H(),onClose:()=>Kt(!1,"user")});Xe.replaceWith(ae.header),Xe=ae.header,te=ae.iconHolder,qe=ae.headerTitle,tt=ae.headerSubtitle,I=ae.closeButton,h=Ne==null?void 0:Ne.layout}else if(Ne&&(te&&(te.style.display=Ne.showIcon===!1?"none":""),qe&&(qe.style.display=Ne.showTitle===!1?"none":""),tt&&(tt.style.display=Ne.showSubtitle===!1?"none":""),I&&(I.style.display=Ne.showCloseButton===!1?"none":""),Me.clearChatButtonWrapper)){let ae=Ne.showClearChat;if(ae!==void 0){Me.clearChatButtonWrapper.style.display=ae?"":"none";let{closeButtonWrapper:Ot}=Me;Ot&&!Ot.classList.contains("persona-absolute")&&(ae?Ot.classList.remove("persona-ml-auto"):Ot.classList.add("persona-ml-auto"))}}let gt=((tm=n.layout)==null?void 0:tm.showHeader)!==!1;Xe&&(Xe.style.display=gt?"":"none");let dt=((rm=n.layout)==null?void 0:rm.showFooter)!==!1;Je&&(Je.style.display=dt?"":"none"),Lt(),oo(),T!==w?T?Kt(A,"auto"):(W=!0,Eo()):A!==b&&Kt(A,"auto"),b=A,w=T,yr(),Wr();let ze=JSON.stringify(c.toolCall)!==JSON.stringify(g),Fe=JSON.stringify(n.messageActions)!==JSON.stringify(C),nt=JSON.stringify((nm=n.layout)==null?void 0:nm.messages)!==JSON.stringify(S),D=((om=n.loadingIndicator)==null?void 0:om.render)!==(F==null?void 0:F.render)||((sm=n.loadingIndicator)==null?void 0:sm.renderIdle)!==(F==null?void 0:F.renderIdle)||((am=n.loadingIndicator)==null?void 0:am.showBubble)!==(F==null?void 0:F.showBubble),$e=n.iterationDisplay!==U,Ge=((lm=(im=n.features)==null?void 0:im.showReasoning)!=null?lm:!0)!==(V!=null?V:!0)||((cm=(dm=n.features)==null?void 0:dm.showToolCalls)!=null?cm:!0)!==($!=null?$:!0)||JSON.stringify((pm=n.features)==null?void 0:pm.toolCallDisplay)!==JSON.stringify(De)||JSON.stringify((um=n.features)==null?void 0:um.reasoningDisplay)!==JSON.stringify(Ae);(ze||Fe||nt||D||$e||Ge)&&R&&(Qs++,zo(Ke,R.getMessages(),ve));let Re=(fm=n.launcher)!=null?fm:{},jt=(mm=Re.headerIconHidden)!=null?mm:!1,bt=(hm=(gm=n.layout)==null?void 0:gm.header)==null?void 0:hm.showIcon,br=jt||bt===!1,Hr=Re.headerIconName,Gt=(xm=Re.headerIconSize)!=null?xm:"48px";if(te){let ae=be.querySelector(".persona-border-b-persona-divider"),Ot=ae==null?void 0:ae.querySelector(".persona-flex-col");if(br)te.style.display="none",ae&&Ot&&!ae.contains(Ot)&&ae.insertBefore(Ot,ae.firstChild);else{if(te.style.display="",te.style.height=Gt,te.style.width=Gt,ae&&Ot&&(ae.contains(te)?te.nextSibling!==Ot&&(te.remove(),ae.insertBefore(te,Ot)):ae.insertBefore(te,Ot)),Hr){let At=parseFloat(Gt)||24,Ut=Pe(Hr,At*.6,"#ffffff",2);Ut?te.replaceChildren(Ut):te.textContent=(ym=Re.agentIconText)!=null?ym:"\u{1F4AC}"}else if(Re.iconUrl){let At=te.querySelector("img");if(At)At.src=Re.iconUrl,At.style.height=Gt,At.style.width=Gt;else{let Ut=document.createElement("img");Ut.src=Re.iconUrl,Ut.alt="",Ut.className="persona-rounded-xl persona-object-cover",Ut.style.height=Gt,Ut.style.width=Gt,te.replaceChildren(Ut)}}else{let At=te.querySelector("svg"),Ut=te.querySelector("img");(At||Ut)&&te.replaceChildren(),te.textContent=(bm=Re.agentIconText)!=null?bm:"\u{1F4AC}"}let tr=te.querySelector("img");tr&&(tr.style.height=Gt,tr.style.width=Gt)}}let Vr=(Cm=(wm=n.layout)==null?void 0:wm.header)==null?void 0:Cm.showTitle,Br=(Sm=(vm=n.layout)==null?void 0:vm.header)==null?void 0:Sm.showSubtitle;if(qe&&(qe.style.display=Vr===!1?"none":""),tt&&(tt.style.display=Br===!1?"none":""),I){((Tm=(Am=n.layout)==null?void 0:Am.header)==null?void 0:Tm.showCloseButton)===!1?I.style.display="none":I.style.display="";let Ot=(Mm=Re.closeButtonSize)!=null?Mm:"32px",tr=(km=Re.closeButtonPlacement)!=null?km:"inline";I.style.height=Ot,I.style.width=Ot;let{closeButtonWrapper:At}=Me,Ut=tr==="top-right",kr=At==null?void 0:At.classList.contains("persona-absolute");if(At&&Ut!==kr)if(At.remove(),Ut)At.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",be.style.position="relative",be.appendChild(At);else{let Mt=(Lm=(Em=Re.clearChat)==null?void 0:Em.placement)!=null?Lm:"inline",Er=(Im=(Pm=Re.clearChat)==null?void 0:Pm.enabled)!=null?Im:!0;At.className=Er&&Mt==="inline"?"":"persona-ml-auto";let sn=be.querySelector(".persona-border-b-persona-divider");sn&&sn.appendChild(At)}if(I.style.color=Re.closeButtonColor||en.actionIconColor,Re.closeButtonBackgroundColor?(I.style.backgroundColor=Re.closeButtonBackgroundColor,I.classList.remove("hover:persona-bg-gray-100")):(I.style.backgroundColor="",I.classList.add("hover:persona-bg-gray-100")),Re.closeButtonBorderWidth||Re.closeButtonBorderColor){let Mt=Re.closeButtonBorderWidth||"0px",Er=Re.closeButtonBorderColor||"transparent";I.style.border=`${Mt} solid ${Er}`,I.classList.remove("persona-border-none")}else I.style.border="",I.classList.add("persona-border-none");Re.closeButtonBorderRadius?(I.style.borderRadius=Re.closeButtonBorderRadius,I.classList.remove("persona-rounded-full")):(I.style.borderRadius="",I.classList.add("persona-rounded-full")),Re.closeButtonPaddingX?(I.style.paddingLeft=Re.closeButtonPaddingX,I.style.paddingRight=Re.closeButtonPaddingX):(I.style.paddingLeft="",I.style.paddingRight=""),Re.closeButtonPaddingY?(I.style.paddingTop=Re.closeButtonPaddingY,I.style.paddingBottom=Re.closeButtonPaddingY):(I.style.paddingTop="",I.style.paddingBottom="");let Ur=(Rm=Re.closeButtonIconName)!=null?Rm:"x",Nn=(Wm=Re.closeButtonIconText)!=null?Wm:"\xD7";I.innerHTML="";let Jr=Pe(Ur,"28px","currentColor",1);Jr?I.appendChild(Jr):I.textContent=Nn;let wr=(Hm=Re.closeButtonTooltipText)!=null?Hm:"Close chat",mn=(Bm=Re.closeButtonShowTooltip)!=null?Bm:!0;if(I.setAttribute("aria-label",wr),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),mn&&wr)){let Mt=null,Er=()=>{if(Mt||!I)return;let Yo=I.ownerDocument,ha=Yo.body;if(!ha)return;Mt=Yn(Yo,"div","persona-clear-chat-tooltip"),Mt.textContent=wr;let xa=Yn(Yo,"div");xa.className="persona-clear-chat-tooltip-arrow",Mt.appendChild(xa);let Qo=I.getBoundingClientRect();Mt.style.position="fixed",Mt.style.zIndex=String(Ro),Mt.style.left=`${Qo.left+Qo.width/2}px`,Mt.style.top=`${Qo.top-8}px`,Mt.style.transform="translate(-50%, -100%)",ha.appendChild(Mt)},sn=()=>{Mt&&Mt.parentNode&&(Mt.parentNode.removeChild(Mt),Mt=null)};At.addEventListener("mouseenter",Er),At.addEventListener("mouseleave",sn),I.addEventListener("focus",Er),I.addEventListener("blur",sn),At._cleanupTooltip=()=>{sn(),At&&(At.removeEventListener("mouseenter",Er),At.removeEventListener("mouseleave",sn)),I&&(I.removeEventListener("focus",Er),I.removeEventListener("blur",sn))}}}let{clearChatButton:ft,clearChatButtonWrapper:St}=Me;if(ft){let ae=(Dm=Re.clearChat)!=null?Dm:{},Ot=(Om=ae.enabled)!=null?Om:!0,tr=(Nm=(_m=n.layout)==null?void 0:_m.header)==null?void 0:Nm.showClearChat,At=tr!==void 0?tr:Ot,Ut=($m=ae.placement)!=null?$m:"inline";if(St){St.style.display=At?"":"none";let{closeButtonWrapper:kr}=Me;!B()&&kr&&!kr.classList.contains("persona-absolute")&&(At?kr.classList.remove("persona-ml-auto"):kr.classList.add("persona-ml-auto"));let Ur=Ut==="top-right",Nn=St.classList.contains("persona-absolute");if(!B()&&Ur!==Nn&&At){if(St.remove(),Ur)St.className="persona-absolute persona-top-4 persona-z-50",St.style.right="48px",be.style.position="relative",be.appendChild(St);else{St.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",St.style.right="";let wr=be.querySelector(".persona-border-b-persona-divider"),mn=Me.closeButtonWrapper;wr&&mn&&mn.parentElement===wr?wr.insertBefore(St,mn):wr&&wr.appendChild(St)}let Jr=Me.closeButtonWrapper;Jr&&!Jr.classList.contains("persona-absolute")&&(Ur?Jr.classList.add("persona-ml-auto"):Jr.classList.remove("persona-ml-auto"))}}if(At){if(!B()){let Mt=(Fm=ae.size)!=null?Fm:"32px";ft.style.height=Mt,ft.style.width=Mt}let kr=(Um=ae.iconName)!=null?Um:"refresh-cw",Ur=(zm=ae.iconColor)!=null?zm:"";ft.style.color=Ur||en.actionIconColor,ft.innerHTML="";let Nn=B()?"14px":"20px",Jr=Pe(kr,Nn,"currentColor",2);if(Jr&&ft.appendChild(Jr),ae.backgroundColor?(ft.style.backgroundColor=ae.backgroundColor,ft.classList.remove("hover:persona-bg-gray-100")):(ft.style.backgroundColor="",ft.classList.add("hover:persona-bg-gray-100")),ae.borderWidth||ae.borderColor){let Mt=ae.borderWidth||"0px",Er=ae.borderColor||"transparent";ft.style.border=`${Mt} solid ${Er}`,ft.classList.remove("persona-border-none")}else ft.style.border="",ft.classList.add("persona-border-none");ae.borderRadius?(ft.style.borderRadius=ae.borderRadius,ft.classList.remove("persona-rounded-full")):(ft.style.borderRadius="",ft.classList.add("persona-rounded-full")),ae.paddingX?(ft.style.paddingLeft=ae.paddingX,ft.style.paddingRight=ae.paddingX):(ft.style.paddingLeft="",ft.style.paddingRight=""),ae.paddingY?(ft.style.paddingTop=ae.paddingY,ft.style.paddingBottom=ae.paddingY):(ft.style.paddingTop="",ft.style.paddingBottom="");let wr=(qm=ae.tooltipText)!=null?qm:"Clear chat",mn=(jm=ae.showTooltip)!=null?jm:!0;if(ft.setAttribute("aria-label",wr),St&&(St._cleanupTooltip&&(St._cleanupTooltip(),delete St._cleanupTooltip),mn&&wr)){let Mt=null,Er=()=>{if(Mt||!ft)return;let Yo=ft.ownerDocument,ha=Yo.body;if(!ha)return;Mt=Yn(Yo,"div","persona-clear-chat-tooltip"),Mt.textContent=wr;let xa=Yn(Yo,"div");xa.className="persona-clear-chat-tooltip-arrow",Mt.appendChild(xa);let Qo=ft.getBoundingClientRect();Mt.style.position="fixed",Mt.style.zIndex=String(Ro),Mt.style.left=`${Qo.left+Qo.width/2}px`,Mt.style.top=`${Qo.top-8}px`,Mt.style.transform="translate(-50%, -100%)",ha.appendChild(Mt)},sn=()=>{Mt&&Mt.parentNode&&(Mt.parentNode.removeChild(Mt),Mt=null)};St.addEventListener("mouseenter",Er),St.addEventListener("mouseleave",sn),ft.addEventListener("focus",Er),ft.addEventListener("blur",sn),St._cleanupTooltip=()=>{sn(),St&&(St.removeEventListener("mouseenter",Er),St.removeEventListener("mouseleave",sn)),ft&&(ft.removeEventListener("focus",Er),ft.removeEventListener("blur",sn))}}}}let Gr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ri],Fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[hs.message,hs.messageAndClick];E=ni({parsers:Gr,handlers:Fr,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ve=ly(n,E,se),R.updateConfig(n),zo(Ke,R.getMessages(),ve),Wn.render(n.suggestionChips,R,Y,void 0,n.suggestionChipsConfig),aa(),ws(R.isStreaming());let Vo=((Vm=n.voiceRecognition)==null?void 0:Vm.enabled)===!0,Go=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ko=((Km=(Gm=n.voiceRecognition)==null?void 0:Gm.provider)==null?void 0:Km.type)==="runtype";if(Vo&&(Go||Ko))if(!X||!kt){let ae=As(n.voiceRecognition,n.sendButton);ae&&(X=ae.micButton,kt=ae.micButtonWrapper,zt.insertBefore(kt,Be),X.addEventListener("click",st),X.disabled=R.isStreaming())}else{let ae=(Jm=n.voiceRecognition)!=null?Jm:{},Ot=(Xm=n.sendButton)!=null?Xm:{},tr=(Ym=ae.iconName)!=null?Ym:"mic",At=(Qm=Ot.size)!=null?Qm:"40px",Ut=(Zm=ae.iconSize)!=null?Zm:At,kr=parseFloat(Ut)||24;X.style.width=Ut,X.style.height=Ut,X.style.minWidth=Ut,X.style.minHeight=Ut;let Ur=(tg=(eg=ae.iconColor)!=null?eg:Ot.textColor)!=null?tg:"currentColor";X.innerHTML="";let Nn=Pe(tr,kr,Ur,2);Nn?X.appendChild(Nn):X.textContent="\u{1F3A4}";let Jr=(rg=ae.backgroundColor)!=null?rg:Ot.backgroundColor;Jr?X.style.backgroundColor=Jr:X.style.backgroundColor="",Ur?X.style.color=Ur:X.style.color="var(--persona-text, #111827)",ae.borderWidth?(X.style.borderWidth=ae.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),ae.borderColor?X.style.borderColor=ae.borderColor:X.style.borderColor="",ae.paddingX?(X.style.paddingLeft=ae.paddingX,X.style.paddingRight=ae.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),ae.paddingY?(X.style.paddingTop=ae.paddingY,X.style.paddingBottom=ae.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let wr=kt==null?void 0:kt.querySelector(".persona-send-button-tooltip"),mn=(ng=ae.tooltipText)!=null?ng:"Start voice recognition";if(((og=ae.showTooltip)!=null?og:!1)&&mn)if(wr)wr.textContent=mn,wr.style.display="";else{let Er=document.createElement("div");Er.className="persona-send-button-tooltip",Er.textContent=mn,kt==null||kt.insertBefore(Er,X)}else wr&&(wr.style.display="none");kt.style.display="",X.disabled=R.isStreaming()}else X&&kt&&(kt.style.display="none",((ag=(sg=n.voiceRecognition)==null?void 0:sg.provider)==null?void 0:ag.type)==="runtype"?R.isVoiceActive()&&R.toggleVoice():un&&_n());if(((ig=n.attachments)==null?void 0:ig.enabled)===!0)if(!Jt||!ct){let ae=(lg=n.attachments)!=null?lg:{},tr=(cg=((dg=n.sendButton)!=null?dg:{}).size)!=null?cg:"40px";Se||(Se=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Se.style.display="none",ke.insertBefore(Se,Y)),fe||(fe=document.createElement("input"),fe.type="file",fe.accept=((pg=ae.allowedTypes)!=null?pg:mo).join(","),fe.multiple=((ug=ae.maxFiles)!=null?ug:4)>1,fe.style.display="none",fe.setAttribute("aria-label","Attach files"),ke.insertBefore(fe,Y)),Jt=x("div","persona-send-button-wrapper"),ct=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ct.type="button",ct.setAttribute("aria-label",(fg=ae.buttonTooltipText)!=null?fg:"Attach file");let At=(mg=ae.buttonIconName)!=null?mg:"paperclip",Ut=tr,kr=parseFloat(Ut)||40,Ur=Math.round(kr*.6);ct.style.width=Ut,ct.style.height=Ut,ct.style.minWidth=Ut,ct.style.minHeight=Ut,ct.style.fontSize="18px",ct.style.lineHeight="1",ct.style.backgroundColor="transparent",ct.style.color="var(--persona-primary, #111827)",ct.style.border="none",ct.style.borderRadius="6px",ct.style.transition="background-color 0.15s ease",ct.addEventListener("mouseenter",()=>{ct.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ct.addEventListener("mouseleave",()=>{ct.style.backgroundColor="transparent"});let Nn=Pe(At,Ur,"currentColor",1.5);Nn?ct.appendChild(Nn):ct.textContent="\u{1F4CE}",ct.addEventListener("click",mn=>{mn.preventDefault(),fe==null||fe.click()}),Jt.appendChild(ct);let Jr=(gg=ae.buttonTooltipText)!=null?gg:"Attach file",wr=x("div","persona-send-button-tooltip");wr.textContent=Jr,Jt.appendChild(wr),ht.append(Jt),!mt&&fe&&Se&&(mt=cs.fromConfig(ae),mt.setPreviewsContainer(Se),fe.addEventListener("change",async()=>{mt&&(fe!=null&&fe.files)&&(await mt.handleFileSelect(fe.files),fe.value="")})),be.querySelector(".persona-attachment-drop-overlay")||be.appendChild(dy(ae.dropOverlay))}else{Jt.style.display="";let ae=(hg=n.attachments)!=null?hg:{};fe&&(fe.accept=((xg=ae.allowedTypes)!=null?xg:mo).join(","),fe.multiple=((yg=ae.maxFiles)!=null?yg:4)>1),mt&&mt.updateConfig({allowedTypes:ae.allowedTypes,maxFileSize:ae.maxFileSize,maxFiles:ae.maxFiles})}else Jt&&(Jt.style.display="none"),mt&&mt.clearAttachments(),(bg=be.querySelector(".persona-attachment-drop-overlay"))==null||bg.remove();let pr=(wg=n.sendButton)!=null?wg:{},Jo=(Cg=pr.useIcon)!=null?Cg:!1,Po=(vg=pr.iconText)!=null?vg:"\u2191",Bt=pr.iconName,rn=(Sg=pr.tooltipText)!=null?Sg:"Send message",io=(Ag=pr.showTooltip)!=null?Ag:!1,Kr=(Tg=pr.size)!=null?Tg:"40px",nn=pr.backgroundColor,Yt=pr.textColor;if(Jo){if(Q.style.width=Kr,Q.style.height=Kr,Q.style.minWidth=Kr,Q.style.minHeight=Kr,Q.style.fontSize="18px",Q.style.lineHeight="1",Q.innerHTML="",Yt?Q.style.color=Yt:Q.style.color="var(--persona-button-primary-fg, #ffffff)",Bt){let ae=parseFloat(Kr)||24,Ot=(Yt==null?void 0:Yt.trim())||"currentColor",tr=Pe(Bt,ae,Ot,2);tr?Q.appendChild(tr):Q.textContent=Po}else Q.textContent=Po;Q.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nn?(Q.style.backgroundColor=nn,Q.classList.remove("persona-bg-persona-primary")):(Q.style.backgroundColor="",Q.classList.add("persona-bg-persona-primary"))}else Q.textContent=(kg=(Mg=n.copy)==null?void 0:Mg.sendButtonLabel)!=null?kg:"Send",Q.style.width="",Q.style.height="",Q.style.minWidth="",Q.style.minHeight="",Q.style.fontSize="",Q.style.lineHeight="",Q.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nn?(Q.style.backgroundColor=nn,Q.classList.remove("persona-bg-persona-accent")):Q.classList.add("persona-bg-persona-accent"),Yt?Q.style.color=Yt:Q.classList.add("persona-text-white");pr.borderWidth?(Q.style.borderWidth=pr.borderWidth,Q.style.borderStyle="solid"):(Q.style.borderWidth="",Q.style.borderStyle=""),pr.borderColor?Q.style.borderColor=pr.borderColor:Q.style.borderColor="",pr.paddingX?(Q.style.paddingLeft=pr.paddingX,Q.style.paddingRight=pr.paddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),pr.paddingY?(Q.style.paddingTop=pr.paddingY,Q.style.paddingBottom=pr.paddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let lr=Be==null?void 0:Be.querySelector(".persona-send-button-tooltip");if(io&&rn)if(lr)lr.textContent=rn,lr.style.display="";else{let ae=document.createElement("div");ae.className="persona-send-button-tooltip",ae.textContent=rn,Be==null||Be.insertBefore(ae,Q)}else lr&&(lr.style.display="none");let Qt=(Rg=(Eg=n.layout)==null?void 0:Eg.contentMaxWidth)!=null?Rg:B()?(Ig=(Pg=(Lg=n.launcher)==null?void 0:Lg.composerBar)==null?void 0:Pg.contentMaxWidth)!=null?Ig:"720px":void 0;Qt?(Ke.style.maxWidth=Qt,Ke.style.marginLeft="auto",Ke.style.marginRight="auto",Ke.style.width="100%",ke&&(ke.style.maxWidth=Qt,ke.style.marginLeft="auto",ke.style.marginRight="auto"),ne&&(ne.style.maxWidth=Qt,ne.style.marginLeft="auto",ne.style.marginRight="auto")):(Ke.style.maxWidth="",Ke.style.marginLeft="",Ke.style.marginRight="",Ke.style.width="",ke&&(ke.style.maxWidth="",ke.style.marginLeft="",ke.style.marginRight=""),ne&&(ne.style.maxWidth="",ne.style.marginLeft="",ne.style.marginRight=""));let ur=(Wg=n.statusIndicator)!=null?Wg:{},on=(Hg=ur.visible)!=null?Hg:!0;if(ge.style.display=on?"":"none",R){let ae=R.getStatus();ye(ge,(tr=>{var At,Ut,kr,Ur;return tr==="idle"?(At=ur.idleText)!=null?At:zr.idle:tr==="connecting"?(Ut=ur.connectingText)!=null?Ut:zr.connecting:tr==="connected"?(kr=ur.connectedText)!=null?kr:zr.connected:tr==="error"?(Ur=ur.errorText)!=null?Ur:zr.error:zr[tr]})(ae),ur,ae)}ge.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=ur.align==="left"?"persona-text-left":ur.align==="center"?"persona-text-center":"persona-text-right";ge.classList.add(fn)},open(){H()&&Kt(!0,"api")},close(){H()&&Kt(!1,"api")},toggle(){H()&&Kt(!W,"api")},clearChat(){Ee=!1,R.clearMessages(),Hn.clear(),So();try{localStorage.removeItem(Xs),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},E.syncFromMetadata(),j==null||j.clear(),Ce==null||Ce.reset(),Z==null||Z.update()},setMessage(c){return!Y||R.isStreaming()?!1:(!W&&H()&&Kt(!0,"system"),Y.value=c,Y.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(R.isStreaming())return!1;let g=(c==null?void 0:c.trim())||Y.value.trim();return g?(!W&&H()&&Kt(!0,"system"),Y.value="",Y.style.height="auto",R.sendMessage(g),!0):!1},startVoiceRecognition(){var g,C;return R.isStreaming()?!1:((C=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:C.type)==="runtype"?(R.isVoiceActive()||(!W&&H()&&Kt(!0,"system"),Pt.manuallyDeactivated=!1,tn(),R.toggleVoice().then(()=>{Pt.active=R.isVoiceActive(),Sn("user"),R.isVoiceActive()&&O()})),!0):un?!0:fa()?(!W&&H()&&Kt(!0,"system"),Pt.manuallyDeactivated=!1,tn(),jo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?R.isVoiceActive()?(R.toggleVoice().then(()=>{Pt.active=!1,Pt.manuallyDeactivated=!0,tn(),Sn("user"),re()}),!0):!1:un?(Pt.manuallyDeactivated=!0,tn(),_n("user"),!0):!1},injectMessage(c){return!W&&H()&&Kt(!0,"system"),R.injectMessage(c)},injectAssistantMessage(c){!W&&H()&&Kt(!0,"system");let g=R.injectAssistantMessage(c);return N&&(N=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),g},injectUserMessage(c){return!W&&H()&&Kt(!0,"system"),R.injectUserMessage(c)},injectSystemMessage(c){return!W&&H()&&Kt(!0,"system"),R.injectSystemMessage(c)},injectMessageBatch(c){return!W&&H()&&Kt(!0,"system"),R.injectMessageBatch(c)},injectComponentDirective(c){return!W&&H()&&Kt(!0,"system"),R.injectComponentDirective(c)},injectTestMessage(c){!W&&H()&&Kt(!0,"system"),R.injectTestEvent(c)},async connectStream(c,g){return R.connectStream(c,g)},__pushEventStreamEvent(c){j&&(Ce==null||Ce.processEvent(c.type,c.payload),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!we||!j||Lr()},hideEventStream(){he&&_r()},isEventStreamVisible(){return he},showArtifacts(){Ln(n)&&(Ee=!1,ln(),me==null||me.setMobileOpen(!0))},hideArtifacts(){Ln(n)&&(Ee=!0,ln())},upsertArtifact(c){return Ln(n)?(Ee=!1,R.upsertArtifact(c)):null},selectArtifact(c){Ln(n)&&R.selectArtifact(c)},clearArtifacts(){Ln(n)&&R.clearArtifacts()},getArtifacts(){var c;return(c=R==null?void 0:R.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=R==null?void 0:R.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!W&&!B()||!Y?!1:(Y.focus(),!0)},async resolveApproval(c,g){let S=R.getMessages().find(_=>{var F;return _.variant==="approval"&&((F=_.approval)==null?void 0:F.id)===c});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${c}`);if(S.approval.toolType==="webmcp"){R.resolveWebMcpApproval(S.id,g);return}return R.resolveApproval(S.approval,g)},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return H()&&W},isVoiceActive(){return Pt.active},getState(){return{open:H()&&W,launcherEnabled:T,voiceActive:Pt.active,streaming:R.isStreaming()}},showCSATFeedback(c){!W&&H()&&Kt(!0,"system");let g=Ke.querySelector(".persona-feedback-container");g&&g.remove();let C=Zl({onSubmit:async(S,_)=>{var F;R.isClientTokenMode()&&await R.submitCSATFeedback(S,_),(F=c==null?void 0:c.onSubmit)==null||F.call(c,S,_)},onDismiss:c==null?void 0:c.onDismiss,...c});Ke.appendChild(C),C.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!W&&H()&&Kt(!0,"system");let g=Ke.querySelector(".persona-feedback-container");g&&g.remove();let C=ed({onSubmit:async(S,_)=>{var F;R.isClientTokenMode()&&await R.submitNPSFeedback(S,_),(F=c==null?void 0:c.onSubmit)==null||F.call(c,S,_)},onDismiss:c==null?void 0:c.onDismiss,...c});Ke.appendChild(C),C.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return R.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return R.submitNPSFeedback(c,g)},destroy(){jn!=null&&(clearInterval(jn),jn=null),It.forEach(c=>c()),pe.remove(),Ye==null||Ye.remove(),lt==null||lt.destroy(),ut==null||ut.remove(),cn&&I.removeEventListener("click",cn)}};if((((Wf=r==null?void 0:r.debugTools)!=null?Wf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Sr,getMessages:Sr.getMessages,getStatus:Sr.getStatus,getMetadata:Sr.getPersistentMetadata,updateMetadata:Sr.updatePersistentMetadata,clearHistory:()=>Sr.clearChat(),setVoiceActive:C=>C?Sr.startVoiceRecognition():Sr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,It.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Sr.focusInput()};if(window.addEventListener("persona:focusInput",g),It.push(()=>{window.removeEventListener("persona:focusInput",g)}),we){let V=De=>{let Ae=De.detail;(!(Ae!=null&&Ae.instanceId)||Ae.instanceId===c)&&Sr.showEventStream()},$=De=>{let Ae=De.detail;(!(Ae!=null&&Ae.instanceId)||Ae.instanceId===c)&&Sr.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",$),It.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",$)})}let C=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Sr.showArtifacts()},S=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Sr.hideArtifacts()},_=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==c||$!=null&&$.artifact&&Sr.upsertArtifact($.artifact)},F=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==c||typeof($==null?void 0:$.id)=="string"&&Sr.selectArtifact($.id)},U=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Sr.clearArtifacts()};window.addEventListener("persona:showArtifacts",C),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",_),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",U),It.push(()=>{window.removeEventListener("persona:showArtifacts",C),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",_),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",U)})}let Tn=Iv(n.persistState);if(Tn&&H()){let c=Rv(Tn.storage),g=`${Tn.keyPrefix}widget-open`,C=`${Tn.keyPrefix}widget-voice`,S=`${Tn.keyPrefix}widget-voice-mode`;if(c){let _=((Hf=Tn.persist)==null?void 0:Hf.openState)&&c.getItem(g)==="true",F=((Bf=Tn.persist)==null?void 0:Bf.voiceState)&&c.getItem(C)==="true",U=((Df=Tn.persist)==null?void 0:Df.voiceState)&&c.getItem(S)==="true";if(_&&setTimeout(()=>{Sr.open(),setTimeout(()=>{var V;if(F||U)Sr.startVoiceRecognition();else if((V=Tn.persist)!=null&&V.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),(Of=Tn.persist)!=null&&Of.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(_f=Tn.persist)!=null&&_f.voiceState&&(s.on("voice:state",V=>{c.setItem(C,V.active?"true":"false")}),s.on("user:message",V=>{c.setItem(S,V.viaVoice?"true":"false")})),Tn.clearOnChatClear){let V=()=>{c.removeItem(g),c.removeItem(C),c.removeItem(S)},$=()=>V();window.addEventListener("persona:clear-chat",$),It.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return p&&H()&&setTimeout(()=>{Sr.open()},0),so(),Sr};var Wv=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},cy=(e,t)=>{var n,o;let r=(o=(n=t==null?void 0:t.launcher)==null?void 0:n.enabled)!=null?o:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},vu=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},py=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",vu(e)},bu=e=>{e.style.transition=""},wu=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Cu=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},nd=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Hv=(e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))},Bv=(e,t,r,n,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==n&&a.replaceChildren(n,r):a.lastElementChild!==n&&a.replaceChildren(r,n)},uy=(e,t,r,n,o,s,a)=>{var y,v,E,T,A,M;let i=kn(s),d=i.reveal==="push";Hv(e,t,r,n,d),Bv(e,t,r,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(v=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?v:!0,u=(T=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?T:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),wu(t),bu(n),py(n),Cu(r),nd(o,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((M=(A=s==null?void 0:s.launcher)==null?void 0:A.zIndex)!=null?M:qr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),py(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",wu(t),bu(n),Cu(r),nd(o,n);let b=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",h=a?"translateX(0)":w;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=b,n.style.transform=h,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",bu(n),vu(n),nd(o,n);let b=Wv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),h=i.animate?"transform 180ms ease":"none",k=i.side==="right"?a?`translateX(-${b}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${b}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${w+b}px`,t.style.transition=h,t.style.transform=k,r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",wu(t),vu(n),Cu(r),nd(o,n);let b=i.reveal==="emerge";b?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=a?i.width:"0px",h=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",k=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${w}`,n.style.width=w,n.style.maxWidth=w,n.style.minWidth=w,n.style.minHeight="0",n.style.position="relative",n.style.overflow=b||k?"hidden":"visible",n.style.transition=h,b&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Dv=(e,t)=>{let r=e.ownerDocument.createElement("div");return cy(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){cy(r,n)},destroy(){r.remove()}}},Ov=(e,t)=>{var A,M,b,w;let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=r.createElement("div"),i=r.createElement("div"),d=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),u=(M=(A=t==null?void 0:t.launcher)==null?void 0:A.enabled)==null||M?(w=(b=t==null?void 0:t.launcher)==null?void 0:b.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},y=()=>{m(),kn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{uy(a,i,d,l,p,t,u)}),f.observe(a))},v=()=>{uy(a,i,d,l,p,t,u),y()},E=a.ownerDocument.defaultView,T=()=>{v()};return E==null||E.addEventListener("resize",T),kn(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:p,shell:a,syncWidgetState(h){let k=h.launcherEnabled?h.open:!0;u!==k&&(u=k,v())},updateConfig(h){var k,B;t=h,((B=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)!=null?B:!0)===!1&&(u=!0),v()},destroy(){E==null||E.removeEventListener("resize",T),m(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(e,s):n.appendChild(e)),a.remove()}}},oi=(e,t)=>Tr(t)?Ov(e,t):Dv(e,t);var Su={},_v=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Nv=()=>{try{if(typeof Su!="undefined"&&Su.url)return new URL("../widget.css",Su.url).href}catch{}return null},fy=(e,t)=>{let r=Nv(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(r){let o=t.createElement("link");o.rel="stylesheet",o.href=r,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else n();else if(!t.head.querySelector("link[data-persona]")&&r){let s=t.createElement("link");s.rel="stylesheet",s.href=r,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},my=e=>{var E;let t=_v(e.target),r=e.useShadowDom===!0,n=t.ownerDocument,o=e.config,s=oi(t,o),a,i=[],d=(T,A)=>{var h,k;let b=!((k=(h=A==null?void 0:A.launcher)==null?void 0:h.enabled)!=null?k:!0)||Tr(A),w=n.createElement("div");if(w.setAttribute("data-persona-root","true"),b&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0"),r){let B=T.attachShadow({mode:"open"});B.appendChild(w),fy(B,n)}else T.appendChild(w),fy(T,n);return t.id&&w.setAttribute("data-persona-instance",t.id),w},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let T=d(s.host,o);a=rd(T,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(E=e.onReady)==null||E.call(e);let m=T=>{f(),s.destroy(),s=oi(t,T),o=T,u()},y={update(T){var k,B,H,W,N,q;let A={...o,...T,launcher:{...(k=o==null?void 0:o.launcher)!=null?k:{},...(B=T==null?void 0:T.launcher)!=null?B:{},dock:{...(W=(H=o==null?void 0:o.launcher)==null?void 0:H.dock)!=null?W:{},...(q=(N=T==null?void 0:T.launcher)==null?void 0:N.dock)!=null?q:{}}}},M=Tr(o),b=Tr(A),w=Ho(o),h=Ho(A);if(M!==b||w!==h){m(A);return}o=A,s.updateConfig(o),a.update(T),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(y,{get(T,A,M){if(A==="host")return s.host;if(A in T)return Reflect.get(T,A,M);let b=a[A];return typeof b=="function"?b.bind(a):b}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var by=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$v=new Set(["button","a","input","select","textarea","details","summary"]),Fv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Au=/\b(product|card|item|listing|result)\b/i,Mu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Uv=3e3,zv=100;function wy(e){let t=typeof e.className=="string"?e.className:"";if(Au.test(t)||e.id&&Au.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];if(n.name.startsWith("data-")&&Au.test(n.value))return!0}return!1}function Cy(e){var t;return Mu.test(((t=e.textContent)!=null?t:"").trim())}function vy(e){var r;let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=(r=t[n].getAttribute("href"))!=null?r:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function qv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function gy(e){let t=e.match(Mu);return t?t[0]:null}function hy(e){var n,o,s;let t=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=r==null?void 0:r.textContent)!=null&&s.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function jv(e){let t=[],r=n=>{let o=n.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;r((o=n.value)!=null?o:"")}),t.slice(0,6)}var Vv="commerce-card",Gv="result-card";function xy(e){return!wy(e)||!Cy(e)||!vy(e)&&!qv(e)?0:5200}function yy(e){var n;return!wy(e)||Cy(e)||!vy(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var ku=[{id:Vv,scoreElement(e){return xy(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let n=r.text.trim();return!!(n.length===0||Mu.test(n)&&n.length<32)}return!0},formatSummary(e,t){var d,l,p;if(xy(e)===0)return null;let{title:r,href:n}=hy(e),o=(p=(l=gy(((d=e.textContent)!=null?d:"").trim()))!=null?l:gy(t.text))!=null?p:"",s=jv(e);return[n&&r?`[${r}](${n})${o?` \u2014 ${o}`:""}`:r?`${r}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
158
- `)}},{id:Gv,scoreElement(e){return yy(e)},formatSummary(e,t){if(yy(e)===0)return null;let{title:r,href:n}=hy(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
159
- `)}}];function Kv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Jv(e){var p,u,f,m,y,v,E,T,A,M,b,w,h;let t=(p=e.options)!=null?p:{},r=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,n=(y=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?y:".persona-host",o=(E=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,s=(A=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?A:!0,a=(M=t.root)!=null?M:e.root,i=(b=t.mode)!=null?b:"structured",d=(w=t.maxCandidates)!=null?w:Math.max(500,r*10),l=(h=e.rules)!=null?h:ku;return i==="simple"&&e.rules&&e.rules.length>0?(Kv(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Tu(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Xv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Yv(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":t==="button"||r==="button"||$v.has(t)||r&&Fv.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Sy(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Qv(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Eu(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Tu(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Xv){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Tu(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let r=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${t}.${r.map(a=>Tu(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=e.parentElement;if(n){let s=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Zv(e){return e==="static"?zv:Uv}function Ay(e,t){var o;let r=e.tagName.toLowerCase(),n=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:Eu(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:Yv(e),attributes:Qv(e)}}function eS(e,t,r,n){let o=Zv(t.interactivity),s=null;for(let a of r){let i=a.scoreElement(e,t,n);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function tS(e,t){var r;for(let n of e)if(t.el!==n.el&&(r=n.formattingRule)!=null&&r.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function rS(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(by.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Sy(l)){i=a.nextNode();continue}let u=Ay(l,e.maxTextLength),f=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(u.selector)){i=a.nextNode();continue}n.add(u.selector);let{score:y,formattingRule:v}=eS(l,u,e.rules,r);o.push({el:l,domIndex:s,enriched:u,score:y,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;tS(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,r);m&&(p=m)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function nS(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&r.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(by.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Sy(d)){s=o.nextNode();continue}let p=Ay(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!f){s=o.nextNode();continue}n.has(p.selector)||(n.add(p.selector),r.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of r)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Ty(e={}){var n;let t=Jv(e),r=(n=t.root)!=null?n:document.body;return r?t.mode==="simple"?nS(t,r):rS(t,r):[]}var od=100;function My(e,t={}){var s;if(e.length===0)return"No page elements found.";let r=(s=t.mode)!=null?s:"structured",n=[];if(r==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
157
+ `}if(!C&&!c){let Zt="max-height: -moz-available !important; max-height: stretch !important;",pr=g?"":"padding-top: 1.25em !important;",on=g?"":`z-index: ${(ir=(Yt=n.launcher)==null?void 0:Yt.zIndex)!=null?ir:zr} !important;`;Ce.style.cssText+=Zt+pr+on}H()};Rn(),Io(t,n),zl(t,n),ql(t,n);let Pt=[];Pt.push(()=>{document.removeEventListener("keydown",wn)});let gr=null,hr=null;Pt.push(()=>{gr==null||gr(),gr=null,hr==null||hr(),hr=null}),P&&Pt.push(()=>{P==null||P.disconnect(),P=null}),Pt.push(()=>{Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue==null||ue.element.style.removeProperty("width"),ue==null||ue.element.style.removeProperty("maxWidth")}),ve&&Pt.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),ae==null||ae.destroy(),ae=null,K==null||K.destroy(),K=null,X=null});let dn=null,vo=()=>{dn&&(dn(),dn=null),n.colorScheme==="auto"&&(dn=bl(()=>{Io(t,n)}))};vo(),Pt.push(()=>{dn&&(dn(),dn=null)});let Cn=(gf=n.features)==null?void 0:gf.streamAnimation;if(Cn!=null&&Cn.type&&Cn.type!=="none"){let c=$s(Cn.type,Cn.plugins);c&&(_p(c,t),Pt.push(()=>lx(t)))}let Wn=Rx(Z),cn=null,I,pn=!1,Bn=rx(),to=new Map,qn=new Map,Xa=0,Hn=Cl(),Dn=0,On=null,ro=!1,Fo=!1,ri=4,Ja=24,ni=80,ha=new Map,Lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Qa=(xf=(hf=n.voiceRecognition)==null?void 0:hf.autoResume)!=null?xf:!1,An=c=>{s.emit("voice:state",{active:Lt.active,source:c,timestamp:Date.now()})},tn=()=>{f(c=>({...c,voiceState:{active:Lt.active,timestamp:Date.now(),manuallyDeactivated:Lt.manuallyDeactivated}}))},oi=()=>{var C,D;if(((C=n.voiceRecognition)==null?void 0:C.enabled)===!1)return;let c=cu(d.voiceState),g=!!c.active,w=Number((D=c.timestamp)!=null?D:0);Lt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-w<sC&&setTimeout(()=>{var $,U;Lt.active||(Lt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),An("restore"),I.isVoiceActive()&&z()}):qo("restore"))},1e3)},ai=()=>I?Qx(I.getMessages()).filter(c=>!c.__skipPersist):[];function xa(c){if(!(i!=null&&i.save))return;let w={messages:c?Qx(c):I?ai():[],metadata:d,artifacts:ee.artifacts,selectedArtifactId:ee.selectedId};try{let C=i.save(w);C instanceof Promise&&C.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let no=null,si=()=>Ce.querySelector("#persona-scroll-container")||J,$o=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ro=!1},Ya=()=>{On!==null&&(cancelAnimationFrame(On),On=null),Fo=!1,$o()},oo=()=>{if(!mr()||xe){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==me&&me.appendChild(Ot),Et();let c=Os(J)>0;Ot.style.display=Hn.isFollowing()||!c?"none":""},Za=()=>{Hn.pause()&&(Ya(),oo())},Co=()=>{Hn.resume(),oo()},Ao=(c=!1)=>{Hn.isFollowing()&&(!c&&!pn||(On!==null&&(cancelAnimationFrame(On),On=null),Fo=!0,On=requestAnimationFrame(()=>{On=null,Fo=!1,Hn.isFollowing()&&ii(si(),c?220:140)})))},ii=(c,g=500)=>{let w=c.scrollTop,C=Os(c),D=C-w;if(Math.abs(D)<1){Dn=c.scrollTop;return}if(Math.abs(D)>=ni){$o(),ro=!0,c.scrollTop=C,Dn=c.scrollTop,ro=!1;return}$o();let $=performance.now();ro=!0;let U=F=>1-Math.pow(1-F,3),j=F=>{if(!Hn.isFollowing()){$o();return}let We=Os(c);We!==C&&(C=We,D=C-w);let we=F-$,ie=Math.min(we/g,1),Le=U(ie),De=w+D*Le;c.scrollTop=De,Dn=c.scrollTop,ie<1?no=requestAnimationFrame(j):(c.scrollTop=C,Dn=c.scrollTop,no=null,ro=!1)};no=requestAnimationFrame(j)},li=c=>{let g=new Map;c.forEach(w=>{let C=ha.get(w.id);g.set(w.id,{streaming:w.streaming,role:w.role}),!C&&w.role==="assistant"&&s.emit("assistant:message",w),w.role==="assistant"&&(C!=null&&C.streaming)&&w.streaming===!1&&s.emit("assistant:complete",w),w.variant==="approval"&&w.approval&&(C?w.approval.status!=="pending"&&s.emit("approval:resolved",{approval:w.approval,decision:w.approval.status}):s.emit("approval:requested",{approval:w.approval,message:w}))}),ha.clear(),g.forEach((w,C)=>{ha.set(C,w)})},Uo=(c,g,w)=>{var dt,wt,vt,ze,$e,nt;let C=document.createElement("div"),$=(()=>{var Oe;let H=o.find(Je=>Je.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),U=(H,Oe)=>Oe==null?!1:typeof Oe=="string"?(H.textContent=Oe,!0):(H.appendChild(Oe),!0),j=new Set,F=new Set,We=o.some(H=>H.renderAskUserQuestion),we=[],ie=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(H=>{var jr,Br,pt,Ct,Gr,Fr,Vo,jo,Go,Aa,Sa,cr,Ko,Po;j.add(H.id);let Oe=We&&ho(H),Je=!Oe&&H.role==="assistant"&&!H.variant&&Le&&Kl(H);if(!Je&&qn.has(H.id)){let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime"),qn.delete(H.id)}let it=ho(H)?`:${(jr=H.agentMetadata)!=null&&jr.askUserQuestionAnswered?"a":"u"}:${(Br=H.agentMetadata)!=null&&Br.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Pe=tx(H,Xa)+it,qt=Oe||Je?null:nx(Bn,H.id,Pe);if(qt){C.appendChild(qt.cloneNode(!0)),ho(H)&&((pt=H.toolCall)!=null&&pt.id)&&((Ct=H.agentMetadata)==null?void 0:Ct.awaitingLocalTool)===!0&&!((Gr=H.agentMetadata)!=null&&Gr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),qa(H,n,Ne.composerOverlay));return}let bt=null,yr=o.find(Bt=>!!(H.variant==="reasoning"&&Bt.renderReasoning||H.variant==="tool"&&Bt.renderToolCall||H.variant==="approval"&&Bt.renderApproval||!H.variant&&Bt.renderMessage)),Wr=(Fr=n.layout)==null?void 0:Fr.messages;if(ho(H)&&((Vo=H.agentMetadata)==null?void 0:Vo.askUserQuestionAnswered)===!0){to.delete(H.id);let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime");return}if(ho(H)&&((Go=(jo=n.features)==null?void 0:jo.askUserQuestion)==null?void 0:Go.enabled)!==!1){let Bt=o.find(rn=>typeof rn.renderAskUserQuestion=="function");if(Bt&&rt.current){let rn=to.get(H.id),io=rn!==Pe,Kr=null;if(io){let{payload:ir,complete:Zt}=xo(H),pr=H.id,on=()=>{var fn;return(fn=rt.current)==null?void 0:fn.getMessages().find(Cr=>Cr.id===pr)};Kr=Bt.renderAskUserQuestion({message:H,payload:ir,complete:Zt,resolve:fn=>{var jn;let Cr=on();Cr&&((jn=rt.current)==null||jn.resolveAskUserQuestion(Cr,fn))},dismiss:()=>{var Cr,jn,lo;let fn=on();(Cr=fn==null?void 0:fn.agentMetadata)!=null&&Cr.awaitingLocalTool&&((jn=rt.current)==null||jn.markAskUserQuestionResolved(fn),(lo=rt.current)==null||lo.resolveAskUserQuestion(fn,"(dismissed)"))},config:n})}let nn=rn!=null;if(io&&Kr===null&&!nn){((Aa=H.agentMetadata)==null?void 0:Aa.awaitingLocalTool)===!0&&!((Sa=H.agentMetadata)!=null&&Sa.askUserQuestionAnswered)&&(F.add(H.toolCall.id),qa(H,n,Ne.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),C.appendChild(Yt),we.push({messageId:H.id,fingerprint:Pe,bubble:Kr});return}else{((cr=H.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Ko=H.agentMetadata)!=null&&Ko.askUserQuestionAnswered)&&(F.add(H.toolCall.id),qa(H,n,Ne.composerOverlay));return}}else if(yr)if(H.variant==="reasoning"&&H.reasoning&&yr.renderReasoning){if(!Qe)return;bt=yr.renderReasoning({message:H,defaultRenderer:()=>Kp(H,n),config:n})}else if(H.variant==="tool"&&H.toolCall&&yr.renderToolCall){if(!je)return;bt=yr.renderToolCall({message:H,defaultRenderer:()=>Xp(H,n),config:n})}else if(H.variant==="approval"&&H.approval&&yr.renderApproval){if(n.approval===!1)return;bt=yr.renderApproval({message:H,defaultRenderer:()=>nu(H,n),config:n})}else yr.renderMessage&&(bt=yr.renderMessage({message:H,defaultRenderer:()=>{let Bt=Na(H,w,Wr,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n});return H.role!=="user"&&iu(Bt,H,n,I),Bt},config:n}));if(!bt&&Je){let Bt=Xl(H);if(Bt){let rn=qn.get(H.id),io=rn!==Pe,Kr=n.wrapComponentDirectiveInBubble!==!1,nn=null;if(io){let Yt=Gl(Bt,{config:n,message:H,transform:w});if(Yt)if(Kr){let ir=document.createElement("div");if(ir.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Zt.innerHTML=w({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}else{let ir=document.createElement("div");if(ir.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),ir.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Zt.innerHTML=w({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}}if(nn||rn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),Kr||Yt.classList.add("persona-w-full"),C.appendChild(Yt),ie.push({messageId:H.id,fingerprint:Pe,bubble:nn});return}}}if(!bt)if(H.variant==="reasoning"&&H.reasoning){if(!Qe)return;bt=Kp(H,n)}else if(H.variant==="tool"&&H.toolCall){if(!je)return;bt=Xp(H,n)}else if(H.variant==="approval"&&H.approval){if(n.approval===!1)return;bt=nu(H,n)}else{let Bt=(Po=n.layout)==null?void 0:Po.messages;Bt!=null&&Bt.renderUserMessage&&H.role==="user"?bt=Bt.renderUserMessage({message:H,config:n,streaming:!!H.streaming}):Bt!=null&&Bt.renderAssistantMessage&&H.role==="assistant"?bt=Bt.renderAssistantMessage({message:H,config:n,streaming:!!H.streaming}):bt=Na(H,w,Bt,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n}),H.role!=="user"&&bt&&iu(bt,H,n,I)}let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-${H.id}`,Gt.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Gt.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&Gt.classList.add("persona-w-full"),Gt.appendChild(bt),ox(Bn,H.id,Pe,Gt),C.appendChild(Gt)}),Ne.composerOverlay&&Ne.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Je=Oe.getAttribute("data-persona-ask-sheet-for");Je&&!F.has(Je)&&_o(Ne.composerOverlay,Je)}),(wt=(dt=n.features)==null?void 0:dt.toolCallDisplay)!=null&&wt.grouped){let H=[],Oe=[];g.forEach(Je=>{if(Je.variant==="tool"&&Je.toolCall&&je){Oe.push(Je);return}Oe.length>1&&H.push(Oe),Oe=[]}),Oe.length>1&&H.push(Oe),H.forEach((Je,it)=>{var Br,pt;let Pe=Je.map(Ct=>Array.from(C.children).find(Gr=>Gr instanceof HTMLElement&&Gr.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(Pe.length<2)return;let qt=document.createElement("div");qt.className="persona-flex",qt.id=`wrapper-tool-group-${it}-${Je[0].id}`,qt.setAttribute("data-wrapper-id",`tool-group-${it}-${Je[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let yr=document.createElement("div");yr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Wr=`Called ${Je.length} tools`,Gt=(pt=(Br=n.toolCall)==null?void 0:Br.renderGroupedSummary)==null?void 0:pt.call(Br,{messages:Je,toolCalls:Je.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:Wr,config:n});U(yr,Gt)||(yr.textContent=Wr);let jr=document.createElement("div");jr.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(yr,jr),qt.appendChild(bt),Pe[0].before(qt),Pe.forEach((Ct,Gr)=>{let Fr=document.createElement("div");Fr.className="persona-tool-group-item persona-relative",Fr.setAttribute("data-persona-tool-group-item","true"),Gr<Pe.length-1&&Fr.setAttribute("data-persona-tool-group-connector","true"),Fr.appendChild(Ct),jr.appendChild(Fr)})})}ax(Bn,j);let De=g.some(H=>H.role==="assistant"&&H.streaming),Ye=g[g.length-1],ht=(Ye==null?void 0:Ye.role)==="assistant"&&!Ye.streaming&&Ye.variant!=="approval";if(pn&&g.some(H=>H.role==="user")&&!De&&!ht){let H={config:n,streaming:!0,location:"standalone",defaultRenderer:ua},Oe=o.find(it=>it.renderLoadingIndicator),Je=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Je=Oe.renderLoadingIndicator(H)),Je===null&&((vt=n.loadingIndicator)!=null&&vt.render)&&(Je=n.loadingIndicator.render(H)),Je===null&&(Je=ua()),Je){let it=document.createElement("div"),Pe=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;it.className=Pe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),it.setAttribute("data-typing-indicator","true"),it.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",it.appendChild(Je);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-typing-indicator",qt.setAttribute("data-wrapper-id","typing-indicator"),qt.appendChild(it),C.appendChild(qt)}}if(!pn&&g.length>0){let H=g[g.length-1],Oe={config:n,lastMessage:H,messageCount:g.length},Je=o.find(Pe=>Pe.renderIdleIndicator),it=null;if(Je!=null&&Je.renderIdleIndicator&&(it=Je.renderIdleIndicator(Oe)),it===null&&(($e=n.loadingIndicator)!=null&&$e.renderIdle)&&(it=n.loadingIndicator.renderIdle(Oe)),it){let Pe=document.createElement("div"),qt=((nt=n.loadingIndicator)==null?void 0:nt.showBubble)!==!1;Pe.className=qt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(it);let bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Pe),C.appendChild(bt)}}if(wl(c,C),we.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Je}of we){let it=c.querySelector(`#wrapper-${H}`);it&&Je!==null&&(it.replaceChildren(Je),it.setAttribute("data-bubble-fp",Oe),to.set(H,Oe))}if(to.size>0)for(let H of to.keys())j.has(H)||to.delete(H);if(ie.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Je}of ie){let it=c.querySelector(`#wrapper-${H}`);it&&Je!==null&&(it.replaceChildren(Je),it.setAttribute("data-bubble-fp",Oe),qn.set(H,Oe))}if(qn.size>0)for(let H of qn.keys())j.has(H)||qn.delete(H)},So=null,di=()=>{var w;if(So)return;let c=C=>{let D=C.composedPath();D.includes(Ce)||tt&&D.includes(tt)||Kt(!1,"user")};So=c,((w=t.ownerDocument)!=null?w:document).addEventListener("pointerdown",c,!0)},es=()=>{var g;if(!So)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("pointerdown",So,!0),So=null};Pt.push(()=>es());let To=null,ci=()=>{var w;if(To)return;let c=C=>{C.key==="Escape"&&(C.isComposing||Kt(!1,"user"))};To=c,((w=t.ownerDocument)!=null?w:document).addEventListener("keydown",c,!0)},ts=()=>{var g;if(!To)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("keydown",To,!0),To=null};Pt.push(()=>ts());let Mo=!1,rs=new Set,pi=()=>{var g,w,C,D;let c=(C=(w=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:w.peek)==null?void 0:C.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},ao=()=>{var wt,vt,ze,$e;if(!W())return;let c=Ne.peekBanner,g=Ne.peekTextNode;if(!c||!g)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let w=(wt=I==null?void 0:I.getMessages())!=null?wt:[],C;for(let nt=w.length-1;nt>=0;nt--){let H=w[nt];if(H.role==="assistant"&&H.content){C=H;break}}if(!C){c.classList.remove("persona-pill-peek--visible");return}let D=C.content,$=!!C.streaming,U=pi(),j=Tl(U),F=j.type!=="none"?$s(j.type,U==null?void 0:U.plugins):null,We=((vt=F==null?void 0:F.isAnimating)==null?void 0:vt.call(F,C))===!0,we=F!==null&&($||We);we&&F&&!rs.has(F.name)&&(_p(F,t),rs.add(F.name));let ie=we&&(F!=null&&F.containerClass)?F.containerClass:null,Le=(ze=g.dataset.personaPeekStreamClass)!=null?ze:null;Le&&Le!==ie&&(g.classList.remove(Le),delete g.dataset.personaPeekStreamClass),ie&&Le!==ie&&(g.classList.add(ie),g.dataset.personaPeekStreamClass=ie),we?(g.style.setProperty("--persona-stream-step",`${j.speed}ms`),g.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let De=we?Ml(D,j.buffer,F,C,$):D;if(we&&j.placeholder==="skeleton"&&$&&(!De||!De.trim())){let nt=document.createElement("div"),H=zs();H.classList.add("persona-pill-peek__skeleton"),nt.appendChild(H),wl(g,nt)}else{let nt=Math.max(0,De.length-100),H=De.length>100?De.slice(-100):De,Oe=na(H);if(!we||!F){let Je=De.length>100?`\u2026${H}`:H;g.textContent!==Je&&(g.textContent=Je)}else{let Je=Oe;(F.wrap==="char"||F.wrap==="word")&&(Je=Us(Oe,F.wrap,`peek-${C.id}`,{skipTags:F.skipTags,startIndex:nt}));let it=document.createElement("div");if(it.innerHTML=Je,F.useCaret&&H.length>0){let Pe=kl(),qt=it.querySelectorAll(".persona-stream-char, .persona-stream-word"),bt=qt[qt.length-1];bt!=null&&bt.parentNode?bt.parentNode.insertBefore(Pe,bt.nextSibling):it.appendChild(Pe)}wl(g,it),($e=F.onAfterRender)==null||$e.call(F,{container:g,bubble:c,messageId:C.id,message:C,speed:j.speed,duration:j.duration})}}let dt=pn||Mo;c.classList.toggle("persona-pill-peek--visible",dt)};if(W()){let c=Ne.peekBanner;if(c){let C=D=>{D.preventDefault(),D.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",C),Pt.push(()=>{c.removeEventListener("pointerdown",C)})}let g=()=>{Mo||(Mo=!0,ao())},w=()=>{Mo&&(Mo=!1,ao())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",w),Pt.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",w)}),tt&&(tt.addEventListener("pointerenter",g),tt.addEventListener("pointerleave",w),Pt.push(()=>{tt.removeEventListener("pointerenter",g),tt.removeEventListener("pointerleave",w)}))}let ui=c=>{var Le,De,Ye,ht,dt,wt,vt,ze;let g=(De=(Le=n.launcher)==null?void 0:Le.composerBar)!=null?De:{},w=(Ye=g.expandedSize)!=null?Ye:"anchored",C=(ht=g.bottomOffset)!=null?ht:"16px",D=g.collapsedMaxWidth,$=(dt=g.expandedMaxWidth)!=null?dt:"880px",U=(wt=g.expandedTopOffset)!=null?wt:"5vh",j=(vt=g.modalMaxWidth)!=null?vt:"880px",F=(ze=g.modalMaxHeight)!=null?ze:"min(90vh, 800px)",We="calc(100vw - 32px)",we="var(--persona-pill-area-height, 80px)",ie=Ce.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",tt){let $e=tt.style;$e.bottom=C,$e.width=D!=null?D:""}if(c&&w!=="fullscreen"){if(w==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=j,ie.maxWidth=We,ie.maxHeight=F,ie.height=F;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${C} + ${we})`,ie.top=U,ie.width=$,ie.maxWidth=We}},ko=()=>{var F,We,we,ie,Le,De,Ye,ht;if(!R())return;if(W()){let wt=(we=((We=(F=n.launcher)==null?void 0:F.composerBar)!=null?We:{}).expandedSize)!=null?we:"anchored",vt=B?"expanded":"collapsed";Ce.dataset.state=vt,Ce.dataset.expandedSize=wt,tt&&(tt.dataset.state=vt,tt.dataset.expandedSize=wt),Ce.style.removeProperty("display"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ui(B),me.style.display=B?"flex":"none",Rn(),B?(di(),ci()):(es(),ts()),ao();return}let c=Ar(n),g=(ie=t.ownerDocument.defaultView)!=null?ie:window,w=(De=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?De:640,C=(ht=(Ye=n.launcher)==null?void 0:Ye.mobileFullscreen)!=null?ht:!0,D=g.innerWidth<=w,$=C&&D&&T,U=kn(n).reveal;B?(Ce.style.removeProperty("display"),Ce.style.display=c?"flex":"",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),Fe?Fe.element.style.display="none":lt&&(lt.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Ce.style.removeProperty("display"),Ce.style.display="flex",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.setProperty("display","none","important"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.display="",Ce.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),Fe?Fe.element.style.display=c?"none":"":lt&&(lt.style.display=c?"none":""))},Kt=(c,g="user")=>{var $,U;if(!R()||B===c)return;let w=B;B=c,ko();let C=(()=>{var Ye,ht,dt,wt,vt,ze,$e,nt,H,Oe;let j=(ht=(Ye=n.launcher)==null?void 0:Ye.sidebarMode)!=null?ht:!1,F=(dt=t.ownerDocument.defaultView)!=null?dt:window,We=(vt=(wt=n.launcher)==null?void 0:wt.mobileFullscreen)!=null?vt:!0,we=($e=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?$e:640,ie=F.innerWidth<=we,Le=Ar(n)&&We&&ie,De=W()&&((Oe=(H=(nt=n.launcher)==null?void 0:nt.composerBar)==null?void 0:H.expandedSize)!=null?Oe:"fullscreen")==="fullscreen";return j||We&&ie&&T||Le||De})();if(B&&C){if(!gr){let j=t.getRootNode(),F=j instanceof ShadowRoot?j.host:t.closest(".persona-host");F&&(gr=Np(F,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:zr))}hr||(hr=Fp(t.ownerDocument))}else B||(gr==null||gr(),gr=null,hr==null||hr(),hr=null);B&&(jt(),Ao(!0));let D={open:B,source:g,timestamp:Date.now()};B&&!w?s.emit("widget:opened",D):!B&&w&&s.emit("widget:closed",D),s.emit("widget:state",{open:B,launcherEnabled:T,voiceActive:Lt.active,streaming:I.isStreaming()})},ya=c=>{Xt(c?"stop":"send"),G&&(G.disabled=c),Wn.buttons.forEach(g=>{g.disabled=c}),Xe.dataset.personaComposerStreaming=c?"true":"false",Xe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},ba=()=>{Lt.active||ge&&ge.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>ba(),200)});let ns=()=>{var w,C,D,$,U,j,F,We,we,ie,Le;pe.textContent=(C=(w=n.copy)==null?void 0:w.welcomeTitle)!=null?C:"Hello \u{1F44B}",Be.textContent=($=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ge.placeholder=(j=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?j:"How can I help...";let c=J.querySelector("[data-persona-intro-card]");if(c){let De=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=De?"":"none",De?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}!((we=(We=n.sendButton)==null?void 0:We.useIcon)!=null&&we)&&!(I!=null&&I.isStreaming())&&(q.textContent=(Le=(ie=n.copy)==null?void 0:ie.sendButtonLabel)!=null?Le:"Send"),ge.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ge.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let Vn=null,fi=()=>{Vn==null&&(Vn=setInterval(()=>{let c=qe.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Vn),Vn=null;return}let g=Date.now();c.forEach(w=>{let C=Number(w.getAttribute("data-tool-elapsed"));C&&(w.textContent=qi(g-C))})},100))};if(I=new Wa(n,{onMessagesChanged(c){Uo(qe,c,be),fi(),I&&(c.some(D=>D.role==="user")?Wn.render([],I,ge,c):Wn.render(n.suggestionChips,I,ge,c,n.suggestionChipsConfig)),Ao(!pn),li(c);let g=[...c].reverse().find(C=>C.role==="user"),w=Lt.lastUserMessageId;g&&g.id!==w&&(Lt.lastUserMessageId=g.id,s.emit("user:message",g)),Lt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),xa(c),ao()},onStatusChanged(c){var C;let g=(C=n.statusIndicator)!=null?C:{};ut(fe,(D=>{var $,U,j,F;return D==="idle"?($=g.idleText)!=null?$:Ur.idle:D==="connecting"?(U=g.connectingText)!=null?U:Ur.connecting:D==="connected"?(j=g.connectedText)!=null?j:Ur.connected:D==="error"?(F=g.errorText)!=null?F:Ur.error:Ur[D]})(c),g,c)},onStreamingChanged(c){pn=c,ya(c),I&&Uo(qe,I.getMessages(),be),c||Ao(!0),ao()},onVoiceStatusChanged(c){var g,w;if(((w=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:w.type)==="runtype")switch(c){case"listening":break;case"processing":Y(),O();break;case"speaking":Y(),se();break;default:c==="idle"&&I.isBargeInActive()?(Y(),z(),G==null||G.setAttribute("aria-label","End voice session")):(Lt.active=!1,Y(),An("system"),tn());break}},onArtifactsState(c){ee=c,ln(),xa()}}),rt.current=I,((bf=(yf=n.voiceRecognition)==null?void 0:yf.provider)==null?void 0:bf.type)==="runtype")try{I.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&I.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||n.onSSEEvent)&&I.setSSEEventCallback((c,g)=>{var w;(w=n.onSSEEvent)==null||w.call(n,c,g),Te==null||Te.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,w,C;c&&(c.metadata&&(d=cu(c.metadata),E.syncFromMetadata()),(g=c.messages)!=null&&g.length&&I.hydrateMessages(c.messages),(w=c.artifacts)!=null&&w.length&&I.hydrateArtifacts(c.artifacts,(C=c.selectedArtifactId)!=null?C:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let os=()=>{var g,w,C;!W()||B||!((C=(w=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:w.expandOnSubmit)==null||C)||Kt(!0,"auto")},as=c=>{var D;if(c.preventDefault(),I.isStreaming()){I.cancel(),Te==null||Te.reset(),ae==null||ae.update();return}let g=ge.value.trim(),w=(D=ft==null?void 0:ft.hasAttachments())!=null?D:!1;if(!g&&!w)return;os();let C;w&&(C=[],C.push(...ft.getContentParts()),g&&C.push(Rs(g))),ge.value="",ge.style.height="auto",zo(),I.sendMessage(g,{contentParts:C}),w&&ft.clearAttachments()},mi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},wa={...vl},va=!1,zo=()=>{wa={...vl}},gi=()=>I.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),hi=c=>{if(!ge)return;va=!0,ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),va=!1;let g=ge.value.length;ge.setSelectionRange(g,g)},ss=()=>{va||zo()},is=c=>{if(ge){if(mi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ge.selectionStart===0&&ge.selectionEnd===0,w=ex({direction:c.key==="ArrowUp"?"up":"down",history:gi(),currentValue:ge.value,atStart:g,state:wa});if(wa=w.state,w.handled){c.preventDefault(),w.value!==void 0&&hi(w.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(I.isStreaming()){c.preventDefault();return}zo(),c.preventDefault(),q.click()}}},ls=c=>{c.key!=="Escape"||c.isComposing||I.isStreaming()&&c.composedPath().includes(me)&&(I.cancel(),Te==null||Te.reset(),ae==null||ae.update(),zo(),c.preventDefault(),c.stopImmediatePropagation())},ds=async c=>{var w;if(((w=n.attachments)==null?void 0:w.enabled)!==!0||!ft)return;let g=lC(c.clipboardData);g.length!==0&&(c.preventDefault(),await ft.handleFiles(g))},qr=null,un=!1,so=null,yt=null,cs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qo=(c="user")=>{var $,U,j,F,We,we,ie;if(un||I.isStreaming())return;let g=cs();if(!g)return;qr=new g;let C=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;qr.continuous=!0,qr.interimResults=!0,qr.lang="en-US";let D=ge.value;qr.onresult=Le=>{let De="",Ye="";for(let dt=0;dt<Le.results.length;dt++){let wt=Le.results[dt],vt=wt[0].transcript;wt.isFinal?De+=vt+" ":Ye=vt}let ht=D+De+Ye;ge.value=ht,so&&clearTimeout(so),(De||Ye)&&(so=window.setTimeout(()=>{let dt=ge.value.trim();dt&&qr&&un&&(_n(),ge.value="",ge.style.height="auto",I.sendMessage(dt,{viaVoice:!0}))},C))},qr.onerror=Le=>{Le.error!=="no-speech"&&_n()},qr.onend=()=>{if(un){let Le=ge.value.trim();Le&&Le!==D.trim()&&(ge.value="",ge.style.height="auto",I.sendMessage(Le,{viaVoice:!0})),_n()}};try{if(qr.start(),un=!0,Lt.active=!0,c!=="system"&&(Lt.manuallyDeactivated=!1),An(c),tn(),G){let Le=(j=n.voiceRecognition)!=null?j:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(F=Le.iconName)!=null?F:"mic",iconSize:parseFloat((ie=(we=Le.iconSize)!=null?we:(We=n.sendButton)==null?void 0:We.size)!=null?ie:"40")||24};let De=Le.recordingBackgroundColor,Ye=Le.recordingIconColor,ht=Le.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Ye!=null?Ye:"var(--persona-voice-recording-indicator, #ffffff)",Ye){let dt=G.querySelector("svg");dt&&dt.setAttribute("stroke",Ye)}ht&&(G.style.borderColor=ht),G.setAttribute("aria-label","Stop voice recognition")}}catch{_n("system")}},_n=(c="user")=>{if(un){if(un=!1,so&&(clearTimeout(so),so=null),qr){try{qr.stop()}catch{}qr=null}if(Lt.active=!1,An(c),tn(),G){if(G.classList.remove("persona-voice-recording"),yt){G.style.backgroundColor=yt.backgroundColor,G.style.color=yt.color,G.style.borderColor=yt.borderColor;let g=G.querySelector("svg");g&&g.setAttribute("stroke",yt.color||"currentColor"),yt=null}G.setAttribute("aria-label","Start voice recognition")}}},xi=(c,g)=>{var wt,vt,ze,$e,nt,H,Oe,Je;let w=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((wt=c==null?void 0:c.provider)==null?void 0:wt.type)==="runtype";if(!(w||C))return null;let $=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let j=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",F=(ze=g==null?void 0:g.size)!=null?ze:"40px",We=($e=c==null?void 0:c.iconSize)!=null?$e:F,we=parseFloat(We)||24,ie=(nt=c==null?void 0:c.backgroundColor)!=null?nt:g==null?void 0:g.backgroundColor,Le=(H=c==null?void 0:c.iconColor)!=null?H:g==null?void 0:g.textColor;U.style.width=We,U.style.height=We,U.style.minWidth=We,U.style.minHeight=We,U.style.fontSize="18px",U.style.lineHeight="1",Le?U.style.color=Le:U.style.color="var(--persona-text, #111827)";let Ye=Ie(j,we,Le||"currentColor",1.5);Ye?U.appendChild(Ye):U.textContent="\u{1F3A4}",ie?U.style.backgroundColor=ie:U.style.backgroundColor="",c!=null&&c.borderWidth&&(U.style.borderWidth=c.borderWidth,U.style.borderStyle="solid"),c!=null&&c.borderColor&&(U.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(U.style.paddingLeft=c.paddingX,U.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(U.style.paddingTop=c.paddingY,U.style.paddingBottom=c.paddingY),$.appendChild(U);let ht=(Oe=c==null?void 0:c.tooltipText)!=null?Oe:"Start voice recognition";if(((Je=c==null?void 0:c.showTooltip)!=null?Je:!1)&&ht){let it=v("div","persona-send-button-tooltip");it.textContent=ht,$.appendChild(it)}return{micButton:U,micButtonWrapper:$}},Eo=()=>{var g,w,C,D,$;if(!G||yt)return;let c=(g=n.voiceRecognition)!=null?g:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(w=c.iconName)!=null?w:"mic",iconSize:parseFloat(($=(D=c.iconSize)!=null?D:(C=n.sendButton)==null?void 0:C.size)!=null?$:"40")||24}},st=(c,g)=>{var $,U,j,F,We;if(!G)return;let w=G.querySelector("svg");w&&w.remove();let C=(We=yt==null?void 0:yt.iconSize)!=null?We:parseFloat((F=(j=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?j:(U=n.sendButton)==null?void 0:U.size)!=null?F:"40")||24,D=Ie(c,C,g,1.5);D&&G.appendChild(D)},L=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},z=()=>{var D;if(!G)return;Eo();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,w=c.recordingIconColor,C=c.recordingBorderColor;if(L(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=w!=null?w:"var(--persona-voice-recording-indicator, #ffffff)",w){let $=G.querySelector("svg");$&&$.setAttribute("stroke",w)}C&&(G.style.borderColor=C),G.setAttribute("aria-label","Stop voice recognition")},O=()=>{var j,F,We,we,ie,Le,De,Ye;if(!G)return;Eo();let c=(j=n.voiceRecognition)!=null?j:{},g=I.getVoiceInterruptionMode(),w=(F=c.processingIconName)!=null?F:"loader",C=(we=(We=c.processingIconColor)!=null?We:yt==null?void 0:yt.color)!=null?we:"",D=(Le=(ie=c.processingBackgroundColor)!=null?ie:yt==null?void 0:yt.backgroundColor)!=null?Le:"",$=(Ye=(De=c.processingBorderColor)!=null?De:yt==null?void 0:yt.borderColor)!=null?Ye:"";L(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=D,G.style.borderColor=$;let U=C||"currentColor";G.style.color=U,st(w,U),G.setAttribute("aria-label","Processing voice input"),g==="none"&&(G.style.cursor="default")},se=()=>{var We,we,ie,Le,De,Ye,ht,dt,wt,vt,ze,$e;if(!G)return;Eo();let c=(We=n.voiceRecognition)!=null?We:{},g=I.getVoiceInterruptionMode(),w=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(we=c.speakingIconName)!=null?we:w,D=(Ye=c.speakingIconColor)!=null?Ye:g==="barge-in"?(Le=(ie=c.recordingIconColor)!=null?ie:yt==null?void 0:yt.color)!=null?Le:"":(De=yt==null?void 0:yt.color)!=null?De:"",$=(wt=c.speakingBackgroundColor)!=null?wt:g==="barge-in"?(ht=c.recordingBackgroundColor)!=null?ht:"var(--persona-voice-recording-bg, #ef4444)":(dt=yt==null?void 0:yt.backgroundColor)!=null?dt:"",U=($e=c.speakingBorderColor)!=null?$e:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(ze=yt==null?void 0:yt.borderColor)!=null?ze:"";L(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=$,G.style.borderColor=U;let j=D||"currentColor";G.style.color=j,st(C,j);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",F),g==="none"&&(G.style.cursor="default"),g==="barge-in"&&G.classList.add("persona-voice-recording")},Y=()=>{var c,g,w;G&&(L(),yt&&(G.style.backgroundColor=(c=yt.backgroundColor)!=null?c:"",G.style.color=(g=yt.color)!=null?g:"",G.style.borderColor=(w=yt.borderColor)!=null?w:"",st(yt.iconName,yt.color||"currentColor"),yt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},te=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let w=I.getVoiceStatus(),C=I.getVoiceInterruptionMode();if(C==="none"&&(w==="processing"||w==="speaking"))return;if(C==="cancel"&&(w==="processing"||w==="speaking")){I.stopVoicePlayback();return}if(I.isBargeInActive()){I.stopVoicePlayback(),I.deactivateBargeIn().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),Y()});return}I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),Lt.manuallyDeactivated=!I.isVoiceActive(),tn(),An("user"),I.isVoiceActive()?z():Y()});return}if(un){let w=ge.value.trim();Lt.manuallyDeactivated=!0,tn(),_n("user"),w&&(ge.value="",ge.style.height="auto",I.sendMessage(w))}else Lt.manuallyDeactivated=!1,tn(),qo("user")};dr=te,G&&(G.addEventListener("click",te),Pt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(I.isVoiceActive()&&I.toggleVoice(),Y()):_n("system"),G&&G.removeEventListener("click",te)}));let ct=s.on("assistant:complete",()=>{Qa&&(Lt.active||Lt.manuallyDeactivated||Qa==="assistant"&&!Lt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Lt.active&&!Lt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),An("auto"),I.isVoiceActive()&&z()}):qo("auto"))},600))});Pt.push(ct);let et=s.on("action:resubmit",()=>{setTimeout(()=>{I&&!I.isStreaming()&&I.continueConversation()},100)});Pt.push(et);let mt=()=>{Kt(!B,"user")},Fe=null,lt=null;if(T&&!W()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Vs(n,mt).element,onToggle:mt});g&&(lt=g)}lt||(Fe=Vs(n,mt))}Fe?t.appendChild(Fe.element):lt&&t.appendChild(lt),ko(),Wn.render(n.suggestionChips,I,ge,void 0,n.suggestionChipsConfig),ns(),ya(I.isStreaming()),Ao(!0),oi(),k&&(!T||W()?setTimeout(()=>ba(),0):B&&setTimeout(()=>ba(),200));let jt=()=>{var F,We,we,ie,Le,De,Ye,ht,dt,wt,vt,ze,$e,nt,H,Oe,Je,it,Pe,qt,bt,yr;if(W()){Et(),ko();return}let c=Ar(n),g=(We=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?We:!1,w=c||g||((ie=(we=n.launcher)==null?void 0:we.fullHeight)!=null?ie:!1),C=(Le=t.ownerDocument.defaultView)!=null?Le:window,D=(Ye=(De=n.launcher)==null?void 0:De.mobileFullscreen)!=null?Ye:!0,$=(dt=(ht=n.launcher)==null?void 0:ht.mobileBreakpoint)!=null?dt:640,U=C.innerWidth<=$,j=D&&U&&T;try{if(j){Rn(),Io(t,n);return}if(M&&(M=!1,Rn(),Io(t,n)),!T&&!c){he.style.height="",he.style.width="";return}if(!g&&!c){let Wr=(vt=(wt=n==null?void 0:n.launcher)==null?void 0:wt.width)!=null?vt:n==null?void 0:n.launcherWidth,Gt=Wr!=null?Wr:yn;he.style.width=Gt,he.style.maxWidth=Gt}if(zn(),!w){let Wr=C.innerHeight,Gt=64,jr=($e=(ze=n.launcher)==null?void 0:ze.heightOffset)!=null?$e:0,Br=Math.max(200,Wr-Gt),pt=Math.min(640,Br),Ct=Math.max(200,pt-jr);he.style.height=`${Ct}px`}}finally{if(Et(),ko(),B&&T){let Gt=((nt=t.ownerDocument.defaultView)!=null?nt:window).innerWidth<=((Oe=(H=n.launcher)==null?void 0:H.mobileBreakpoint)!=null?Oe:640),jr=(it=(Je=n.launcher)==null?void 0:Je.sidebarMode)!=null?it:!1,Br=(qt=(Pe=n.launcher)==null?void 0:Pe.mobileFullscreen)!=null?qt:!0,pt=Ar(n)&&Br&&Gt,Ct=jr||Br&&Gt&&T||pt;if(Ct&&!hr){let Gr=t.getRootNode(),Fr=Gr instanceof ShadowRoot?Gr.host:t.closest(".persona-host");Fr&&!gr&&(gr=Np(Fr,(yr=(bt=n.launcher)==null?void 0:bt.zIndex)!=null?yr:zr)),hr=Fp(t.ownerDocument)}else Ct||(gr==null||gr(),gr=null,hr==null||hr(),hr=null)}}};jt();let Sr=(wf=t.ownerDocument.defaultView)!=null?wf:window;if(Sr.addEventListener("resize",jt),Pt.push(()=>Sr.removeEventListener("resize",jt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Et()});c.observe(Xe),Pt.push(()=>c.disconnect())}Dn=J.scrollTop;let _t=J.scrollHeight,zt=()=>{let c=J.scrollTop,g=J.scrollHeight,w=g<_t;_t=g;let{action:C,nextLastScrollTop:D}=Al({following:Hn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:_s(J,Ja),userScrollThreshold:ri,isAutoScrolling:ro||Fo||w,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=D,C==="resume"){Co();return}C==="pause"&&Za()};J.addEventListener("scroll",zt,{passive:!0}),Pt.push(()=>J.removeEventListener("scroll",zt));let Tr=c=>{let g=Sl({following:Hn.isFollowing(),deltaY:c.deltaY,nearBottom:_s(J,Ja),resumeWhenNearBottom:!0});g==="pause"?Za():g==="resume"&&Co()};J.addEventListener("wheel",Tr,{passive:!0}),Pt.push(()=>J.removeEventListener("wheel",Tr)),Ot.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,Dn=J.scrollTop,Co(),Ao(!0)}),Pt.push(()=>Ot.remove()),Pt.push(()=>{Ya()});let Nr=()=>{Q&&(cn&&(Q.removeEventListener("click",cn),cn=null),R()?(Q.style.display="",cn=()=>{Kt(!1,"user")},Q.addEventListener("click",cn)):Q.style.display="none")};Nr(),(()=>{let{clearChatButton:c}=Ne;c&&c.addEventListener("click",()=>{I.clearMessages(),Bn.clear(),Co(),_o(Ne.composerOverlay);try{localStorage.removeItem(Ga),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(w){console.error("[AgentWidget] Failed to clear default localStorage:",w)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(w){console.error("[AgentWidget] Failed to clear custom localStorage:",w)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let w=i.clear();w instanceof Promise&&w.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)}d={},E.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),ae==null||ae.update()})})(),Ae&&Ae.addEventListener("submit",as),ge==null||ge.addEventListener("keydown",is),ge==null||ge.addEventListener("input",ss),ge==null||ge.addEventListener("paste",ds);let xr=(vf=t.ownerDocument)!=null?vf:document;xr.addEventListener("keydown",ls,!0);let Sn="persona-attachment-drop-active",ps=0,nd=()=>{ps=0,me.classList.remove(Sn)},Ca=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&ft!==null},ku=c=>{!Yl(c.dataTransfer)||!Ca()||(ps++,ps===1&&me.classList.add(Sn))},Eu=c=>{!Yl(c.dataTransfer)||!Ca()||(ps--,ps<=0&&nd())},Lu=c=>{!Yl(c.dataTransfer)||!Ca()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Pu=c=>{var w;if(!Yl(c.dataTransfer)||!Ca())return;c.preventDefault(),c.stopPropagation(),nd();let g=Array.from((w=c.dataTransfer.files)!=null?w:[]);g.length!==0&&ft.handleFiles(g)},Lo=!0;me.addEventListener("dragenter",ku,Lo),me.addEventListener("dragleave",Eu,Lo),t.addEventListener("dragover",Lu,Lo),t.addEventListener("drop",Pu,Lo);let yi=t.ownerDocument,Iu=c=>{Ca()&&c.preventDefault()},Ru=c=>{Ca()&&c.preventDefault()};yi.addEventListener("dragover",Iu),yi.addEventListener("drop",Ru),Pt.push(()=>{Ae&&Ae.removeEventListener("submit",as),ge==null||ge.removeEventListener("keydown",is),ge==null||ge.removeEventListener("input",ss),ge==null||ge.removeEventListener("paste",ds),xr.removeEventListener("keydown",ls,!0)}),Pt.push(()=>{me.removeEventListener("dragenter",ku,Lo),me.removeEventListener("dragleave",Eu,Lo),t.removeEventListener("dragover",Lu,Lo),t.removeEventListener("drop",Pu,Lo),yi.removeEventListener("dragover",Iu),yi.removeEventListener("drop",Ru),nd()}),Pt.push(()=>{I.cancel()}),Fe?Pt.push(()=>{Fe==null||Fe.destroy()}):lt&&Pt.push(()=>{lt==null||lt.remove()});let vr={update(c){var Cr,jn,lo,bi,wi,vi,Xo,Ci,us,Ef,Lf,Pf,If,Rf,Wf,Bf,Hf,Df,Of,_f,Nf,Ff,$f,Uf,zf,qf,Vf,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,wm,vm,Cm,Am,Sm,Tm,Mm,km,Em,Lm,Pm,Im,Rm,Wm,Bm,Hm,Dm,Om,_m,Nm,Fm,$m,Um,zm,qm,Vm,jm,Gm,Km,Xm,Jm,Qm,Ym,Zm,eg,tg,rg,ng,og,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,wg,vg,Cg,Ag;let g=n.toolCall,w=n.messageActions,C=(Cr=n.layout)==null?void 0:Cr.messages,D=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,j=(jn=n.features)==null?void 0:jn.showReasoning,F=(lo=n.features)==null?void 0:lo.showToolCalls,We=(bi=n.features)==null?void 0:bi.toolCallDisplay,we=(wi=n.features)==null?void 0:wi.reasoningDisplay;n={...n,...c},Rn(),Io(t,n),zl(t,n),ql(t,n),ln(),n.colorScheme!==D&&vo();let ie=Qs.getForInstance(n.plugins);o.length=0,o.push(...ie),T=(Xo=(vi=n.launcher)==null?void 0:vi.enabled)!=null?Xo:!0,S=(us=(Ci=n.launcher)==null?void 0:Ci.autoExpand)!=null?us:!1,Qe=(Lf=(Ef=n.features)==null?void 0:Ef.showReasoning)!=null?Lf:!0,je=(If=(Pf=n.features)==null?void 0:Pf.showToolCalls)!=null?If:!0,Ee=(Wf=(Rf=n.features)==null?void 0:Rf.scrollToBottom)!=null?Wf:{},sr(),oo();let Le=ve;if(ve=(Hf=(Bf=n.features)==null?void 0:Bf.showEventStreamToggle)!=null?Hf:!1,ve&&!Le){if(K||(X=new Xs(_e),K=new Ks(Ue,X),Te=Te!=null?Te:new Js,X.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),I.setSSEEventCallback((ne,Dt)=>{var rr;(rr=n.onSSEEvent)==null||rr.call(n,ne,Dt),Te==null||Te.processEvent(ne,Dt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Dt)})})),!xt&&Ve){let ne=(Of=(Df=n.features)==null?void 0:Df.eventStream)==null?void 0:Of.classNames,Dt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");xt=v("button",Dt),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let rr=Ie("activity","18px","currentColor",1.5);rr&&xt.appendChild(rr);let At=Ne.clearChatButtonWrapper,Ut=Ne.closeButtonWrapper,Mr=At||Ut;Mr&&Mr.parentNode===Ve?Ve.insertBefore(xt,Mr):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}}else!ve&&Le&&(Or(),xt&&(xt.remove(),xt=null),K==null||K.clear(),X==null||X.destroy(),K=null,X=null,Te==null||Te.reset(),Te=null);if(((_f=n.launcher)==null?void 0:_f.enabled)===!1&&Fe&&(Fe.destroy(),Fe=null),((Nf=n.launcher)==null?void 0:Nf.enabled)===!1&&lt&&(lt.remove(),lt=null),((Ff=n.launcher)==null?void 0:Ff.enabled)!==!1&&!Fe&&!lt){let ne=o.find(Dt=>Dt.renderLauncher);if(ne!=null&&ne.renderLauncher){let Dt=ne.renderLauncher({config:n,defaultRenderer:()=>Vs(n,mt).element,onToggle:mt});Dt&&(lt=Dt,t.appendChild(lt))}lt||(Fe=Vs(n,mt),t.appendChild(Fe.element))}Fe&&Fe.update(n),ke&&(($f=n.launcher)==null?void 0:$f.title)!==void 0&&(ke.textContent=n.launcher.title),He&&((Uf=n.launcher)==null?void 0:Uf.subtitle)!==void 0&&(He.textContent=n.launcher.subtitle);let De=(zf=n.layout)==null?void 0:zf.header;if((De==null?void 0:De.layout)!==h&&Ve){let ne=De?Oa(n,De,{showClose:R(),onClose:()=>Kt(!1,"user")}):go({config:n,showClose:R(),onClose:()=>Kt(!1,"user")});Ve.replaceWith(ne.header),Ve=ne.header,N=ne.iconHolder,ke=ne.headerTitle,He=ne.headerSubtitle,Q=ne.closeButton,h=De==null?void 0:De.layout}else if(De&&(N&&(N.style.display=De.showIcon===!1?"none":""),ke&&(ke.style.display=De.showTitle===!1?"none":""),He&&(He.style.display=De.showSubtitle===!1?"none":""),Q&&(Q.style.display=De.showCloseButton===!1?"none":""),Ne.clearChatButtonWrapper)){let ne=De.showClearChat;if(ne!==void 0){Ne.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Dt}=Ne;Dt&&!Dt.classList.contains("persona-absolute")&&(ne?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"))}}let ht=((qf=n.layout)==null?void 0:qf.showHeader)!==!1;Ve&&(Ve.style.display=ht?"":"none");let dt=((Vf=n.layout)==null?void 0:Vf.showFooter)!==!1;Xe&&(Xe.style.display=dt?"":"none"),Et(),oo(),T!==b?T?Kt(S,"auto"):(B=!0,ko()):S!==x&&Kt(S,"auto"),x=S,b=T,jt(),Nr();let ze=JSON.stringify(c.toolCall)!==JSON.stringify(g),$e=JSON.stringify(n.messageActions)!==JSON.stringify(w),nt=JSON.stringify((jf=n.layout)==null?void 0:jf.messages)!==JSON.stringify(C),H=((Gf=n.loadingIndicator)==null?void 0:Gf.render)!==($==null?void 0:$.render)||((Kf=n.loadingIndicator)==null?void 0:Kf.renderIdle)!==($==null?void 0:$.renderIdle)||((Xf=n.loadingIndicator)==null?void 0:Xf.showBubble)!==($==null?void 0:$.showBubble),Oe=n.iterationDisplay!==U,Je=((Qf=(Jf=n.features)==null?void 0:Jf.showReasoning)!=null?Qf:!0)!==(j!=null?j:!0)||((Zf=(Yf=n.features)==null?void 0:Yf.showToolCalls)!=null?Zf:!0)!==(F!=null?F:!0)||JSON.stringify((em=n.features)==null?void 0:em.toolCallDisplay)!==JSON.stringify(We)||JSON.stringify((tm=n.features)==null?void 0:tm.reasoningDisplay)!==JSON.stringify(we);(ze||$e||nt||H||Oe||Je)&&I&&(Xa++,Uo(qe,I.getMessages(),be));let Pe=(rm=n.launcher)!=null?rm:{},qt=(nm=Pe.headerIconHidden)!=null?nm:!1,bt=(am=(om=n.layout)==null?void 0:om.header)==null?void 0:am.showIcon,yr=qt||bt===!1,Wr=Pe.headerIconName,Gt=(sm=Pe.headerIconSize)!=null?sm:"48px";if(N){let ne=me.querySelector(".persona-border-b-persona-divider"),Dt=ne==null?void 0:ne.querySelector(".persona-flex-col");if(yr)N.style.display="none",ne&&Dt&&!ne.contains(Dt)&&ne.insertBefore(Dt,ne.firstChild);else{if(N.style.display="",N.style.height=Gt,N.style.width=Gt,ne&&Dt&&(ne.contains(N)?N.nextSibling!==Dt&&(N.remove(),ne.insertBefore(N,Dt)):ne.insertBefore(N,Dt)),Wr){let At=parseFloat(Gt)||24,Ut=Ie(Wr,At*.6,"#ffffff",2);Ut?N.replaceChildren(Ut):N.textContent=(im=Pe.agentIconText)!=null?im:"\u{1F4AC}"}else if(Pe.iconUrl){let At=N.querySelector("img");if(At)At.src=Pe.iconUrl,At.style.height=Gt,At.style.width=Gt;else{let Ut=document.createElement("img");Ut.src=Pe.iconUrl,Ut.alt="",Ut.className="persona-rounded-xl persona-object-cover",Ut.style.height=Gt,Ut.style.width=Gt,N.replaceChildren(Ut)}}else{let At=N.querySelector("svg"),Ut=N.querySelector("img");(At||Ut)&&N.replaceChildren(),N.textContent=(lm=Pe.agentIconText)!=null?lm:"\u{1F4AC}"}let rr=N.querySelector("img");rr&&(rr.style.height=Gt,rr.style.width=Gt)}}let jr=(cm=(dm=n.layout)==null?void 0:dm.header)==null?void 0:cm.showTitle,Br=(um=(pm=n.layout)==null?void 0:pm.header)==null?void 0:um.showSubtitle;if(ke&&(ke.style.display=jr===!1?"none":""),He&&(He.style.display=Br===!1?"none":""),Q){((mm=(fm=n.layout)==null?void 0:fm.header)==null?void 0:mm.showCloseButton)===!1?Q.style.display="none":Q.style.display="";let Dt=(gm=Pe.closeButtonSize)!=null?gm:"32px",rr=(hm=Pe.closeButtonPlacement)!=null?hm:"inline";Q.style.height=Dt,Q.style.width=Dt;let{closeButtonWrapper:At}=Ne,Ut=rr==="top-right",Mr=At==null?void 0:At.classList.contains("persona-absolute");if(At&&Ut!==Mr)if(At.remove(),Ut)At.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(At);else{let Tt=(ym=(xm=Pe.clearChat)==null?void 0:xm.placement)!=null?ym:"inline",kr=(wm=(bm=Pe.clearChat)==null?void 0:bm.enabled)!=null?wm:!0;At.className=kr&&Tt==="inline"?"":"persona-ml-auto";let an=me.querySelector(".persona-border-b-persona-divider");an&&an.appendChild(At)}if(Q.style.color=Pe.closeButtonColor||en.actionIconColor,Pe.closeButtonBackgroundColor?(Q.style.backgroundColor=Pe.closeButtonBackgroundColor,Q.classList.remove("hover:persona-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Tt=Pe.closeButtonBorderWidth||"0px",kr=Pe.closeButtonBorderColor||"transparent";Q.style.border=`${Tt} solid ${kr}`,Q.classList.remove("persona-border-none")}else Q.style.border="",Q.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Q.style.borderRadius=Pe.closeButtonBorderRadius,Q.classList.remove("persona-rounded-full")):(Q.style.borderRadius="",Q.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Q.style.paddingLeft=Pe.closeButtonPaddingX,Q.style.paddingRight=Pe.closeButtonPaddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),Pe.closeButtonPaddingY?(Q.style.paddingTop=Pe.closeButtonPaddingY,Q.style.paddingBottom=Pe.closeButtonPaddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let $r=(vm=Pe.closeButtonIconName)!=null?vm:"x",Nn=(Cm=Pe.closeButtonIconText)!=null?Cm:"\xD7";Q.innerHTML="";let Xr=Ie($r,"28px","currentColor",1);Xr?Q.appendChild(Xr):Q.textContent=Nn;let br=(Am=Pe.closeButtonTooltipText)!=null?Am:"Close chat",mn=(Sm=Pe.closeButtonShowTooltip)!=null?Sm:!0;if(Q.setAttribute("aria-label",br),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),mn&&br)){let Tt=null,kr=()=>{if(Tt||!Q)return;let Jo=Q.ownerDocument,fs=Jo.body;if(!fs)return;Tt=Qn(Jo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let ms=Qn(Jo,"div");ms.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(ms);let Qo=Q.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Ro),Tt.style.left=`${Qo.left+Qo.width/2}px`,Tt.style.top=`${Qo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",fs.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};At.addEventListener("mouseenter",kr),At.addEventListener("mouseleave",an),Q.addEventListener("focus",kr),Q.addEventListener("blur",an),At._cleanupTooltip=()=>{an(),At&&(At.removeEventListener("mouseenter",kr),At.removeEventListener("mouseleave",an)),Q&&(Q.removeEventListener("focus",kr),Q.removeEventListener("blur",an))}}}let{clearChatButton:pt,clearChatButtonWrapper:Ct}=Ne;if(pt){let ne=(Tm=Pe.clearChat)!=null?Tm:{},Dt=(Mm=ne.enabled)!=null?Mm:!0,rr=(Em=(km=n.layout)==null?void 0:km.header)==null?void 0:Em.showClearChat,At=rr!==void 0?rr:Dt,Ut=(Lm=ne.placement)!=null?Lm:"inline";if(Ct){Ct.style.display=At?"":"none";let{closeButtonWrapper:Mr}=Ne;!W()&&Mr&&!Mr.classList.contains("persona-absolute")&&(At?Mr.classList.remove("persona-ml-auto"):Mr.classList.add("persona-ml-auto"));let $r=Ut==="top-right",Nn=Ct.classList.contains("persona-absolute");if(!W()&&$r!==Nn&&At){if(Ct.remove(),$r)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",me.style.position="relative",me.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let br=me.querySelector(".persona-border-b-persona-divider"),mn=Ne.closeButtonWrapper;br&&mn&&mn.parentElement===br?br.insertBefore(Ct,mn):br&&br.appendChild(Ct)}let Xr=Ne.closeButtonWrapper;Xr&&!Xr.classList.contains("persona-absolute")&&($r?Xr.classList.add("persona-ml-auto"):Xr.classList.remove("persona-ml-auto"))}}if(At){if(!W()){let Tt=(Pm=ne.size)!=null?Pm:"32px";pt.style.height=Tt,pt.style.width=Tt}let Mr=(Im=ne.iconName)!=null?Im:"refresh-cw",$r=(Rm=ne.iconColor)!=null?Rm:"";pt.style.color=$r||en.actionIconColor,pt.innerHTML="";let Nn=W()?"14px":"20px",Xr=Ie(Mr,Nn,"currentColor",2);if(Xr&&pt.appendChild(Xr),ne.backgroundColor?(pt.style.backgroundColor=ne.backgroundColor,pt.classList.remove("hover:persona-bg-gray-100")):(pt.style.backgroundColor="",pt.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let Tt=ne.borderWidth||"0px",kr=ne.borderColor||"transparent";pt.style.border=`${Tt} solid ${kr}`,pt.classList.remove("persona-border-none")}else pt.style.border="",pt.classList.add("persona-border-none");ne.borderRadius?(pt.style.borderRadius=ne.borderRadius,pt.classList.remove("persona-rounded-full")):(pt.style.borderRadius="",pt.classList.add("persona-rounded-full")),ne.paddingX?(pt.style.paddingLeft=ne.paddingX,pt.style.paddingRight=ne.paddingX):(pt.style.paddingLeft="",pt.style.paddingRight=""),ne.paddingY?(pt.style.paddingTop=ne.paddingY,pt.style.paddingBottom=ne.paddingY):(pt.style.paddingTop="",pt.style.paddingBottom="");let br=(Wm=ne.tooltipText)!=null?Wm:"Clear chat",mn=(Bm=ne.showTooltip)!=null?Bm:!0;if(pt.setAttribute("aria-label",br),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),mn&&br)){let Tt=null,kr=()=>{if(Tt||!pt)return;let Jo=pt.ownerDocument,fs=Jo.body;if(!fs)return;Tt=Qn(Jo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let ms=Qn(Jo,"div");ms.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(ms);let Qo=pt.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Ro),Tt.style.left=`${Qo.left+Qo.width/2}px`,Tt.style.top=`${Qo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",fs.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};Ct.addEventListener("mouseenter",kr),Ct.addEventListener("mouseleave",an),pt.addEventListener("focus",kr),pt.addEventListener("blur",an),Ct._cleanupTooltip=()=>{an(),Ct&&(Ct.removeEventListener("mouseenter",kr),Ct.removeEventListener("mouseleave",an)),pt&&(pt.removeEventListener("focus",kr),pt.removeEventListener("blur",an))}}}}let Gr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ys],Fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ga.message,ga.messageAndClick];E=Zs({parsers:Gr,handlers:Fr,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),be=Yx(n,E,oe),I.updateConfig(n),Uo(qe,I.getMessages(),be),Wn.render(n.suggestionChips,I,ge,void 0,n.suggestionChipsConfig),ns(),ya(I.isStreaming());let Vo=((Hm=n.voiceRecognition)==null?void 0:Hm.enabled)===!0,jo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Go=((Om=(Dm=n.voiceRecognition)==null?void 0:Dm.provider)==null?void 0:Om.type)==="runtype";if(Vo&&(jo||Go))if(!G||!Jt){let ne=xi(n.voiceRecognition,n.sendButton);ne&&(G=ne.micButton,Jt=ne.micButtonWrapper,Mt.insertBefore(Jt,Re),G.addEventListener("click",te),G.disabled=I.isStreaming())}else{let ne=(_m=n.voiceRecognition)!=null?_m:{},Dt=(Nm=n.sendButton)!=null?Nm:{},rr=(Fm=ne.iconName)!=null?Fm:"mic",At=($m=Dt.size)!=null?$m:"40px",Ut=(Um=ne.iconSize)!=null?Um:At,Mr=parseFloat(Ut)||24;G.style.width=Ut,G.style.height=Ut,G.style.minWidth=Ut,G.style.minHeight=Ut;let $r=(qm=(zm=ne.iconColor)!=null?zm:Dt.textColor)!=null?qm:"currentColor";G.innerHTML="";let Nn=Ie(rr,Mr,$r,2);Nn?G.appendChild(Nn):G.textContent="\u{1F3A4}";let Xr=(Vm=ne.backgroundColor)!=null?Vm:Dt.backgroundColor;Xr?G.style.backgroundColor=Xr:G.style.backgroundColor="",$r?G.style.color=$r:G.style.color="var(--persona-text, #111827)",ne.borderWidth?(G.style.borderWidth=ne.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ne.borderColor?G.style.borderColor=ne.borderColor:G.style.borderColor="",ne.paddingX?(G.style.paddingLeft=ne.paddingX,G.style.paddingRight=ne.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ne.paddingY?(G.style.paddingTop=ne.paddingY,G.style.paddingBottom=ne.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let br=Jt==null?void 0:Jt.querySelector(".persona-send-button-tooltip"),mn=(jm=ne.tooltipText)!=null?jm:"Start voice recognition";if(((Gm=ne.showTooltip)!=null?Gm:!1)&&mn)if(br)br.textContent=mn,br.style.display="";else{let kr=document.createElement("div");kr.className="persona-send-button-tooltip",kr.textContent=mn,Jt==null||Jt.insertBefore(kr,G)}else br&&(br.style.display="none");Jt.style.display="",G.disabled=I.isStreaming()}else G&&Jt&&(Jt.style.display="none",((Xm=(Km=n.voiceRecognition)==null?void 0:Km.provider)==null?void 0:Xm.type)==="runtype"?I.isVoiceActive()&&I.toggleVoice():un&&_n());if(((Jm=n.attachments)==null?void 0:Jm.enabled)===!0)if(!Nt||!at){let ne=(Qm=n.attachments)!=null?Qm:{},rr=(Zm=((Ym=n.sendButton)!=null?Ym:{}).size)!=null?Zm:"40px";ye||(ye=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ye.style.display="none",Ae.insertBefore(ye,ge)),de||(de=document.createElement("input"),de.type="file",de.accept=((eg=ne.allowedTypes)!=null?eg:mo).join(","),de.multiple=((tg=ne.maxFiles)!=null?tg:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Ae.insertBefore(de,ge)),Nt=v("div","persona-send-button-wrapper"),at=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),at.type="button",at.setAttribute("aria-label",(rg=ne.buttonTooltipText)!=null?rg:"Attach file");let At=(ng=ne.buttonIconName)!=null?ng:"paperclip",Ut=rr,Mr=parseFloat(Ut)||40,$r=Math.round(Mr*.6);at.style.width=Ut,at.style.height=Ut,at.style.minWidth=Ut,at.style.minHeight=Ut,at.style.fontSize="18px",at.style.lineHeight="1",at.style.backgroundColor="transparent",at.style.color="var(--persona-primary, #111827)",at.style.border="none",at.style.borderRadius="6px",at.style.transition="background-color 0.15s ease",at.addEventListener("mouseenter",()=>{at.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),at.addEventListener("mouseleave",()=>{at.style.backgroundColor="transparent"});let Nn=Ie(At,$r,"currentColor",1.5);Nn?at.appendChild(Nn):at.textContent="\u{1F4CE}",at.addEventListener("click",mn=>{mn.preventDefault(),de==null||de.click()}),Nt.appendChild(at);let Xr=(og=ne.buttonTooltipText)!=null?og:"Attach file",br=v("div","persona-send-button-tooltip");br.textContent=Xr,Nt.appendChild(br),ot.append(Nt),!ft&&de&&ye&&(ft=da.fromConfig(ne),ft.setPreviewsContainer(ye),de.addEventListener("change",async()=>{ft&&(de!=null&&de.files)&&(await ft.handleFileSelect(de.files),de.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(Zx(ne.dropOverlay))}else{Nt.style.display="";let ne=(ag=n.attachments)!=null?ag:{};de&&(de.accept=((sg=ne.allowedTypes)!=null?sg:mo).join(","),de.multiple=((ig=ne.maxFiles)!=null?ig:4)>1),ft&&ft.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else Nt&&(Nt.style.display="none"),ft&&ft.clearAttachments(),(lg=me.querySelector(".persona-attachment-drop-overlay"))==null||lg.remove();let cr=(dg=n.sendButton)!=null?dg:{},Ko=(cg=cr.useIcon)!=null?cg:!1,Po=(pg=cr.iconText)!=null?pg:"\u2191",Bt=cr.iconName,rn=(ug=cr.tooltipText)!=null?ug:"Send message",io=(fg=cr.showTooltip)!=null?fg:!1,Kr=(mg=cr.size)!=null?mg:"40px",nn=cr.backgroundColor,Yt=cr.textColor;if(Ko){if(q.style.width=Kr,q.style.height=Kr,q.style.minWidth=Kr,q.style.minHeight=Kr,q.style.fontSize="18px",q.style.lineHeight="1",q.innerHTML="",Yt?q.style.color=Yt:q.style.color="var(--persona-button-primary-fg, #ffffff)",Bt){let ne=parseFloat(Kr)||24,Dt=(Yt==null?void 0:Yt.trim())||"currentColor",rr=Ie(Bt,ne,Dt,2);rr?q.appendChild(rr):q.textContent=Po}else q.textContent=Po;q.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nn?(q.style.backgroundColor=nn,q.classList.remove("persona-bg-persona-primary")):(q.style.backgroundColor="",q.classList.add("persona-bg-persona-primary"))}else q.textContent=(hg=(gg=n.copy)==null?void 0:gg.sendButtonLabel)!=null?hg:"Send",q.style.width="",q.style.height="",q.style.minWidth="",q.style.minHeight="",q.style.fontSize="",q.style.lineHeight="",q.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nn?(q.style.backgroundColor=nn,q.classList.remove("persona-bg-persona-accent")):q.classList.add("persona-bg-persona-accent"),Yt?q.style.color=Yt:q.classList.add("persona-text-white");cr.borderWidth?(q.style.borderWidth=cr.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),cr.borderColor?q.style.borderColor=cr.borderColor:q.style.borderColor="",cr.paddingX?(q.style.paddingLeft=cr.paddingX,q.style.paddingRight=cr.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),cr.paddingY?(q.style.paddingTop=cr.paddingY,q.style.paddingBottom=cr.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let ir=Re==null?void 0:Re.querySelector(".persona-send-button-tooltip");if(io&&rn)if(ir)ir.textContent=rn,ir.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=rn,Re==null||Re.insertBefore(ne,q)}else ir&&(ir.style.display="none");let Zt=(vg=(xg=n.layout)==null?void 0:xg.contentMaxWidth)!=null?vg:W()?(wg=(bg=(yg=n.launcher)==null?void 0:yg.composerBar)==null?void 0:bg.contentMaxWidth)!=null?wg:"720px":void 0;Zt?(qe.style.maxWidth=Zt,qe.style.marginLeft="auto",qe.style.marginRight="auto",qe.style.width="100%",Ae&&(Ae.style.maxWidth=Zt,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Z&&(Z.style.maxWidth=Zt,Z.style.marginLeft="auto",Z.style.marginRight="auto")):(qe.style.maxWidth="",qe.style.marginLeft="",qe.style.marginRight="",qe.style.width="",Ae&&(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight=""),Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight=""));let pr=(Cg=n.statusIndicator)!=null?Cg:{},on=(Ag=pr.visible)!=null?Ag:!0;if(fe.style.display=on?"":"none",I){let ne=I.getStatus();ut(fe,(rr=>{var At,Ut,Mr,$r;return rr==="idle"?(At=pr.idleText)!=null?At:Ur.idle:rr==="connecting"?(Ut=pr.connectingText)!=null?Ut:Ur.connecting:rr==="connected"?(Mr=pr.connectedText)!=null?Mr:Ur.connected:rr==="error"?($r=pr.errorText)!=null?$r:Ur.error:Ur[rr]})(ne),pr,ne)}fe.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=pr.align==="left"?"persona-text-left":pr.align==="center"?"persona-text-center":"persona-text-right";fe.classList.add(fn)},open(){R()&&Kt(!0,"api")},close(){R()&&Kt(!1,"api")},toggle(){R()&&Kt(!B,"api")},clearChat(){Se=!1,I.clearMessages(),Bn.clear(),Co();try{localStorage.removeItem(Ga),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(w=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},E.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),ae==null||ae.update()},setMessage(c){return!ge||I.isStreaming()?!1:(!B&&R()&&Kt(!0,"system"),ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(I.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ge.value.trim();return g?(!B&&R()&&Kt(!0,"system"),ge.value="",ge.style.height="auto",I.sendMessage(g),!0):!1},startVoiceRecognition(){var g,w;return I.isStreaming()?!1:((w=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:w.type)==="runtype"?(I.isVoiceActive()||(!B&&R()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),An("user"),I.isVoiceActive()&&z()})),!0):un?!0:cs()?(!B&&R()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),qo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?I.isVoiceActive()?(I.toggleVoice().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),Y()}),!0):!1:un?(Lt.manuallyDeactivated=!0,tn(),_n("user"),!0):!1},injectMessage(c){return!B&&R()&&Kt(!0,"system"),I.injectMessage(c)},injectAssistantMessage(c){!B&&R()&&Kt(!0,"system");let g=I.injectAssistantMessage(c);return _&&(_=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{I&&!I.isStreaming()&&I.continueConversation()},100)),g},injectUserMessage(c){return!B&&R()&&Kt(!0,"system"),I.injectUserMessage(c)},injectSystemMessage(c){return!B&&R()&&Kt(!0,"system"),I.injectSystemMessage(c)},injectMessageBatch(c){return!B&&R()&&Kt(!0,"system"),I.injectMessageBatch(c)},injectComponentDirective(c){return!B&&R()&&Kt(!0,"system"),I.injectComponentDirective(c)},injectTestMessage(c){!B&&R()&&Kt(!0,"system"),I.injectTestEvent(c)},async connectStream(c,g){return I.connectStream(c,g)},__pushEventStreamEvent(c){K&&(Te==null||Te.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ve||!K||Lr()},hideEventStream(){xe&&Or()},isEventStreamVisible(){return xe},showArtifacts(){Ln(n)&&(Se=!1,ln(),ue==null||ue.setMobileOpen(!0))},hideArtifacts(){Ln(n)&&(Se=!0,ln())},upsertArtifact(c){return Ln(n)?(Se=!1,I.upsertArtifact(c)):null},selectArtifact(c){Ln(n)&&I.selectArtifact(c)},clearArtifacts(){Ln(n)&&I.clearArtifacts()},getArtifacts(){var c;return(c=I==null?void 0:I.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=I==null?void 0:I.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!B&&!W()||!ge?!1:(ge.focus(),!0)},async resolveApproval(c,g){let C=I.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===c});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${c}`);if(C.approval.toolType==="webmcp"){I.resolveWebMcpApproval(C.id,g);return}return I.resolveApproval(C.approval,g)},getMessages(){return I.getMessages()},getStatus(){return I.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return R()&&B},isVoiceActive(){return Lt.active},getState(){return{open:R()&&B,launcherEnabled:T,voiceActive:Lt.active,streaming:I.isStreaming()}},showCSATFeedback(c){!B&&R()&&Kt(!0,"system");let g=qe.querySelector(".persona-feedback-container");g&&g.remove();let w=Jl({onSubmit:async(C,D)=>{var $;I.isClientTokenMode()&&await I.submitCSATFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});qe.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&R()&&Kt(!0,"system");let g=qe.querySelector(".persona-feedback-container");g&&g.remove();let w=Ql({onSubmit:async(C,D)=>{var $;I.isClientTokenMode()&&await I.submitNPSFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});qe.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return I.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return I.submitNPSFeedback(c,g)},destroy(){Vn!=null&&(clearInterval(Vn),Vn=null),Pt.forEach(c=>c()),Ce.remove(),tt==null||tt.remove(),Fe==null||Fe.destroy(),lt==null||lt.remove(),cn&&Q.removeEventListener("click",cn)}};if((((Cf=r==null?void 0:r.debugTools)!=null?Cf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:vr,getMessages:vr.getMessages,getStatus:vr.getStatus,getMetadata:vr.getPersistentMetadata,updateMetadata:vr.updatePersistentMetadata,clearHistory:()=>vr.clearChat(),setVoiceActive:w=>w?vr.startVoiceRecognition():vr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Pt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.focusInput()};if(window.addEventListener("persona:focusInput",g),Pt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ve){let j=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.showEventStream()},F=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",F),Pt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",F)})}let w=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.showArtifacts()},C=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.hideArtifacts()},D=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&vr.upsertArtifact(F.artifact)},$=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&vr.selectArtifact(F.id)},U=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),Pt.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Tn=dC(n.persistState);if(Tn&&R()){let c=cC(Tn.storage),g=`${Tn.keyPrefix}widget-open`,w=`${Tn.keyPrefix}widget-voice`,C=`${Tn.keyPrefix}widget-voice-mode`;if(c){let D=((Af=Tn.persist)==null?void 0:Af.openState)&&c.getItem(g)==="true",$=((Sf=Tn.persist)==null?void 0:Sf.voiceState)&&c.getItem(w)==="true",U=((Tf=Tn.persist)==null?void 0:Tf.voiceState)&&c.getItem(C)==="true";if(D&&setTimeout(()=>{vr.open(),setTimeout(()=>{var j;if($||U)vr.startVoiceRecognition();else if((j=Tn.persist)!=null&&j.focusInput){let F=t.querySelector("textarea");F&&F.focus()}},100)},0),(Mf=Tn.persist)!=null&&Mf.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(kf=Tn.persist)!=null&&kf.voiceState&&(s.on("voice:state",j=>{c.setItem(w,j.active?"true":"false")}),s.on("user:message",j=>{c.setItem(C,j.viaVoice?"true":"false")})),Tn.clearOnChatClear){let j=()=>{c.removeItem(g),c.removeItem(w),c.removeItem(C)},F=()=>j();window.addEventListener("persona:clear-chat",F),Pt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return p&&R()&&setTimeout(()=>{vr.open()},0),ao(),vr};var pC=(t,e)=>{let r=t.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,e*parseFloat(o[1])/100):420},ey=(t,e)=>{var n,o;let r=(o=(n=e==null?void 0:e.launcher)==null?void 0:n.enabled)!=null?o:!0;t.className="persona-host",t.style.height=r?"":"100%",t.style.display=r?"":"flex",t.style.flexDirection=r?"":"column",t.style.flex=r?"":"1 1 auto",t.style.minHeight=r?"":"0"},mu=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},ty=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.minWidth="",mu(t)},pu=t=>{t.style.transition=""},uu=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform=""},fu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},ed=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},uC=(t,e,r,n,o)=>{o?r.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(r,n),t.appendChild(e)):r.parentElement===e&&(e.replaceChildren(),t.appendChild(r),t.appendChild(n))},fC=(t,e,r,n,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==n&&a.replaceChildren(n,r):a.lastElementChild!==n&&a.replaceChildren(r,n)},ry=(t,e,r,n,o,s,a)=>{var y,A,E,T,S,k;let i=kn(s),d=i.reveal==="push";uC(t,e,r,n,d),fC(t,e,r,n,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=t.ownerDocument.defaultView,p=(A=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?A:!0,m=(T=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?T:640,u=l!=null?l.innerWidth<=m:!1;if(p&&u&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),uu(e),pu(n),ty(n),fu(r),ed(o,n),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((k=(S=s==null?void 0:s.launcher)==null?void 0:S.zIndex)!=null?k:zr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),ty(n),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",uu(e),pu(n),fu(r),ed(o,n);let x=i.animate?"transform 180ms ease":"none",b=i.side==="right"?"translateX(100%)":"translateX(-100%)",h=a?"translateX(0)":b;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=x,n.style.transform=h,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",pu(n),mu(n),ed(o,n);let x=pC(i.width,t.clientWidth),b=Math.max(0,t.clientWidth),h=i.animate?"transform 180ms ease":"none",M=i.side==="right"?a?`translateX(-${x}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${x}px)`;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${b+x}px`,e.style.transition=h,e.style.transform=M,r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${b}px`,r.style.maxWidth=`${b}px`,r.style.minWidth=`${b}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",uu(e),mu(n),fu(r),ed(o,n);let x=i.reveal==="emerge";x?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let b=a?i.width:"0px",h=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${b}`,n.style.width=b,n.style.maxWidth=b,n.style.minWidth=b,n.style.minHeight="0",n.style.position="relative",n.style.overflow=x||M?"hidden":"visible",n.style.transition=h,x&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},mC=(t,e)=>{let r=t.ownerDocument.createElement("div");return ey(r,e),t.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){ey(r,n)},destroy(){r.remove()}}},gC=(t,e)=>{var S,k,x,b;let{ownerDocument:r}=t,n=t.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=t.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=r.createElement("div"),i=r.createElement("div"),d=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),m=(k=(S=e==null?void 0:e.launcher)==null?void 0:S.enabled)==null||k?(b=(x=e==null?void 0:e.launcher)==null?void 0:x.autoExpand)!=null?b:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),n.insertBefore(a,t),d.appendChild(t);let u=null,f=()=>{u==null||u.disconnect(),u=null},y=()=>{f(),kn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{ry(a,i,d,l,p,e,m)}),u.observe(a))},A=()=>{ry(a,i,d,l,p,e,m),y()},E=a.ownerDocument.defaultView,T=()=>{A()};return E==null||E.addEventListener("resize",T),kn(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),A(),{mode:"docked",host:p,shell:a,syncWidgetState(h){let M=h.launcherEnabled?h.open:!0;m!==M&&(m=M,A())},updateConfig(h){var M,W;e=h,((W=(M=e==null?void 0:e.launcher)==null?void 0:M.enabled)!=null?W:!0)===!1&&(m=!0),A()},destroy(){E==null||E.removeEventListener("resize",T),f(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(t,s):n.appendChild(t)),a.remove()}}},ei=(t,e)=>Ar(e)?gC(t,e):mC(t,e);var gu={},hC=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let e=document.querySelector(t);if(!e)throw new Error(`Chat widget target "${t}" was not found`);return e}return t},xC=()=>{try{if(typeof gu!="undefined"&&gu.url)return new URL("../widget.css",gu.url).href}catch{}return null},ny=(t,e)=>{let r=xC(),n=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let o=e.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);t.insertBefore(s,t.firstChild)};if(t instanceof ShadowRoot)if(r){let o=e.createElement("link");o.rel="stylesheet",o.href=r,o.setAttribute("data-persona","true"),t.insertBefore(o,t.firstChild)}else n();else if(!e.head.querySelector("link[data-persona]")&&r){let s=e.createElement("link");s.rel="stylesheet",s.href=r,s.setAttribute("data-persona","true"),e.head.appendChild(s)}},oy=t=>{var E;let e=hC(t.target),r=t.useShadowDom===!0,n=e.ownerDocument,o=t.config,s=ei(e,o),a,i=[],d=(T,S)=>{var h,M;let x=!((M=(h=S==null?void 0:S.launcher)==null?void 0:h.enabled)!=null?M:!0)||Ar(S),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),x&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0"),r){let W=T.attachShadow({mode:"open"});W.appendChild(b),ny(W,n)}else T.appendChild(b),ny(T,n);return e.id&&b.setAttribute("data-persona-instance",e.id),b},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let T=d(s.host,o);a=Zl(T,o,{debugTools:t.debugTools}),p()},u=()=>{i.forEach(T=>T()),i=[],a.destroy()};m(),(E=t.onReady)==null||E.call(t);let f=T=>{u(),s.destroy(),s=ei(e,T),o=T,m()},y={update(T){var M,W,R,B,_,V;let S={...o,...T,launcher:{...(M=o==null?void 0:o.launcher)!=null?M:{},...(W=T==null?void 0:T.launcher)!=null?W:{},dock:{...(B=(R=o==null?void 0:o.launcher)==null?void 0:R.dock)!=null?B:{},...(V=(_=T==null?void 0:T.launcher)==null?void 0:_.dock)!=null?V:{}}}},k=Ar(o),x=Ar(S),b=Bo(o),h=Bo(S);if(k!==x||b!==h){f(S);return}o=S,s.updateConfig(o),a.update(T),l()},destroy(){u(),s.destroy(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}},A=new Proxy(y,{get(T,S,k){if(S==="host")return s.host;if(S in T)return Reflect.get(T,S,k);let x=a[S];return typeof x=="function"?x.bind(a):x}});return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=A),A};var dy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),yC=new Set(["button","a","input","select","textarea","details","summary"]),bC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),hu=/\b(product|card|item|listing|result)\b/i,yu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,wC=3e3,vC=100;function cy(t){let e=typeof t.className=="string"?t.className:"";if(hu.test(e)||t.id&&hu.test(t.id))return!0;for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];if(n.name.startsWith("data-")&&hu.test(n.value))return!0}return!1}function py(t){var e;return yu.test(((e=t.textContent)!=null?e:"").trim())}function uy(t){var r;let e=t.querySelectorAll("a[href]");for(let n=0;n<e.length;n++){let o=(r=e[n].getAttribute("href"))!=null?r:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function CC(t){return!!t.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ay(t){let e=t.match(yu);return e?e[0]:null}function sy(t){var n,o,s;let e=(n=t.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:t.querySelector("a[href]");if(e&&((o=e.textContent)!=null&&o.trim())){let a=e.getAttribute("href");return{title:e.textContent.trim(),href:a&&a!=="#"?a:null}}let r=t.querySelector("h1, h2, h3, h4, h5, h6");return(s=r==null?void 0:r.textContent)!=null&&s.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function AC(t){let e=[],r=n=>{let o=n.trim();o&&!e.includes(o)&&e.push(o)};return t.querySelectorAll("button").forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('[role="button"]').forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;r((o=n.value)!=null?o:"")}),e.slice(0,6)}var SC="commerce-card",TC="result-card";function iy(t){return!cy(t)||!py(t)||!uy(t)&&!CC(t)?0:5200}function ly(t){var n;return!cy(t)||py(t)||!uy(t)||((n=t.textContent)!=null?n:"").trim().length<20||!(!!t.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!t.querySelector(".snippet, .description, p"))?0:2800}var bu=[{id:SC,scoreElement(t){return iy(t)},shouldSuppressDescendant(t,e,r){if(e===t||!t.contains(e))return!1;if(r.interactivity==="static"){let n=r.text.trim();return!!(n.length===0||yu.test(n)&&n.length<32)}return!0},formatSummary(t,e){var d,l,p;if(iy(t)===0)return null;let{title:r,href:n}=sy(t),o=(p=(l=ay(((d=t.textContent)!=null?d:"").trim()))!=null?l:ay(e.text))!=null?p:"",s=AC(t);return[n&&r?`[${r}](${n})${o?` \u2014 ${o}`:""}`:r?`${r}${o?` \u2014 ${o}`:""}`:o||e.text.trim().slice(0,120),`selector: ${e.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
158
+ `)}},{id:TC,scoreElement(t){return ly(t)},formatSummary(t,e){if(ly(t)===0)return null;let{title:r,href:n}=sy(t);return[n&&r?`[${r}](${n})`:r||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
159
+ `)}}];function MC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function kC(t){var p,m,u,f,y,A,E,T,S,k,x,b,h;let e=(p=t.options)!=null?p:{},r=(u=(m=e.maxElements)!=null?m:t.maxElements)!=null?u:80,n=(y=(f=e.excludeSelector)!=null?f:t.excludeSelector)!=null?y:".persona-host",o=(E=(A=e.maxTextLength)!=null?A:t.maxTextLength)!=null?E:200,s=(S=(T=e.visibleOnly)!=null?T:t.visibleOnly)!=null?S:!0,a=(k=e.root)!=null?k:t.root,i=(x=e.mode)!=null?x:"structured",d=(b=e.maxCandidates)!=null?b:Math.max(500,r*10),l=(h=t.rules)!=null?h:bu;return i==="simple"&&t.rules&&t.rules.length>0?(MC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function xu(t){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/([^\w-])/g,"\\$1")}var EC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function LC(t){let e=t.tagName.toLowerCase(),r=t.getAttribute("role");return e==="a"&&t.hasAttribute("href")?"navigable":e==="input"||e==="select"||e==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":e==="button"||r==="button"||yC.has(e)||r&&bC.has(r)||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||t.getAttribute("contenteditable")==="true"?"clickable":"static"}function fy(t){if(t.hidden)return!1;try{let e=getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden")return!1}catch{}return!(t.style.display==="none"||t.style.visibility==="hidden")}function PC(t){let e={},r=t.id;r&&(e.id=r);let n=t.getAttribute("href");n&&(e.href=n);let o=t.getAttribute("aria-label");o&&(e["aria-label"]=o);let s=t.getAttribute("type");s&&(e.type=s);let a=t.getAttribute("value");a&&(e.value=a);let i=t.getAttribute("name");i&&(e.name=i);let d=t.getAttribute("role");d&&(e.role=d);for(let l=0;l<t.attributes.length;l++){let p=t.attributes[l];p.name.startsWith("data-")&&(e[p.name]=p.value)}return e}function wu(t){let e=t.tagName.toLowerCase();if(t.id){let o=`#${xu(t.id)}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of EC){let s=t.getAttribute(o);if(s){let a=`${e}[${o}="${xu(s)}"]`;try{if(t.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let r=Array.from(t.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${e}.${r.map(a=>xu(a)).join(".")}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=t.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${e}`)).indexOf(t);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(t.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=t.parentElement;if(n){let s=Array.from(n.querySelectorAll(`:scope > ${e}`)).indexOf(t);if(s>=0)return`${e}:nth-of-type(${s+1})`}return e}function IC(t){return t==="static"?vC:wC}function my(t,e){var o;let r=t.tagName.toLowerCase(),n=((o=t.textContent)!=null?o:"").trim().substring(0,e);return{selector:wu(t),tagName:r,text:n,role:t.getAttribute("role"),interactivity:LC(t),attributes:PC(t)}}function RC(t,e,r,n){let o=IC(e.interactivity),s=null;for(let a of r){let i=a.scoreElement(t,e,n);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function WC(t,e){var r;for(let n of t)if(e.el!==n.el&&(r=n.formattingRule)!=null&&r.shouldSuppressDescendant&&n.el.contains(e.el)&&n.formattingRule.shouldSuppressDescendant(n.el,e.el,e.enriched))return!0;return!1}function BC(t,e){let r={doc:e.ownerDocument,maxTextLength:t.maxTextLength},n=new Set,o=[],s=0,a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<t.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(dy.has(p)){i=a.nextNode();continue}if(t.excludeSelector)try{if(l.closest(t.excludeSelector)){i=a.nextNode();continue}}catch{}if(t.visibleOnly&&!fy(l)){i=a.nextNode();continue}let m=my(l,t.maxTextLength),u=m.text.length>0,f=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(E=>E==="role");if(!u&&!f){i=a.nextNode();continue}if(n.has(m.selector)){i=a.nextNode();continue}n.add(m.selector);let{score:y,formattingRule:A}=RC(l,m,t.rules,r);o.push({el:l,domIndex:s,enriched:m,score:y,formattingRule:A}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return m!==u?m-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=t.maxElements)break;WC(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return m!==u?m-u:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var u;let p;if((u=l.formattingRule)!=null&&u.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,r);f&&(p=f)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function HC(t,e){let r=[],n=new Set,o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&r.length<t.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(dy.has(l)){s=o.nextNode();continue}if(t.excludeSelector)try{if(d.closest(t.excludeSelector)){s=o.nextNode();continue}}catch{}if(t.visibleOnly&&!fy(d)){s=o.nextNode();continue}let p=my(d,t.maxTextLength),m=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!m&&!u){s=o.nextNode();continue}n.has(p.selector)||(n.add(p.selector),r.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of r)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,t.maxElements)}function gy(t={}){var n;let e=kC(t),r=(n=e.root)!=null?n:document.body;return r?e.mode==="simple"?HC(e,r):BC(e,r):[]}var td=100;function hy(t,e={}){var s;if(t.length===0)return"No page elements found.";let r=(s=e.mode)!=null?s:"structured",n=[];if(r==="structured"){let a=t.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
160
160
  ${a.map(i=>`- ${i.split(`
161
161
  `).join(`
162
162
  `)}`).join(`
163
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)r==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,od)}" (clickable)`);n.push(`Interactive elements:
163
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of t)r==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,td)}" (clickable)`);n.push(`Interactive elements:
164
164
  ${a.join(`
165
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,od)}" (navigable)`);n.push(`Navigation links:
165
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,td)}" (navigable)`);n.push(`Navigation links:
166
166
  ${a.join(`
167
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,od)}" (input)`);n.push(`Form inputs:
167
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,td)}" (input)`);n.push(`Form inputs:
168
168
  ${a.join(`
169
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,od)}"`);n.push(`Content:
169
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,td)}"`);n.push(`Content:
170
170
  ${a.join(`
171
171
  `)}`)}return n.join(`
172
172
 
173
- `)}var ky={name:"@runtypelabs/persona",version:"3.24.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var xs=ky.version;function bo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function sS(e){if(e)return{getHeaders:bo(e.getHeaders),onFeedback:bo(e.onFeedback),onCopy:bo(e.onCopy),requestMiddleware:bo(e.requestMiddleware),actionHandlers:bo(e.actionHandlers),actionParsers:bo(e.actionParsers),postprocessMessage:bo(e.postprocessMessage),contextProviders:bo(e.contextProviders),streamParser:bo(e.streamParser)}}var Ey=`({ text, message }: any) => {
174
- const jsonSource = (message as any).rawContent || text || message.content;
175
- if (!jsonSource || typeof jsonSource !== 'string') return null;
176
- let cleanJson = jsonSource
177
- .replace(/^\`\`\`(?:json)?\\s*\\n?/, '')
178
- .replace(/\\n?\`\`\`\\s*$/, '')
179
- .trim();
180
- if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;
181
- try {
182
- const parsed = JSON.parse(cleanJson);
183
- if (parsed.action) return { type: parsed.action, payload: parsed };
184
- } catch (e) { return null; }
185
- return null;
186
- }`,Ly=`function(ctx) {
187
- var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
188
- if (!jsonSource || typeof jsonSource !== 'string') return null;
189
- var cleanJson = jsonSource
190
- .replace(/^\`\`\`(?:json)?\\s*\\n?/, '')
191
- .replace(/\\n?\`\`\`\\s*$/, '')
192
- .trim();
193
- if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;
194
- try {
195
- var parsed = JSON.parse(cleanJson);
196
- if (parsed.action) return { type: parsed.action, payload: parsed };
197
- } catch (e) { return null; }
198
- return null;
199
- }`,Py=`(action: any, context: any) => {
200
- if (action.type !== 'nav_then_click') return;
201
- const payload = action.payload || action.raw || {};
202
- const url = payload?.page;
203
- const text = payload?.on_load_text || 'Navigating...';
204
- if (!url) return { handled: true, displayText: text };
205
- const messageId = context.message?.id;
206
- const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');
207
- const actionKey = \`nav_\${messageId}_\${url}\`;
208
- if (processedActions.includes(actionKey)) {
209
- return { handled: true, displayText: text };
210
- }
211
- processedActions.push(actionKey);
212
- localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));
213
- const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
214
- window.location.href = targetUrl;
215
- return { handled: true, displayText: text };
216
- }`,Iy=`function(action, context) {
217
- if (action.type !== 'nav_then_click') return;
218
- var payload = action.payload || action.raw || {};
219
- var url = payload.page;
220
- var text = payload.on_load_text || 'Navigating...';
221
- if (!url) return { handled: true, displayText: text };
222
- var messageId = context.message ? context.message.id : null;
223
- var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');
224
- var actionKey = 'nav_' + messageId + '_' + url;
225
- if (processedActions.includes(actionKey)) {
226
- return { handled: true, displayText: text };
227
- }
228
- processedActions.push(actionKey);
229
- localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));
230
- var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
231
- window.location.href = targetUrl;
232
- return { handled: true, displayText: text };
233
- }`,aS=`(parsed: any) => {
234
- if (!parsed || typeof parsed !== 'object') return null;
235
- if (parsed.action === 'nav_then_click') return 'Navigating...';
236
- if (parsed.action === 'message') return parsed.text || '';
237
- if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
238
- return parsed.text || null;
239
- }`,iS=`function(parsed) {
240
- if (!parsed || typeof parsed !== 'object') return null;
241
- if (parsed.action === 'nav_then_click') return 'Navigating...';
242
- if (parsed.action === 'message') return parsed.text || '';
243
- if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
244
- return parsed.text || null;
245
- }`;function lS(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function sd(e){var t,r;return(r=(t=e.parserType)!=null?t:lS(e.streamParser))!=null?r:"plain"}function ad(e,t){let r=[];return e.toolCall&&(r.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([n,o])=>{typeof o=="string"&&r.push(`${t} ${n}: "${o}",`)}),r.push(`${t}},`)),r}function id(e,t,r){let n=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(n.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${a}: ${i},`))}),r!=null&&r.onFeedback&&n.push(`${t} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&n.push(`${t} onCopy: ${r.onCopy},`),n.push(`${t}},`)),n}function ld(e,t){let r=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(n||o)&&(r.push(`${t}markdown: {`),n&&(r.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?r.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&r.push(`${t} ${s}: ${a},`)}),r.push(`${t} },`)),o&&r.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${t}},`))}return r}function dd(e,t){let r=[];if(e.layout){let n=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(n||o)&&(r.push(`${t}layout: {`),n&&(r.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?r.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&r.push(`${t} ${s}: ${a},`))}),r.push(`${t} },`)),o&&(r.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(r.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?r.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&r.push(`${t} ${i}: ${d},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?r.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&r.push(`${t} ${d}: ${l},`))}),r.push(`${t} },`)):typeof a=="string"?r.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&r.push(`${t} ${s}: ${a},`))}),r.push(`${t} },`)),r.push(`${t}},`))}return r}function Lu(e,t){let r=[];return e&&(e.getHeaders&&r.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${t}streamParser: ${e.streamParser},`)),r}function Ry(e,t,r){Object.entries(t).forEach(([n,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${r}${n}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${r}${n}: {`),Ry(e,o,`${r} `),e.push(`${r}},`);return}e.push(`${r}${n}: ${JSON.stringify(o)},`)}})}function $o(e,t,r,n){r&&(e.push(`${n}${t}: {`),Ry(e,r,`${n} `),e.push(`${n}},`))}function Wy(e,t="esm",r){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let o=r?{...r,hooks:sS(r.hooks)}:void 0;return t==="esm"?dS(n,o):t==="script-installer"?uS(n,o):t==="script-advanced"?mS(n,o):t==="react-component"?cS(n,o):t==="react-advanced"?pS(n,o):fS(n,o)}function dS(e,t){let r=t==null?void 0:t.hooks,n=sd(e),o=n!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&$o(s,"theme",e.theme," "),e.launcher&&$o(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ad(e," ")),s.push(...id(e," ",r)),s.push(...ld(e," ")),s.push(...dd(e," ")),s.push(...Lu(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
246
- `)}function cS(e,t){let r=t==null?void 0:t.hooks,n=sd(e),o=n!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&$o(s,"theme",e.theme," "),e.launcher&&$o(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ad(e," ")),s.push(...id(e," ",r)),s.push(...ld(e," ")),s.push(...dd(e," ")),s.push(...Lu(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
247
- `)}function pS(e,t){let r=t==null?void 0:t.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&$o(n,"theme",e.theme," "),e.launcher&&$o(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{n.push(` ${o}: "${s}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?n.push(` ${o}: "${s}",`):typeof s=="boolean"&&n.push(` ${o}: ${s},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?n.push(` ${o}: "${s}",`):typeof s=="boolean"?n.push(` ${o}: ${s},`):typeof s=="number"&&n.push(` ${o}: ${s},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?n.push(` ${o}: "${s}",`):typeof s=="boolean"&&n.push(` ${o}: ${s},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{n.push(` ${o}: ${s},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...ad(e," ")),n.push(...id(e," ",r)),n.push(...ld(e," ")),n.push(...dd(e," ")),r!=null&&r.getHeaders&&n.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&n.push(` contextProviders: ${r.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?n.push(` streamParser: ${r.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${aS}),`)),r!=null&&r.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${Ey}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${Ey}`),n.push(" ],")),r!=null&&r.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${r.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${Py}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${Py}`),n.push(" ],")),r!=null&&r.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
248
- `)}function Hy(e){var o;let t=sd(e),r=t!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),r&&(n.parserType=t),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(n.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(n.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(n.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(n.layout=s)}return n}function uS(e,t){let r=Hy(e),n=t!=null&&t.windowKey?{config:r,windowKey:t.windowKey}:r,o=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xs}/dist/install.global.js" data-config='${o}'></script>`}function fS(e,t){let r=t==null?void 0:t.hooks,n=sd(e),o=n!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xs}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xs}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&$o(s,"theme",e.theme," "),e.launcher&&$o(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ad(e," ")),s.push(...id(e," ",r)),s.push(...ld(e," ")),s.push(...dd(e," ")),s.push(...Lu(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
249
- `)}function mS(e,t){let r=t==null?void 0:t.hooks,n=Hy(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
250
- `).map((a,i)=>i===0?a:" "+a).join(`
251
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xs}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${iS});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ly}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ly}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Iy}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Iy}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
252
- `)}var By={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Dy=.1,Oy=.15,_y=1.5,Pu=24,Ny=40,gS=`
253
- /* \u2500\u2500 Root \u2500\u2500 */
254
- .persona-dc-root {
255
- display: flex;
256
- flex-direction: column;
257
- width: 100%;
258
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
259
- font-size: 14px;
260
- color: #111827;
261
- line-height: 1.4;
262
- }
263
-
264
- /* \u2500\u2500 Toolbar \u2500\u2500 */
265
- .persona-dc-toolbar {
266
- display: flex;
267
- align-items: center;
268
- justify-content: space-between;
269
- gap: 12px;
270
- padding: 8px 12px;
271
- background: #fff;
272
- border: 1px solid #e5e7eb;
273
- border-bottom: none;
274
- border-radius: 10px 10px 0 0;
275
- flex-wrap: wrap;
276
- }
277
- .persona-dc-toolbar-lead {
278
- display: flex;
279
- align-items: center;
280
- gap: 6px;
281
- min-width: 0;
282
- }
283
- .persona-dc-toolbar-trail {
284
- display: flex;
285
- align-items: center;
286
- gap: 8px;
287
- flex-wrap: wrap;
288
- }
289
-
290
- .persona-dc-title-btn {
291
- display: inline-flex;
292
- align-items: center;
293
- gap: 4px;
294
- font-weight: 600;
295
- font-size: 13px;
296
- white-space: nowrap;
297
- max-width: 240px;
298
- background: none;
299
- border: 1px solid transparent;
300
- border-radius: 0.375rem;
301
- padding: 4px 6px;
302
- cursor: pointer;
303
- color: inherit;
304
- font-family: inherit;
305
- transition: background-color 0.15s ease, border-color 0.15s ease;
306
- }
307
- .persona-dc-title-btn:hover {
308
- background: #f3f4f6;
309
- border-color: #e5e7eb;
310
- }
311
- .persona-dc-title-btn .persona-dc-title-text {
312
- overflow: hidden;
313
- text-overflow: ellipsis;
314
- }
315
- .persona-dc-title-btn .persona-dc-title-chevron {
316
- flex-shrink: 0;
317
- transition: transform 0.15s ease;
318
- }
319
- .persona-dc-title-btn[aria-expanded="true"] .persona-dc-title-chevron {
320
- transform: rotate(180deg);
321
- }
322
-
323
- /* \u2500\u2500 Title dropdown \u2500\u2500 */
324
- .persona-dc-dropdown {
325
- position: absolute;
326
- top: 100%;
327
- left: 0;
328
- margin-top: 4px;
329
- min-width: 220px;
330
- max-width: 320px;
331
- background: #fff;
332
- border: 1px solid #e5e7eb;
333
- border-radius: 8px;
334
- box-shadow: 0 8px 24px rgba(0,0,0,0.12), 0 2px 6px rgba(0,0,0,0.06);
335
- padding: 4px;
336
- z-index: 100;
337
- max-height: 300px;
338
- overflow-y: auto;
339
- }
340
- .persona-dc-root .persona-dc-dropdown button.persona-dc-dropdown-item {
341
- display: flex;
342
- flex-direction: column;
343
- align-items: flex-start;
344
- justify-content: flex-start;
345
- width: 100%;
346
- padding: 8px 10px;
347
- border: none;
348
- background: none;
349
- border-radius: 6px;
350
- cursor: pointer;
351
- text-align: left;
352
- font-family: inherit;
353
- font-size: 13px;
354
- font-weight: 500;
355
- color: #111827;
356
- transition: background-color 0.1s ease;
357
- }
358
- .persona-dc-root .persona-dc-dropdown button.persona-dc-dropdown-item:hover {
359
- background: #f3f4f6;
360
- }
361
- .persona-dc-root .persona-dc-dropdown button.persona-dc-dropdown-item[aria-current="true"] {
362
- background: #f5f5f5;
363
- color: #0f0f0f;
364
- }
365
- .persona-dc-root .persona-dc-dropdown-desc {
366
- font-weight: 400;
367
- font-size: 12px;
368
- color: #6b7280;
369
- margin-top: 1px;
370
- text-align: left;
371
- }
372
- .persona-dc-root .persona-dc-dropdown button.persona-dc-dropdown-item[aria-current="true"] .persona-dc-dropdown-desc {
373
- color: #737373;
374
- }
375
- .persona-dc-counter {
376
- font-size: 12px;
377
- color: #6b7280;
378
- white-space: nowrap;
379
- }
380
- .persona-dc-zoom-controls {
381
- display: flex;
382
- align-items: center;
383
- gap: 2px;
384
- }
385
- .persona-dc-zoom-level {
386
- font-size: 12px;
387
- color: #6b7280;
388
- min-width: 36px;
389
- text-align: center;
390
- user-select: none;
391
- }
392
- .persona-dc-separator {
393
- width: 1px;
394
- height: 20px;
395
- background: #e5e7eb;
396
- flex-shrink: 0;
397
- }
398
-
399
- /* \u2500\u2500 Stage \u2500\u2500 */
400
- .persona-dc-stage {
401
- height: 550px;
402
- min-height: 400px;
403
- padding: ${Pu}px;
404
- overflow: auto;
405
- background: #f0f1f3;
406
- background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
407
- background-size: 24px 24px;
408
- border: 1px solid #e5e7eb;
409
- border-radius: 0 0 10px 10px;
410
- display: flex;
411
- }
412
-
413
- /* \u2500\u2500 Iframe wrapper \u2500\u2500 */
414
- .persona-dc-iframe-wrapper {
415
- position: relative;
416
- overflow: hidden;
417
- background: #fff;
418
- border-radius: 10px;
419
- box-shadow: 0 16px 64px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
420
- margin: auto;
421
- flex-shrink: 0;
422
- transition: border-radius 0.2s ease;
423
- }
424
- .persona-dc-iframe-wrapper[data-color-scheme="dark"] {
425
- background: #0f172a;
426
- }
427
-
428
- /* \u2500\u2500 Iframe \u2500\u2500 */
429
- .persona-dc-iframe {
430
- border: none;
431
- display: block;
432
- background: #fff;
433
- transform-origin: top left;
434
- }
435
- .persona-dc-iframe-wrapper[data-color-scheme="dark"] .persona-dc-iframe {
436
- background: #0f172a;
437
- }
438
-
439
- /* \u2500\u2500 Button/toggle base styles (standalone, no widget.css dependency) \u2500\u2500 */
440
- .persona-dc-root .persona-icon-btn {
441
- display: inline-flex;
442
- align-items: center;
443
- justify-content: center;
444
- padding: 0.25rem;
445
- border-radius: 0.375rem;
446
- border: 1px solid #e5e7eb;
447
- background: #ffffff;
448
- color: #111827;
449
- cursor: pointer;
450
- line-height: 1;
451
- transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease;
452
- }
453
- .persona-dc-root .persona-icon-btn:hover {
454
- background: #f3f4f6;
455
- }
456
- .persona-dc-root .persona-icon-btn:focus-visible {
457
- outline: 2px solid #171717;
458
- outline-offset: 2px;
459
- }
460
- .persona-dc-root .persona-icon-btn[aria-pressed="true"] {
461
- background: #f3f4f6;
462
- border-color: #d1d5db;
463
- }
464
- .persona-dc-root .persona-toggle-group {
465
- display: inline-flex;
466
- gap: 0;
467
- }
468
- .persona-dc-root .persona-toggle-group > .persona-icon-btn {
469
- border-radius: 0;
470
- }
471
- .persona-dc-root .persona-toggle-group > .persona-icon-btn:first-child {
472
- border-top-left-radius: 0.375rem;
473
- border-bottom-left-radius: 0.375rem;
474
- }
475
- .persona-dc-root .persona-toggle-group > .persona-icon-btn:last-child {
476
- border-top-right-radius: 0.375rem;
477
- border-bottom-right-radius: 0.375rem;
478
- }
479
-
480
- /* \u2500\u2500 Responsive \u2500\u2500 */
481
- @media (max-width: 640px) {
482
- .persona-dc-toolbar {
483
- gap: 8px;
484
- }
485
- .persona-dc-zoom-controls {
486
- display: none;
487
- }
488
- .persona-dc-stage {
489
- height: 400px;
490
- min-height: 300px;
491
- }
492
- }
493
- `;function hS(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=gS,document.head.appendChild(e)}function xS(e,t){let r=e.clientWidth-Pu*2-Ny,n=e.clientHeight-Pu*2-Ny;return r<=0||n<=0?1:Math.min(r/t.w,n/t.h,1)}function yS(e,t,r,n,o){e.style.width=`${r.w*n}px`,e.style.height=`${r.h*n}px`,e.style.borderRadius=o==="mobile"?`${32*n}px`:"10px",t.style.width=`${r.w}px`,t.style.height=`${r.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${n})`}function $y(e,t){let{items:r,initialIndex:n=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(r.length===0)throw new Error("createDemoCarousel: items array must not be empty");hS();let p=Math.max(0,Math.min(n,r.length-1)),u=o,f=s,m=null,y=1,v=!1,E=x("div","persona-dc-root"),T=x("div","persona-dc-toolbar"),A=x("div","persona-dc-toolbar-lead"),M=x("div","persona-dc-toolbar-trail"),b=ir({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>xe(-1)}),w=x("div");w.style.position="relative";let h=x("button","persona-dc-title-btn");h.type="button",h.setAttribute("aria-expanded","false"),h.setAttribute("aria-haspopup","listbox");let k=x("span","persona-dc-title-text"),B=x("span","persona-dc-title-chevron"),H=Pe("chevron-down",12,"currentColor",2);H&&B.appendChild(H),h.append(k,B);let W=x("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let N=!1;function q(){W.innerHTML="";for(let ye=0;ye<r.length;ye++){let pe=r[ye],le=x("button","persona-dc-dropdown-item");le.type="button",le.setAttribute("role","option"),le.setAttribute("aria-current",ye===p?"true":"false");let Ye=x("span");if(Ye.textContent=pe.title,le.appendChild(Ye),pe.description){let Me=x("span","persona-dc-dropdown-desc");Me.textContent=pe.description,le.appendChild(Me)}le.addEventListener("click",()=>{ve(),Ve(ye)}),W.appendChild(le)}}function se(){N=!N,W.style.display=N?"":"none",h.setAttribute("aria-expanded",N?"true":"false"),N&&q()}function ve(){N&&(N=!1,W.style.display="none",h.setAttribute("aria-expanded","false"))}h.addEventListener("click",ye=>{ye.stopPropagation(),se()});let Ue=()=>ve();document.addEventListener("click",Ue),w.append(h,W);let je=ir({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>xe(1)}),we=x("span","persona-dc-counter");A.append(b,w,je,we);let Te=null;i&&(Te=Xa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ye=>{u=ye,j.dataset.device=u,m=null,G()}}),M.appendChild(Te.element));let We=null;if(a){let ye=x("div","persona-dc-zoom-controls"),pe=ir({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Me=m!=null?m:y;m=Math.max(Oy,Me-Dy),G()}});We=x("span","persona-dc-zoom-level"),We.title="Reset to 100%",We.style.cursor="pointer",We.addEventListener("click",()=>{m=1,G()});let le=ir({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Me=m!=null?m:y;m=Math.min(_y,Me+Dy),G()}}),Ye=ir({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,G()}});ye.append(pe,We,le,Ye),M.appendChild(ye)}if(d){let ye=x("div","persona-dc-separator");M.appendChild(ye);let pe=Xa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:le=>{f=le,j.dataset.colorScheme=f,Z()}});M.appendChild(pe.element)}let Oe=x("div","persona-dc-separator");M.appendChild(Oe);let K=ir({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(r[p].url,"_blank")}});M.appendChild(K),T.append(A,M);let He=x("div","persona-dc-stage"),j=x("div","persona-dc-iframe-wrapper");j.dataset.device=u,j.dataset.colorScheme=f;let Ce=x("iframe","persona-dc-iframe");Ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),Ce.setAttribute("loading","lazy"),Ce.title=r[p].title,j.appendChild(Ce),He.appendChild(j),E.append(T,He),e.appendChild(E);function Z(){var ye;try{let pe=(ye=Ce.contentDocument)==null?void 0:ye.body;if(!pe)return;f==="dark"?pe.classList.add("theme-dark"):pe.classList.remove("theme-dark")}catch{}}Ce.addEventListener("load",()=>Z());function he(){let ye=r[p];k.textContent=ye.title,we.textContent=`${p+1} / ${r.length}`,Ce.title=ye.title}function xe(ye){let pe=((p+ye)%r.length+r.length)%r.length;Ve(pe)}function Ve(ye){ye<0||ye>=r.length||(p=ye,Ce.src=r[p].url,he(),l==null||l(p,r[p]))}function G(){var le;if(v)return;let ye=(le=By[u])!=null?le:By.desktop;y=xS(He,ye);let pe=Math.max(Oy,Math.min(_y,m!=null?m:y));yS(j,Ce,ye,pe,u),We&&(We.textContent=`${Math.round(pe*100)}%`)}let ee=new ResizeObserver(()=>G());ee.observe(He),he(),Ce.src=r[p].url,requestAnimationFrame(()=>G());function Ie(){v||(v=!0,ee.disconnect(),document.removeEventListener("click",Ue),E.remove())}return{element:E,goTo:Ve,next:()=>xe(1),prev:()=>xe(-1),getIndex:()=>p,setDevice(ye){u=ye,j.dataset.device=ye,Te==null||Te.setSelected(ye),m=null,G()},setColorScheme(ye){f=ye,j.dataset.colorScheme=ye},setZoom(ye){m=ye,G()},destroy:Ie}}function Fy(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Uy(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function zy(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var n;let r={...t.palette};return(n=e.colors)!=null&&n.primary&&(r.colors={...r.colors,primary:{50:Qn(e.colors.primary,.95),100:Qn(e.colors.primary,.9),200:Qn(e.colors.primary,.8),300:Qn(e.colors.primary,.7),400:Qn(e.colors.primary,.6),500:e.colors.primary,600:Qn(e.colors.primary,.8),700:Qn(e.colors.primary,.7),800:Qn(e.colors.primary,.6),900:Qn(e.colors.primary,.5),950:Qn(e.colors.primary,.45)}}),{...t,palette:r}}}}function qy(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function jy(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Qn(e,t){let r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(r+(255-r)*(1-t)),a=Math.round(n+(255-n)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Vy(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var bS={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Gy={components:{panel:{borderRadius:"0",shadow:"none"}}},Iu={id:"shop",label:"Shopping Assistant",config:{theme:bS,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:yn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Ru={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Gy}},Wu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Gy}},Hu={shop:Iu,minimal:Ru,fullscreen:Wu};function Ky(e){return Hu[e]}var wS=`
173
+ `)}var xy={name:"@runtypelabs/persona",version:"3.26.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var yy=xy.version;function by(){return{name:"@persona/accessibility",version:"1.0.0",transform(t){return{...t,semantic:{...t.semantic,colors:{...t.semantic.colors,interactive:{...t.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function wy(){return{name:"@persona/animations",version:"1.0.0",transform(t){return{...t,palette:{...t.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function vy(t){return{name:"@persona/brand",version:"1.0.0",transform(e){var n;let r={...e.palette};return(n=t.colors)!=null&&n.primary&&(r.colors={...r.colors,primary:{50:Yn(t.colors.primary,.95),100:Yn(t.colors.primary,.9),200:Yn(t.colors.primary,.8),300:Yn(t.colors.primary,.7),400:Yn(t.colors.primary,.6),500:t.colors.primary,600:Yn(t.colors.primary,.8),700:Yn(t.colors.primary,.7),800:Yn(t.colors.primary,.6),900:Yn(t.colors.primary,.5),950:Yn(t.colors.primary,.45)}}),{...e,palette:r}}}}function Cy(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(t){return{...t,palette:{...t.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(t){return{...t,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Ay(){return{name:"@persona/high-contrast",version:"1.0.0",transform(t){return{...t,semantic:{...t.semantic,colors:{...t.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Yn(t,e){let r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16),s=Math.round(r+(255-r)*(1-e)),a=Math.round(n+(255-n)*(1-e)),i=Math.round(o+(255-o)*(1-e));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Sy(t){return{name:t.name,version:t.version,transform:t.transform||(e=>e),cssVariables:t.cssVariables,afterResolve:t.afterResolve}}var OC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Ty={components:{panel:{borderRadius:"0",shadow:"none"}}},vu={id:"shop",label:"Shopping Assistant",config:{theme:OC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:yn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Cu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ty}},Au={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ty}},Su={shop:vu,minimal:Cu,fullscreen:Au};function My(t){return Su[t]}var _C=`
494
174
  @keyframes persona-stream-wipe {
495
175
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
496
176
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -526,7 +206,7 @@ ${a.join(`
526
206
  mask-image: none !important;
527
207
  }
528
208
  }
529
- `.trim(),CS={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:wS};ps(CS);var vS=`
209
+ `.trim(),NC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:_C};ca(NC);var FC=`
530
210
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
531
211
  animation: persona-stream-glyph-cycle-fade
532
212
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -544,7 +224,7 @@ ${a.join(`
544
224
  opacity: 1 !important;
545
225
  }
546
226
  }
547
- `.trim(),si="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",SS=10,AS=120,Bu=120,TS=.4,MS=50,kS=e=>{var n;if(!e)return Bu;let r=((n=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Bu},rb=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=kS(t);return AS*r/Bu},Du=e=>{let t=si[Math.floor(Math.random()*si.length)];return e&&t===e&&(t=si[(si.indexOf(t)+1)%si.length]),t},ES=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let o of Array.from(r)){if(o===e){n=!0;continue}n&&Math.random()<TS&&(o.textContent=Du())}},Jy=new WeakMap,Xy=25,Yy=.5,LS=6,Qy=.25,Zy=new WeakMap,eb=new WeakMap,PS=(e,t)=>{var o;if(!e)return Xy*Yy;let r=Zy.get(e);Zy.set(e,t);let n=(o=eb.get(e))!=null?o:Xy;if(r!==void 0){let s=t-r;s>1&&(n=n*(1-Qy)+s*Qy,eb.set(e,n))}return Math.max(LS,n*Yy)},Ys=new Map,IS=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},RS=e=>{var t;e&&Ys.set(e,((t=Ys.get(e))!=null?t:0)+1)},WS=e=>{var r;if(!e)return;let t=(r=Ys.get(e))!=null?r:0;t<=1?Ys.delete(e):Ys.set(e,t-1)},nb=e=>{var l;if(e.dataset.glyphCycleScheduled==="true")return;let t=(l=e.textContent)!=null?l:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Du();let r=IS(e);r&&(e.dataset.glyphCycleMessageId=r),RS(r);let n=e.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=PS(n,o),a=rb(e),i=SS*a,d=o+i;if(n){let p=Jy.get(n);p!==void 0&&(d=Math.max(d,p)),Jy.set(n,d+s)}HS(e,t,d)},HS=(e,t,r)=>{var a;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let n=rb(e),o=(a=e.textContent)!=null?a:void 0,s=()=>{var d;if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,WS((d=e.dataset.glyphCycleMessageId)!=null?d:null),delete e.dataset.glyphCycleMessageId;return}let i=Du(o);e.textContent=i,o=i,ES(e),setTimeout(s,n)};setTimeout(s,n)},tb=e=>{var r;let t=(r=e.querySelectorAll)==null?void 0:r.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))nb(n)},BS=e=>e.nodeType===1,DS={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:vS,bufferContent(e){if(e.length<MS)return"";let t=0,r=-1,n=0;for(;n<e.length;){if(e[n]==="*"&&e[n+1]==="*"){t+=1,n+=2;continue}/\s/.test(e[n])&&t%2===0&&(r=n),n+=1}return r<0?"":e.slice(0,r)},isAnimating(e){var t;return((t=Ys.get(e.id))!=null?t:0)>0},onAttach(e){tb(e);let t=new MutationObserver(r=>{for(let n of r)for(let o of Array.from(n.addedNodes))BS(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?nb(o):tb(o))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ps(DS);return cb(OS);})();
227
+ `.trim(),ti="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",$C=10,UC=120,Tu=120,zC=.4,qC=50,VC=t=>{var n;if(!t)return Tu;let r=((n=t.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Tu},By=t=>{let e=t.closest(".persona-stream-glyph-cycle"),r=VC(e);return UC*r/Tu},Mu=t=>{let e=ti[Math.floor(Math.random()*ti.length)];return t&&e===t&&(e=ti[(ti.indexOf(e)+1)%ti.length]),e},jC=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let r=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let o of Array.from(r)){if(o===t){n=!0;continue}n&&Math.random()<zC&&(o.textContent=Mu())}},ky=new WeakMap,Ey=25,Ly=.5,GC=6,Py=.25,Iy=new WeakMap,Ry=new WeakMap,KC=(t,e)=>{var o;if(!t)return Ey*Ly;let r=Iy.get(t);Iy.set(t,e);let n=(o=Ry.get(t))!=null?o:Ey;if(r!==void 0){let s=e-r;s>1&&(n=n*(1-Py)+s*Py,Ry.set(t,n))}return Math.max(GC,n*Ly)},Ka=new Map,XC=t=>{var r;let e=t.closest("[data-message-id]");return(r=e==null?void 0:e.dataset.messageId)!=null?r:null},JC=t=>{var e;t&&Ka.set(t,((e=Ka.get(t))!=null?e:0)+1)},QC=t=>{var r;if(!t)return;let e=(r=Ka.get(t))!=null?r:0;e<=1?Ka.delete(t):Ka.set(t,e-1)},Hy=t=>{var l;if(t.dataset.glyphCycleScheduled==="true")return;let e=(l=t.textContent)!=null?l:"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=Mu();let r=XC(t);r&&(t.dataset.glyphCycleMessageId=r),JC(r);let n=t.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=KC(n,o),a=By(t),i=$C*a,d=o+i;if(n){let p=ky.get(n);p!==void 0&&(d=Math.max(d,p)),ky.set(n,d+s)}YC(t,e,d)},YC=(t,e,r)=>{var a;if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let n=By(t),o=(a=t.textContent)!=null?a:void 0,s=()=>{var d;if(!t.isConnected)return;if(Date.now()>=r){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,QC((d=t.dataset.glyphCycleMessageId)!=null?d:null),delete t.dataset.glyphCycleMessageId;return}let i=Mu(o);t.textContent=i,o=i,jC(t),setTimeout(s,n)};setTimeout(s,n)},Wy=t=>{var r;let e=(r=t.querySelectorAll)==null?void 0:r.call(t,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))Hy(n)},ZC=t=>t.nodeType===1,eA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:FC,bufferContent(t){if(t.length<qC)return"";let e=0,r=-1,n=0;for(;n<t.length;){if(t[n]==="*"&&t[n+1]==="*"){e+=1,n+=2;continue}/\s/.test(t[n])&&e%2===0&&(r=n),n+=1}return r<0?"":t.slice(0,r)},isAnimating(t){var e;return((e=Ka.get(t.id))!=null?e:0)>0},onAttach(t){Wy(t);let e=new MutationObserver(r=>{for(let n of r)for(let o of Array.from(n.addedNodes))ZC(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?Hy(o):Wy(o))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ca(eA);return Uy(tA);})();
548
228
  /*! Bundled license information:
549
229
 
550
230
  dompurify/dist/purify.es.mjs: