@runtypelabs/persona 3.22.0 → 3.23.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.
- package/dist/animations/glyph-cycle.cjs +2 -262
- package/dist/animations/glyph-cycle.js +2 -235
- package/dist/animations/wipe.cjs +2 -72
- package/dist/animations/wipe.js +2 -45
- package/dist/index.cjs +50 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +83 -83
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +49 -49
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.cjs +22 -1874
- package/dist/smart-dom-reader.js +22 -1847
- package/dist/testing.cjs +3 -84
- package/dist/testing.js +3 -55
- package/dist/theme-editor.cjs +54 -24695
- package/dist/theme-editor.js +54 -24682
- package/package.json +9 -6
- package/src/components/event-stream-view.ts +122 -1
- package/src/ui.ts +24 -3
- package/src/utils/throughput-tracker.test.ts +366 -0
- package/src/utils/throughput-tracker.ts +427 -0
package/dist/index.global.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var Gy=Object.create;var gs=Object.defineProperty;var Ky=Object.getOwnPropertyDescriptor;var Jy=Object.getOwnPropertyNames;var Xy=Object.getPrototypeOf,Yy=Object.prototype.hasOwnProperty;var Lg=e=>{throw TypeError(e)};var Qy=(e,t,r)=>t in e?gs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Vn=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ig=(e,t)=>{for(var r in t)gs(e,r,{get:t[r],enumerable:!0})},Rg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jy(t))!Yy.call(e,o)&&o!==r&&gs(e,o,{get:()=>t[o],enumerable:!(n=Ky(t,o))||n.enumerable});return e};var ld=(e,t,r)=>(r=e!=null?Gy(Xy(e)):{},Rg(t||!e||!e.__esModule?gs(r,"default",{value:e,enumerable:!0}):r,e)),Zy=e=>Rg(gs({},"__esModule",{value:!0}),e);var Bt=(e,t,r)=>Qy(e,typeof t!="symbol"?t+"":t,r),eb=(e,t,r)=>t.has(e)||Lg("Cannot "+r);var Wg=(e,t,r)=>t.has(e)?Lg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);var Ai=(e,t,r)=>(eb(e,t,"access private method"),r);function Ea(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(!Ea(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 s of n)if(!Ea(e[s],t[s]))return!1;return!0}return e===t}var kd=Vn(()=>{"use strict"});function hn(e){return encodeURI(s0(e))}function s0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Ri=Vn(()=>{"use strict"});function co(e,t=Object.create(null),r=c0,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let a=e.$id||e.id;if(a){let s=new URL(a,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:co(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 a=new URL(e.$ref,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:a.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let a=new URL(e.$recursiveRef,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(e.$anchor){let a=new URL("#"+e.$anchor,r.href);t[a.href]=e}for(let a in e){if(d0[a])continue;let s=`${n}/${hn(a)}`,i=e[a];if(Array.isArray(i)){if(i0[a]){let d=i.length;for(let l=0;l<d;l++)co(i[l],t,r,`${s}/${l}`)}}else if(l0[a])for(let d in i)co(i[d],t,r,`${s}/${hn(d)}`);else co(i,t,r,s)}return t}var i0,l0,d0,c0,Wi=Vn(()=>{"use strict";Ri();i0={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},l0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},d0={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 Kn(e){return e.test.bind(e)}function M0(e){return e%4===0&&(e%100!==0||e%400===0)}function mh(e){let t=e.match(p0);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&M0(r)?29:u0[n])}function gh(e,t){let r=t.match(f0);if(!r)return!1;let n=+r[1],o=+r[2],a=+r[3],s=!!r[5];return(n<=23&&o<=59&&a<=59||n==23&&o==59&&a==60)&&(!e||s)}function E0(e){let t=e.split(k0);return t.length==2&&mh(t[0])&&gh(!0,t[1])}function I0(e){return L0.test(e)&&P0.test(e)}function W0(e){if(R0.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var p0,u0,f0,m0,g0,h0,x0,y0,b0,w0,C0,v0,A0,S0,T0,Ed,k0,L0,P0,R0,Ld=Vn(()=>{"use strict";p0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,u0=[0,31,28,31,30,31,30,31,31,30,31,30,31],f0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,m0=/^(?=.{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,g0=/^(?:[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,h0=/^(?:(?:[^\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,x0=/^(?:(?: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,y0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,b0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,w0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,C0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,v0=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))},A0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,S0=/^((([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,T0=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));Ed={date:mh,time:gh.bind(void 0,!1),"date-time":E0,duration:T0,uri:I0,"uri-reference":Kn(g0),"uri-template":Kn(h0),url:Kn(x0),email:v0,hostname:Kn(m0),ipv4:Kn(A0),ipv6:Kn(S0),regex:W0,uuid:Kn(y0),"json-pointer":Kn(b0),"json-pointer-uri-fragment":Kn(w0),"relative-json-pointer":Kn(C0)};k0=/t|\s/i;L0=/\/|:/,P0=/^(?:[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;R0=/[^\\]\\Z/});var hh,xh=Vn(()=>{"use strict";(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(hh||(hh={}))});function yh(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 Pd=Vn(()=>{"use strict"});function lr(e,t,r="2019-09",n=co(t),o=!0,a=null,s="#",i="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,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:m,$recursiveAnchor:f,type:x,const:C,enum:M,required:T,not:A,anyOf:k,allOf:v,oneOf:w,if:h,then:E,else:W,format:R,properties:I,patternProperties:H,additionalProperties:G,unevaluatedProperties:ie,minProperties:ye,maxProperties:Oe,propertyNames:et,dependentRequired:be,dependentSchemas:xe,dependencies:Ie,prefixItems:Je,items:X,additionalItems:Te,unevaluatedItems:K,contains:ge,minContains:ce,maxContains:fe,minItems:He,maxItems:rt,uniqueItems:Q,minimum:de,maximum:_e,exclusiveMinimum:Y,exclusiveMaximum:V,multipleOf:Ce,minLength:Be,maxLength:oe,pattern:Ee,__absolute_ref__:we,__absolute_recursive_ref__:Dt}=t,U=[];if(f===!0&&a===null&&(a=t),m==="#"){let ze=a===null?n[Dt]:a,he=`${i}/$recursiveRef`,Re=lr(e,a===null?t:a,r,n,o,ze,s,he,d);Re.valid||U.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:he,error:"A subschema had errors."},...Re.errors)}if(u!==void 0){let he=n[we||u];if(he===void 0){let ue=`Unresolved $ref "${u}".`;throw we&&we!==u&&(ue+=` Absolute URI "${we}".`),ue+=`
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var rb=Object.create;var ya=Object.defineProperty;var nb=Object.getOwnPropertyDescriptor;var ob=Object.getOwnPropertyNames;var sb=Object.getPrototypeOf,ab=Object.prototype.hasOwnProperty;var Bg=e=>{throw TypeError(e)};var ib=(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 ob(t))!ab.call(e,o)&&o!==r&&ya(e,o,{get:()=>t[o],enumerable:!(n=nb(t,o))||n.enumerable});return e};var ud=(e,t,r)=>(r=e!=null?rb(sb(e)):{},_g(t||!e||!e.__esModule?ya(r,"default",{value:e,enumerable:!0}):r,e)),lb=e=>_g(ya({},"__esModule",{value:!0}),e);var Dt=(e,t,r)=>ib(e,typeof t!="symbol"?t+"":t,r),db=(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)=>(db(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(g0(e))}function g0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Bi=Gn(()=>{"use strict"});function uo(e,t=Object.create(null),r=b0,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(y0[s])continue;let a=`${n}/${xn(s)}`,i=e[s];if(Array.isArray(i)){if(h0[s]){let d=i.length;for(let l=0;l<d;l++)uo(i[l],t,r,`${a}/${l}`)}}else if(x0[s])for(let d in i)uo(i[d],t,r,`${a}/${xn(d)}`);else uo(i,t,r,a)}return t}var h0,x0,y0,b0,Di=Gn(()=>{"use strict";Bi();h0={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},x0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},y0={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},b0=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 B0(e){return e%4===0&&(e%100!==0||e%400===0)}function wh(e){let t=e.match(w0);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&B0(r)?29:C0[n])}function Ch(e,t){let r=t.match(v0);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 O0(e){let t=e.split(D0);return t.length==2&&wh(t[0])&&Ch(!0,t[1])}function $0(e){return _0.test(e)&&N0.test(e)}function U0(e){if(F0.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var w0,C0,v0,A0,S0,T0,M0,k0,E0,L0,P0,I0,R0,W0,H0,Rd,D0,_0,N0,F0,Wd=Gn(()=>{"use strict";w0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,C0=[0,31,28,31,30,31,30,31,31,30,31,30,31],v0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,A0=/^(?=.{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,S0=/^(?:[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,T0=/^(?:(?:[^\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,M0=/^(?:(?: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,k0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,E0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,L0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,P0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,I0=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))},R0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,W0=/^((([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,H0=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":O0,duration:H0,uri:$0,"uri-reference":Jn(S0),"uri-template":Jn(T0),url:Jn(M0),email:I0,hostname:Jn(A0),ipv4:Jn(R0),ipv6:Jn(W0),regex:U0,uuid:Jn(k0),"json-pointer":Jn(E0),"json-pointer-uri-fragment":Jn(L0),"relative-json-pointer":Jn(P0)};D0=/t|\s/i;_0=/\/|:/,N0=/^(?:[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;F0=/[^\\]\\Z/});var vh,Ah=Gn(()=>{"use strict";(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(vh||(vh={}))});function Sh(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:m,$recursiveAnchor:f,type:y,const:C,enum:k,required:T,not:S,anyOf:M,allOf:v,oneOf:b,if:x,then:E,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(f===!0&&s===null&&(s=t),m==="#"){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+=`
|
|
2
2
|
Known schemas:
|
|
3
3
|
- ${Object.keys(n).join(`
|
|
4
|
-
- `)}`,new Error(ue)}let Re=`${i}/$ref`,ve=lr(e,he,r,n,o,a,s,Re,d);if(ve.valid||U.push({instanceLocation:s,keyword:"$ref",keywordLocation:Re,error:"A subschema had errors."},...ve.errors),r==="4"||r==="7")return{valid:U.length===0,errors:U}}if(Array.isArray(x)){let ze=x.length,he=!1;for(let Re=0;Re<ze;Re++)if(p===x[Re]||x[Re]==="integer"&&p==="number"&&e%1===0&&e===e){he=!0;break}he||U.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x.join('", "')}".`})}else x==="integer"?(p!=="number"||e%1||e!==e)&&U.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x}".`}):x!==void 0&&p!==x&&U.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x}".`});if(C!==void 0&&(p==="object"||p==="array"?Ea(e,C)||U.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`}):e!==C&&U.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`})),M!==void 0&&(p==="object"||p==="array"?M.some(ze=>Ea(e,ze))||U.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(M)}.`}):M.some(ze=>e===ze)||U.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(M)}.`})),A!==void 0){let ze=`${i}/not`;lr(e,A,r,n,o,a,s,ze).valid&&U.push({instanceLocation:s,keyword:"not",keywordLocation:ze,error:'Instance matched "not" schema.'})}let ae=[];if(k!==void 0){let ze=`${i}/anyOf`,he=U.length,Re=!1;for(let ve=0;ve<k.length;ve++){let ue=k[ve],Z=Object.create(d),O=lr(e,ue,r,n,o,f===!0?a:null,s,`${ze}/${ve}`,Z);U.push(...O.errors),Re=Re||O.valid,O.valid&&ae.push(Z)}Re?U.length=he:U.splice(he,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:ze,error:"Instance does not match any subschemas."})}if(v!==void 0){let ze=`${i}/allOf`,he=U.length,Re=!0;for(let ve=0;ve<v.length;ve++){let ue=v[ve],Z=Object.create(d),O=lr(e,ue,r,n,o,f===!0?a:null,s,`${ze}/${ve}`,Z);U.push(...O.errors),Re=Re&&O.valid,O.valid&&ae.push(Z)}Re?U.length=he:U.splice(he,0,{instanceLocation:s,keyword:"allOf",keywordLocation:ze,error:"Instance does not match every subschema."})}if(w!==void 0){let ze=`${i}/oneOf`,he=U.length,Re=w.filter((ve,ue)=>{let Z=Object.create(d),O=lr(e,ve,r,n,o,f===!0?a:null,s,`${ze}/${ue}`,Z);return U.push(...O.errors),O.valid&&ae.push(Z),O.valid}).length;Re===1?U.length=he:U.splice(he,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:ze,error:`Instance does not match exactly one subschema (${Re} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...ae),h!==void 0){let ze=`${i}/if`;if(lr(e,h,r,n,o,a,s,ze,d).valid){if(E!==void 0){let Re=lr(e,E,r,n,o,a,s,`${i}/then`,d);Re.valid||U.push({instanceLocation:s,keyword:"if",keywordLocation:ze,error:'Instance does not match "then" schema.'},...Re.errors)}}else if(W!==void 0){let Re=lr(e,W,r,n,o,a,s,`${i}/else`,d);Re.valid||U.push({instanceLocation:s,keyword:"if",keywordLocation:ze,error:'Instance does not match "else" schema.'},...Re.errors)}}if(p==="object"){if(T!==void 0)for(let ve of T)ve in e||U.push({instanceLocation:s,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${ve}".`});let ze=Object.keys(e);if(ye!==void 0&&ze.length<ye&&U.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${ye} properties.`}),Oe!==void 0&&ze.length>Oe&&U.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Oe} properties.`}),et!==void 0){let ve=`${i}/propertyNames`;for(let ue in e){let Z=`${s}/${hn(ue)}`,O=lr(ue,et,r,n,o,a,Z,ve);O.valid||U.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:ve,error:`Property name "${ue}" does not match schema.`},...O.errors)}}if(be!==void 0){let ve=`${i}/dependantRequired`;for(let ue in be)if(ue in e){let Z=be[ue];for(let O of Z)O in e||U.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:ve,error:`Instance has "${ue}" but does not have "${O}".`})}}if(xe!==void 0)for(let ve in xe){let ue=`${i}/dependentSchemas`;if(ve in e){let Z=lr(e,xe[ve],r,n,o,a,s,`${ue}/${hn(ve)}`,d);Z.valid||U.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:ue,error:`Instance has "${ve}" but does not match dependant schema.`},...Z.errors)}}if(Ie!==void 0){let ve=`${i}/dependencies`;for(let ue in Ie)if(ue in e){let Z=Ie[ue];if(Array.isArray(Z))for(let O of Z)O in e||U.push({instanceLocation:s,keyword:"dependencies",keywordLocation:ve,error:`Instance has "${ue}" but does not have "${O}".`});else{let O=lr(e,Z,r,n,o,a,s,`${ve}/${hn(ue)}`);O.valid||U.push({instanceLocation:s,keyword:"dependencies",keywordLocation:ve,error:`Instance has "${ue}" but does not match dependant schema.`},...O.errors)}}}let he=Object.create(null),Re=!1;if(I!==void 0){let ve=`${i}/properties`;for(let ue in I){if(!(ue in e))continue;let Z=`${s}/${hn(ue)}`,O=lr(e[ue],I[ue],r,n,o,a,Z,`${ve}/${hn(ue)}`);if(O.valid)d[ue]=he[ue]=!0;else if(Re=o,U.push({instanceLocation:s,keyword:"properties",keywordLocation:ve,error:`Property "${ue}" does not match schema.`},...O.errors),Re)break}}if(!Re&&H!==void 0){let ve=`${i}/patternProperties`;for(let ue in H){let Z=new RegExp(ue,"u"),O=H[ue];for(let me in e){if(!Z.test(me))continue;let qe=`${s}/${hn(me)}`,$e=lr(e[me],O,r,n,o,a,qe,`${ve}/${hn(ue)}`);$e.valid?d[me]=he[me]=!0:(Re=o,U.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:ve,error:`Property "${me}" matches pattern "${ue}" but does not match associated schema.`},...$e.errors))}}}if(!Re&&G!==void 0){let ve=`${i}/additionalProperties`;for(let ue in e){if(he[ue])continue;let Z=`${s}/${hn(ue)}`,O=lr(e[ue],G,r,n,o,a,Z,ve);O.valid?d[ue]=!0:(Re=o,U.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:ve,error:`Property "${ue}" does not match additional properties schema.`},...O.errors))}}else if(!Re&&ie!==void 0){let ve=`${i}/unevaluatedProperties`;for(let ue in e)if(!d[ue]){let Z=`${s}/${hn(ue)}`,O=lr(e[ue],ie,r,n,o,a,Z,ve);O.valid?d[ue]=!0:U.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:ve,error:`Property "${ue}" does not match unevaluated properties schema.`},...O.errors)}}}else if(p==="array"){rt!==void 0&&e.length>rt&&U.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${rt}).`}),He!==void 0&&e.length<He&&U.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${He}).`});let ze=e.length,he=0,Re=!1;if(Je!==void 0){let ve=`${i}/prefixItems`,ue=Math.min(Je.length,ze);for(;he<ue;he++){let Z=lr(e[he],Je[he],r,n,o,a,`${s}/${he}`,`${ve}/${he}`);if(d[he]=!0,!Z.valid&&(Re=o,U.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:ve,error:"Items did not match schema."},...Z.errors),Re))break}}if(X!==void 0){let ve=`${i}/items`;if(Array.isArray(X)){let ue=Math.min(X.length,ze);for(;he<ue;he++){let Z=lr(e[he],X[he],r,n,o,a,`${s}/${he}`,`${ve}/${he}`);if(d[he]=!0,!Z.valid&&(Re=o,U.push({instanceLocation:s,keyword:"items",keywordLocation:ve,error:"Items did not match schema."},...Z.errors),Re))break}}else for(;he<ze;he++){let ue=lr(e[he],X,r,n,o,a,`${s}/${he}`,ve);if(d[he]=!0,!ue.valid&&(Re=o,U.push({instanceLocation:s,keyword:"items",keywordLocation:ve,error:"Items did not match schema."},...ue.errors),Re))break}if(!Re&&Te!==void 0){let ue=`${i}/additionalItems`;for(;he<ze;he++){let Z=lr(e[he],Te,r,n,o,a,`${s}/${he}`,ue);d[he]=!0,Z.valid||(Re=o,U.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:ue,error:"Items did not match additional items schema."},...Z.errors))}}}if(ge!==void 0)if(ze===0&&ce===void 0)U.push({instanceLocation:s,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ce!==void 0&&ze<ce)U.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${ze}) than minContains (${ce}).`});else{let ve=`${i}/contains`,ue=U.length,Z=0;for(let O=0;O<ze;O++){let me=lr(e[O],ge,r,n,o,a,`${s}/${O}`,ve);me.valid?(d[O]=!0,Z++):U.push(...me.errors)}Z>=(ce||0)&&(U.length=ue),ce===void 0&&fe===void 0&&Z===0?U.splice(ue,0,{instanceLocation:s,keyword:"contains",keywordLocation:ve,error:"Array does not contain item matching schema."}):ce!==void 0&&Z<ce?U.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${ce} items matching schema. Only ${Z} items were found.`}):fe!==void 0&&Z>fe&&U.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${fe} items matching schema. ${Z} items were found.`})}if(!Re&&K!==void 0){let ve=`${i}/unevaluatedItems`;for(he;he<ze;he++){if(d[he])continue;let ue=lr(e[he],K,r,n,o,a,`${s}/${he}`,ve);d[he]=!0,ue.valid||U.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:ve,error:"Items did not match unevaluated items schema."},...ue.errors)}}if(Q)for(let ve=0;ve<ze;ve++){let ue=e[ve],Z=typeof ue=="object"&&ue!==null;for(let O=0;O<ze;O++){if(ve===O)continue;let me=e[O];(ue===me||Z&&(typeof me=="object"&&me!==null)&&Ea(ue,me))&&(U.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${ve} and ${O}.`}),ve=Number.MAX_SAFE_INTEGER,O=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(de!==void 0&&(Y===!0&&e<=de||e<de)&&U.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${Y?"or equal to ":""} ${de}.`}),_e!==void 0&&(V===!0&&e>=_e||e>_e)&&U.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${V?"or equal to ":""} ${_e}.`})):(de!==void 0&&e<de&&U.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${de}.`}),_e!==void 0&&e>_e&&U.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${_e}.`}),Y!==void 0&&e<=Y&&U.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${Y}.`}),V!==void 0&&e>=V&&U.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${V}.`})),Ce!==void 0){let ze=e%Ce;Math.abs(0-ze)>=11920929e-14&&Math.abs(Ce-ze)>=11920929e-14&&U.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${Ce}.`})}}else if(p==="string"){let ze=Be===void 0&&oe===void 0?0:yh(e);Be!==void 0&&ze<Be&&U.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${ze} < ${Be}).`}),oe!==void 0&&ze>oe&&U.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${ze} > ${oe}).`}),Ee!==void 0&&!new RegExp(Ee,"u").test(e)&&U.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),R!==void 0&&Ed[R]&&!Ed[R](e)&&U.push({instanceLocation:s,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${R}".`})}return{valid:U.length===0,errors:U}}var Id=Vn(()=>{"use strict";kd();Wi();Ld();Ri();Pd()});var Hi,bh=Vn(()=>{"use strict";Wi();Id();Hi=class{constructor(t,r="2019-09",n=!0){Bt(this,"schema");Bt(this,"draft");Bt(this,"shortCircuit");Bt(this,"lookup");this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=co(t)}validate(t){return lr(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),co(t,this.lookup)}}});var wh=Vn(()=>{"use strict";kd();Wi();Ld();Ri();xh();Pd();Id();bh()});var Ih={};Ig(Ih,{cleanupWebMCPPolyfill:()=>Ph,initializeWebMCPPolyfill:()=>Lh,initializeWebModelContextPolyfill:()=>Lh,isPlainObject:()=>Rr,validateArgsWithSchema:()=>Mh});function Jn(e){try{return new DOMException(e,"UnknownError")}catch{let t=new Error(e);return t.name="UnknownError",t}}function _0(e){let t;try{t=JSON.parse(e)}catch{throw Jn(Ch)}if(!t||typeof t!="object"||Array.isArray(t))throw Jn(Ch);return t}function N0(e){if(typeof e=="string")return e;if(Rr(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 Rr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Sh(e){if(!Rr(e))return null;let t=e["~standard"];return Rr(t)?t:null}function $0(e){let t=Sh(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function F0(e){let t=Sh(e);return!t||t.version!==1||!Rr(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Di(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!Rr(t))return{issues:[{message:"expected object arguments"}]};let r=Mh(t,e);return r?{issues:[r]}:{value:t}}}}}function U0(e){for(let t of H0)try{let r=e["~standard"].jsonSchema.input({target:t});return Th(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 z0(e){if(e===void 0){let r=Bi;return{inputSchema:r,standardValidator:Di(r)}}if(F0(e)){let r=U0(e);return{inputSchema:r,standardValidator:Di(r)}}if($0(e))return{inputSchema:Bi,standardValidator:e};if(Th(e),Object.keys(e).length===0)return{inputSchema:Bi,standardValidator:Di(Bi)};let t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:Di(t)}}function Th(e){if(!Rr(e))throw new Error("inputSchema must be a JSON Schema object");La(e,"$")}function La(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(!Rr(o))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Rr(d))throw new Error(`Invalid JSON Schema at ${t}.properties.${i}: expected object schema`);La(d,`${t}.properties.${i}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[i,d]of a.entries()){if(!Rr(d))throw new Error(`Invalid JSON Schema at ${t}.items[${i}]: expected object schema`);La(d,`${t}.items[${i}]`)}else if(Rr(a))La(a,`${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(!Rr(p))throw new Error(`Invalid JSON Schema at ${t}.${i}[${l}]: expected object schema`);La(p,`${t}.${i}[${l}]`)}}}let s=e.not;if(s!==void 0){if(!Rr(s))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);La(s,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function q0(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=z0(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,[Ah]:r.standardValidator}}function Mh(e,t){let r=new Hi(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 j0(e){if(!e||e.length===0)return null;let t=e.map(r=>Rr(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 V0(e,t){let r;try{r=await Promise.resolve(t["~standard"].validate(e))}catch(a){let s=a instanceof Error?`: ${a.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",a),`Input validation error: schema validation failed${s}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let o=j0(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function G0(e,t){return V0(e,t[Ah])}function K0(e){return Rr(e)&&Array.isArray(e.content)}function J0(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Wd(e){return J0(e)?Number.isFinite(e)||typeof e!="number":Array.isArray(e)?e.every(t=>Wd(t)):Rr(e)?Object.values(e).every(t=>Wd(t)):!1}function X0(e){if(!(!Rr(e)||!Wd(e)))return e}function Y0(e){var t;if(typeof e=="string")return e;try{return(t=JSON.stringify(e))!=null?t:String(e)}catch{return String(e)}}function Q0(e){if(K0(e))return e;let t=X0(e);return{content:[{type:"text",text:Y0(e)}],...t?{structuredContent:t}:{},isError:!1}}function Z0(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 ew(e){var r;if(e.isError)throw Jn(((r=Z0(e))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||Oi);let t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw Jn(Oi)}}function tw(e,t){return t?t.aborted?Promise.reject(Jn(Rd)):new Promise((r,n)=>{let o=()=>{a(),n(Jn(Rd))},a=()=>{t.removeEventListener("abort",o)};t.addEventListener("abort",o,{once:!0}),e.then(s=>{a(),r(s)},s=>{a(),n(s)})}):e}function kh(){return typeof navigator!="undefined"?navigator:null}function Eh(){return typeof document!="undefined"?document:null}function rw(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:r})}function vh(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}function nw(e,t){Object.defineProperty(e,"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.")),t}})}function Lh(e){var d;let t=kh(),r=Eh();if(!t&&!r||(r==null?void 0:r.modelContext))return;let o=t==null?void 0:t.modelContext,a=!!o;if(or.installed&&Ph(),r&&o){or.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),vh(r,o),or.installedDocumentModelContext=!0,or.installed=!0;return}if(a)return;let s=new D0,i=s;if(i[B0]=!0,r&&(or.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),vh(r,i),or.installedDocumentModelContext=!0),t){or.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),or.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),_i=!1,nw(t,i),or.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)&&(rw(t,"modelContextTesting",s.getTestingShim()),or.installedNavigatorModelContextTesting=!0)}or.installed=!0}function Ph(){if(!or.installed)return;let e=(n,o,a)=>{if(a){Object.defineProperty(n,o,a);return}delete n[o]},t=kh(),r=Eh();r&&or.installedDocumentModelContext&&e(r,"modelContext",or.previousDocumentModelContextDescriptor),t&&or.installedNavigatorModelContext&&e(t,"modelContext",or.previousNavigatorModelContextDescriptor),t&&or.installedNavigatorModelContextTesting&&e(t,"modelContextTesting",or.previousNavigatorModelContextTestingDescriptor),or.installed=!1,or.previousDocumentModelContextDescriptor=void 0,or.previousNavigatorModelContextDescriptor=void 0,or.previousNavigatorModelContextTestingDescriptor=void 0,or.installedDocumentModelContext=!1,or.installedNavigatorModelContext=!1,or.installedNavigatorModelContextTesting=!1,_i=!1}var Ch,Oi,Rd,Bi,H0,B0,Ah,or,D0,O0,_i,Rh=Vn(()=>{"use strict";wh();Ch="Failed to parse input arguments",Oi="Tool was executed but the invocation failed. For example, the script function threw an error",Rd="Tool was cancelled",Bi={type:"object",properties:{}},H0=["draft-2020-12","draft-07"],B0="__isWebMCPPolyfill",Ah=Symbol("standardValidator"),or={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},D0=class extends EventTarget{constructor(){super(...arguments);Bt(this,"tools",new Map);Bt(this,"testingShim",null);Bt(this,"_ontoolchange",null);Bt(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerTool(t,r){var a;let n=r==null?void 0:r.signal;if(n!=null&&n.aborted){console.warn(`[WebMCPPolyfill] registerTool("${(a=t==null?void 0:t.name)!=null?a:"<unknown>"}") skipped: options.signal was already aborted.`);return}let o=q0(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=N0(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 O0(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,a;let r=this.tools.get(t.name);return{...t,title:(n=r==null?void 0:r.title)!=null?n:"",origin:(a=(o=globalThis.location)==null?void 0:o.origin)!=null?a:"",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 Jn(Rd);let a=this.tools.get(t);if(!a)throw Jn(`Tool not found: ${t}`);let s=_0(r),i=await G0(s,a);if(i)throw Jn(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=a.execute(s,l),m=await tw(Promise.resolve(u),n==null?void 0:n.signal);if(o)return ew(Q0(m));let f=JSON.stringify(m);return f===void 0?null:f}catch(u){throw Jn(u instanceof Error?`${Oi}: ${u.message}`:Oi)}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."))}},O0=class extends EventTarget{constructor(t){super();Bt(this,"context");Bt(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"))}};_i=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let e=window.__webMCPPolyfillOptions;if((e==null?void 0:e.autoInitialize)!==!1)try{Lh(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}});var Bd=Pg(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.Allow=Qe.ALL=Qe.COLLECTION=Qe.ATOM=Qe.SPECIAL=Qe.INF=Qe._INFINITY=Qe.INFINITY=Qe.NAN=Qe.BOOL=Qe.NULL=Qe.OBJ=Qe.ARR=Qe.NUM=Qe.STR=void 0;Qe.STR=1;Qe.NUM=2;Qe.ARR=4;Qe.OBJ=8;Qe.NULL=16;Qe.BOOL=32;Qe.NAN=64;Qe.INFINITY=128;Qe._INFINITY=256;Qe.INF=Qe.INFINITY|Qe._INFINITY;Qe.SPECIAL=Qe.NULL|Qe.BOOL|Qe.INF|Qe.NAN;Qe.ATOM=Qe.STR|Qe.NUM|Qe.SPECIAL;Qe.COLLECTION=Qe.ARR|Qe.OBJ;Qe.ALL=Qe.ATOM|Qe.COLLECTION;Qe.Allow={STR:Qe.STR,NUM:Qe.NUM,ARR:Qe.ARR,OBJ:Qe.OBJ,NULL:Qe.NULL,BOOL:Qe.BOOL,NAN:Qe.NAN,INFINITY:Qe.INFINITY,_INFINITY:Qe._INFINITY,INF:Qe.INF,SPECIAL:Qe.SPECIAL,ATOM:Qe.ATOM,COLLECTION:Qe.COLLECTION,ALL:Qe.ALL};Qe.default=Qe.Allow});var Ui=Pg(Wr=>{"use strict";var pw=Wr&&Wr.__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]})),uw=Wr&&Wr.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&pw(t,e,r)};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Allow=Wr.MalformedJSON=Wr.PartialJSON=Wr.parseJSON=Wr.parse=void 0;var Yr=Bd();Object.defineProperty(Wr,"Allow",{enumerable:!0,get:function(){return Yr.Allow}});uw(Bd(),Wr);var $i=class extends Error{};Wr.PartialJSON=$i;var Fi=class extends Error{};Wr.MalformedJSON=Fi;function Wh(e,t=Yr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return fw(e.trim(),t)}Wr.parseJSON=Wh;var fw=(e,t)=>{let r=e.length,n=0,o=m=>{throw new $i(`${m} at position ${n}`)},a=m=>{throw new Fi(`${m} at position ${n}`)},s=()=>(u(),n>=r&&o("Unexpected end of input"),e[n]==='"'?i():e[n]==="{"?d():e[n]==="["?l():e.substring(n,n+4)==="null"||Yr.Allow.NULL&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||Yr.Allow.BOOL&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||Yr.Allow.BOOL&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||Yr.Allow.INFINITY&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||Yr.Allow._INFINITY&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||Yr.Allow.NAN&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),i=()=>{let m=n,f=!1;for(n++;n<r&&(e[n]!=='"'||f&&e[n-1]==="\\");)f=e[n]==="\\"?!f:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(m,++n-Number(f)))}catch(x){a(String(x))}else if(Yr.Allow.STR&t)try{return JSON.parse(e.substring(m,n-Number(f))+'"')}catch{return JSON.parse(e.substring(m,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,u();let m={};try{for(;e[n]!=="}";){if(u(),n>=r&&Yr.Allow.OBJ&t)return m;let f=i();u(),n++;try{let x=s();m[f]=x}catch(x){if(Yr.Allow.OBJ&t)return m;throw x}u(),e[n]===","&&n++}}catch{if(Yr.Allow.OBJ&t)return m;o("Expected '}' at end of object")}return n++,m},l=()=>{n++;let m=[];try{for(;e[n]!=="]";)m.push(s()),u(),e[n]===","&&n++}catch{if(Yr.Allow.ARR&t)return m;o("Expected ']' at end of array")}return n++,m},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Yr.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(f))}}let m=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==r&&!(Yr.Allow.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(m,n))}catch{e.substring(m,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(e.substring(m,e.lastIndexOf("e")))}catch(x){a(String(x))}}},u=()=>{for(;n<r&&`
|
|
5
|
-
\r `.includes(e[n]);)n++};return
|
|
6
|
-
`).map(o=>{let
|
|
7
|
-
`)}var
|
|
8
|
-
`)}}}fences(t){let r=this.rules.block.fences.exec(t);if(r){let n=r[0],o=
|
|
9
|
-
$1`);n=
|
|
10
|
-
`);let o=this.lexer.state.top;this.lexer.state.top=!0;let
|
|
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(C!==void 0&&(p==="object"||p==="array"?Is(e,C)||ne.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`}):e!==C&&ne.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`})),k!==void 0&&(p==="object"||p==="array"?k.some(Q=>Is(e,Q))||ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(k)}.`}):k.some(Q=>e===Q)||ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(k)}.`})),S!==void 0){let Q=`${i}/not`;fr(e,S,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,f===!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(v!==void 0){let Q=`${i}/allOf`,Be=ne.length,ke=!0;for(let ge=0;ge<v.length;ge++){let ue=v[ge],_e=Object.create(d),I=fr(e,ue,r,n,o,f===!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(b!==void 0){let Q=`${i}/oneOf`,Be=ne.length,ke=b.filter((ge,ue)=>{let _e=Object.create(d),I=fr(e,ge,r,n,o,f===!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),x!==void 0){let Q=`${i}/if`;if(fr(e,x,r,n,o,s,a,Q,d).valid){if(E!==void 0){let ke=fr(e,E,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:Sh(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();Ah();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 G0(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 K0(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 J0(e){let t=Ph(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function X0(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 Y0(e){for(let t of z0)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 Q0(e){if(e===void 0){let r=_i;return{inputSchema:r,standardValidator:Ni(r)}}if(X0(e)){let r=Y0(e);return{inputSchema:r,standardValidator:Ni(r)}}if(J0(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 Z0(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=Q0(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 ew(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 tw(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=ew(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function rw(e,t){return tw(e,t[Lh])}function nw(e){return Dr(e)&&Array.isArray(e.content)}function ow(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Od(e){return ow(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 sw(e){if(!(!Dr(e)||!Od(e)))return e}function aw(e){var t;if(typeof e=="string")return e;try{return(t=JSON.stringify(e))!=null?t:String(e)}catch{return String(e)}}function iw(e){if(nw(e))return e;let t=sw(e);return{content:[{type:"text",text:aw(e)}],...t?{structuredContent:t}:{},isError:!1}}function lw(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 dw(e){var r;if(e.isError)throw Xn(((r=lw(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 cw(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 pw(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 uw(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 j0,i=a;if(i[q0]=!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,uw(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)&&(pw(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,z0,q0,Lh,dr,j0,V0,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:{}},z0=["draft-2020-12","draft-07"],q0="__isWebMCPPolyfill",Lh=Symbol("standardValidator"),dr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},j0=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=Z0(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=K0(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 V0(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=G0(r),i=await rw(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),m=await cw(Promise.resolve(u),n==null?void 0:n.signal);if(o)return dw(iw(m));let f=JSON.stringify(m);return f===void 0?null:f}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."))}},V0=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 ww=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]})),Cw=Or&&Or.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&ww(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}});Cw(Nd(),Or);var zi=class extends Error{};Or.PartialJSON=zi;var qi=class extends Error{};Or.MalformedJSON=qi;function Nh(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 vw(e.trim(),t)}Or.parseJSON=Nh;var vw=(e,t)=>{let r=e.length,n=0,o=m=>{throw new zi(`${m} at position ${n}`)},s=m=>{throw new qi(`${m} 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 m=n,f=!1;for(n++;n<r&&(e[n]!=='"'||f&&e[n-1]==="\\");)f=e[n]==="\\"?!f:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(m,++n-Number(f)))}catch(y){s(String(y))}else if(Zr.Allow.STR&t)try{return JSON.parse(e.substring(m,n-Number(f))+'"')}catch{return JSON.parse(e.substring(m,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,u();let m={};try{for(;e[n]!=="}";){if(u(),n>=r&&Zr.Allow.OBJ&t)return m;let f=i();u(),n++;try{let y=a();m[f]=y}catch(y){if(Zr.Allow.OBJ&t)return m;throw y}u(),e[n]===","&&n++}}catch{if(Zr.Allow.OBJ&t)return m;o("Expected '}' at end of object")}return n++,m},l=()=>{n++;let m=[];try{for(;e[n]!=="]";)m.push(a()),u(),e[n]===","&&n++}catch{if(Zr.Allow.ARR&t)return m;o("Expected ']' at end of array")}return n++,m},p=()=>{if(n===0){e==="-"&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Zr.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}s(String(f))}}let m=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(m,n))}catch{e.substring(m,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(e.substring(m,e.lastIndexOf("e")))}catch(y){s(String(y))}}},u=()=>{for(;n<r&&`
|
|
5
|
+
\r `.includes(e[n]);)n++};return a()},Aw=Nh;Or.parse=Aw});var HA={};Og(HA,{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:()=>ax,VERSION:()=>xs,WEBMCP_TOOL_PREFIX:()=>Ia,WebMcpBridge:()=>Ws,accessibilityPlugin:()=>Ny,animationsPlugin:()=>$y,applyThemeVariables:()=>Io,attachHeaderToContainer:()=>us,brandPlugin:()=>Fy,buildComposer:()=>Fs,buildDefaultHeader:()=>Jp,buildHeader:()=>go,buildHeaderWithLayout:()=>$s,buildMinimalHeader:()=>Xp,collectEnrichedPageContext:()=>Ay,componentRegistry:()=>yo,createActionManager:()=>ni,createAgentExperience:()=>rd,createAskUserQuestionBubble:()=>Nx,createBestAvailableVoiceProvider:()=>al,createBubbleWithLayout:()=>Sx,createCSATFeedback:()=>Zl,createComboButton:()=>Hl,createComponentMiddleware:()=>ny,createComponentStreamParser:()=>Jl,createDefaultSanitizer:()=>Pd,createDemoCarousel:()=>_y,createDirectivePostprocessor:()=>sh,createDropdownMenu:()=>Bo,createFlexibleJsonStreamParser:()=>Uh,createIconButton:()=>ir,createImagePart:()=>Jh,createJsonStreamParser:()=>Qi,createLabelButton:()=>Ja,createLocalStorageAdapter:()=>Kl,createMarkdownProcessor:()=>Ta,createMarkdownProcessorFromConfig:()=>ns,createMessageActions:()=>tu,createNPSFeedback:()=>ed,createPlainTextParser:()=>Xi,createPlugin:()=>qy,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:()=>Xh,formatEnrichedContext:()=>Sy,generateAssistantMessageId:()=>is,generateCodeSnippet:()=>Iy,generateMessageId:()=>qh,generateStableSelector:()=>Eu,generateUserMessageId:()=>Bs,getActiveTheme:()=>Ns,getColorScheme:()=>Fp,getDisplayText:()=>Vh,getHeaderLayout:()=>Yp,getImageParts:()=>Kh,getPreset:()=>Vy,hasComponentDirective:()=>Yl,hasImages:()=>Gh,headerLayouts:()=>Bl,highContrastPlugin:()=>zy,initAgentWidget:()=>uy,isAskUserQuestionMessage:()=>ho,isComponentDirectiveType:()=>ry,isDockedMountMode:()=>Tr,isVoiceSupported:()=>Oa,isWebMcpToolName:()=>Ra,listRegisteredStreamAnimations:()=>jp,markdownPostprocessor:()=>Cd,mergeWithDefaults:()=>bl,normalizeContent:()=>jh,parseAskUserQuestionPayload:()=>xo,pluginRegistry:()=>ti,reducedMotionPlugin:()=>Uy,registerStreamAnimationPlugin:()=>ps,removeAskUserQuestionSheet:()=>_o,renderComponentDirective:()=>Xl,renderLoadingIndicatorWithFallback:()=>eu,renderLucideIcon:()=>Pe,resolveDockConfig:()=>kn,resolveSanitizer:()=>Ps,resolveTokens:()=>wl,stripWebMcpPrefix:()=>_d,themeToCssVariables:()=>Cl,unregisterStreamAnimationPlugin:()=>qp,validateImageFile:()=>Yh,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=/[&<>"']/,cb=new RegExp(Vg.source,"g"),Gg=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,pb=new RegExp(Gg.source,"g"),ub={"&":"&","<":"<",">":">",'"':""","'":"'"},$g=e=>ub[e];function gn(e,t){if(t){if(Vg.test(e))return e.replace(cb,$g)}else if(Gg.test(e))return e.replace(pb,$g);return e}var fb=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function mb(e){return e.replace(fb,(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 gb=/(^|[^\[])\^/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(gb,"$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 hb(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 xb(e,t){let r=e.match(/^(\s+)(?:```)/);if(r===null)return t;let n=r[1];return t.split(`
|
|
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=xb(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
11
|
`,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),m=t.split(`
|
|
12
|
-
`,1)[0],f=0;this.options.pedantic?(f=2,d=u.trimStart()):(f=r[2].search(/[^ ]/),f=f>4?1:f,d=u.slice(f),f+=r[1].length);let
|
|
13
|
-
`,t=t.substring(m.length+1),p=!0),!p){let T=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),
|
|
14
|
-
`,1)[0];if(m=
|
|
15
|
-
`+m.slice(f);else{if(
|
|
16
|
-
`+m}!
|
|
17
|
-
`,t=t.substring(
|
|
18
|
-
`):[],
|
|
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:
|
|
20
|
-
]`).replace("lheading",
|
|
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,a
|
|
12
|
+
`,1)[0],f=0;this.options.pedantic?(f=2,d=u.trimStart()):(f=r[2].search(/[^ ]/),f=f>4?1:f,d=u.slice(f),f+=r[1].length);let y=!1;if(!u&&/^ *$/.test(m)&&(i+=m+`
|
|
13
|
+
`,t=t.substring(m.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+|$)`),M=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),v=new RegExp(`^ {0,${Math.min(3,f-1)}}#`);for(;t;){let b=t.split(`
|
|
14
|
+
`,1)[0];if(m=b,this.options.pedantic&&(m=m.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),M.test(m)||v.test(m)||T.test(m)||S.test(t))break;if(m.search(/[^ ]/)>=f||!m.trim())d+=`
|
|
15
|
+
`+m.slice(f);else{if(y||u.search(/[^ ]/)>=4||M.test(u)||v.test(u)||S.test(u))break;d+=`
|
|
16
|
+
`+m}!y&&!m.trim()&&(y=!0),i+=b+`
|
|
17
|
+
`,t=t.substring(b.length+1),u=m.slice(f)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let C=null,k;this.options.gfm&&(C=/^\[[ xX]\] /.exec(d),C&&(k=C[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!C,checked:k,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(f=>f.type==="space"),m=u.length>0&&u.some(f=>/\n.*\n/.test(f.raw));s.loose=m}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=hb(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 m=[...o[0]][0].length,f=t.slice(0,a+o.index+m+d);if(Math.min(a,d)%2){let C=f.slice(1,-1);return{type:"em",raw:f,text:C,tokens:this.lexer.inlineTokens(C)}}let y=f.slice(2,-2);return{type:"strong",raw:f,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}}}},yb=/^(?: *(?:\n|$))+/,bb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,wb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Aa=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cb=/^ {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]+)*)/,vb=/^[^\n]+/,xd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Ab=nr(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",xd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Sb=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]*?(?:-->|$))/,Tb=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",Aa).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(),Mb=nr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xg).getRegex(),bd={blockquote:Mb,code:bb,def:Ab,fences:wb,heading:Cb,hr:Aa,html:Tb,lheading:Jg,list:Sb,newline:yb,paragraph:Xg,table:wa,text:vb},qg=nr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Aa).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(),kb={...bd,table:qg,paragraph:nr(hd).replace("hr",Aa).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()},Eb={...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",Aa).replace("heading",` *#{1,6} *[^
|
|
20
|
+
]`).replace("lheading",Jg).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Yg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Lb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Qg=/^( {2,}|\\)\n(?!\s*$)/,Pb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Sa="\\p{P}\\p{S}",Ib=nr(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Sa).getRegex(),Rb=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,Wb=nr(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Sa).getRegex(),Hb=nr("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Sa).getRegex(),Bb=nr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Sa).getRegex(),Db=nr(/\\([punct])/,"gu").replace(/punct/g,Sa).getRegex(),Ob=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(),Nb=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=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,$b=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(),Fb=nr("reflink|nolink(?!\\()","g").replace("reflink",Zg).replace("nolink",eh).getRegex(),wd={_backpedal:wa,anyPunctuation:Db,autolink:Ob,blockSkip:Rb,br:Qg,code:Lb,del:wa,emStrongLDelim:Wb,emStrongRDelimAst:Hb,emStrongRDelimUnd:Bb,escape:Yg,link:$b,nolink:eh,punctuation:Ib,reflink:Zg,reflinkSearch:Fb,tag:Nb,text:Pb,url:wa},Ub={...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.!#$%&'*+\/=?_`{\|}~-]+@)))/},zb={...fd,br:nr(Qg).replace("{2,}","*").getRegex(),text:nr(fd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ei={normal:bd,gfm:kb,pedantic:Eb},ba={normal:wd,gfm:fd,breaks:zb,pedantic:Ub},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
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+=`
|
|
23
23
|
`+n.raw,o.text+=`
|
|
24
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+=`
|
|
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(
|
|
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+=`
|
|
27
27
|
`+n.raw,o.text+=`
|
|
28
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n),s
|
|
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+=`
|
|
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,a
|
|
31
|
-
`,o?'<pre><code class="language-'+
|
|
32
|
-
`:"<pre><code>"+(n?t:
|
|
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),m;this.options.extensions.startInline.forEach(f=>{m=f.call({lexer:this},u),typeof m=="number"&&m>=0&&(p=Math.min(p,m))}),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
33
|
`}blockquote(t){return`<blockquote>
|
|
34
34
|
${t}</blockquote>
|
|
35
35
|
`}html(t,r){return t}heading(t,r,n){return`<h${r}>${t}</h${r}>
|
|
36
36
|
`}hr(){return`<hr>
|
|
37
|
-
`}list(t,r,n){let o=r?"ol":"ul",
|
|
37
|
+
`}list(t,r,n){let o=r?"ol":"ul",s=r&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
|
|
38
38
|
`+t+"</"+o+`>
|
|
39
39
|
`}listitem(t,r,n){return`<li>${t}</li>
|
|
40
40
|
`}checkbox(t){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(t){return`<p>${t}</p>
|
|
@@ -45,24 +45,24 @@ ${t}</blockquote>
|
|
|
45
45
|
`}tablerow(t){return`<tr>
|
|
46
46
|
${t}</tr>
|
|
47
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=
|
|
49
|
-
`+(
|
|
50
|
-
Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error occurred:</p><pre>"+mn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var Zo=new bs;function er(e,t){return Zo.parse(e,t)}er.options=er.setOptions=function(e){return Zo.setOptions(e),er.defaults=Zo.defaults,Ng(er.defaults),er};er.getDefaults=pd;er.defaults=ta;er.use=function(...e){return Zo.use(...e),er.defaults=Zo.defaults,Ng(er.defaults),er};er.walkTokens=function(e,t){return Zo.walkTokens(e,t)};er.parseInline=Zo.parseInline;er.Parser=lo;er.parser=lo.parse;er.Renderer=Ma;er.TextRenderer=ys;er.Lexer=io;er.lexer=io.lex;er.Tokenizer=Ta;er.Hooks=Qo;er.parse=er;var hA=er.options,xA=er.setOptions,yA=er.use,bA=er.walkTokens,wA=er.parseInline;var CA=lo.parse,vA=io.lex;var Bb=e=>{if(e)return e},vs=e=>{var o,a;let t=e==null?void 0:e.markedOptions,r=new bs({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(a=t==null?void 0:t.breaks)!=null?a:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),n=Bb(e==null?void 0:e.renderer);return n&&r.use({renderer:n}),s=>r.parse(s)},ra=e=>e?vs({markedOptions:e.options,renderer:e.renderer}):vs(),Db=vs(),xd=e=>Db(e),na=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Yg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Xg=e=>`%%FORM_PLACEHOLDER_${e}%%`,Qg=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let a=JSON.parse(o.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=Xg(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return n}return n}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let a=Xg(t.length);return t.push({token:a,type:o}),a}),r},Zg=e=>{let t=ra(e);return r=>{let n=[],o=Qg(r,n),a=t(o);return n.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Yg(i)}"></div>`;a=a.replace(d,p)}),a}},eh=e=>{let t=[],r=Qg(e,t),n=xd(r);return t.forEach(({token:o,type:a})=>{let s=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Yg(a)}"></div>`;n=n.replace(s,d)}),n};var{entries:dh,setPrototypeOf:th,isFrozen:Ob,getPrototypeOf:_b,getOwnPropertyDescriptor:Nb}=Object,{freeze:Jr,seal:Tn,create:Pi}=Object,{apply:Sd,construct:Td}=typeof Reflect!="undefined"&&Reflect;Jr||(Jr=function(t){return t});Tn||(Tn=function(t){return t});Sd||(Sd=function(t,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),a=2;a<n;a++)o[a-2]=arguments[a];return t.apply(r,o)});Td||(Td=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 Ei=Xr(Array.prototype.forEach),$b=Xr(Array.prototype.lastIndexOf),rh=Xr(Array.prototype.pop),As=Xr(Array.prototype.push),Fb=Xr(Array.prototype.splice),Ii=Xr(String.prototype.toLowerCase),yd=Xr(String.prototype.toString),bd=Xr(String.prototype.match),Ss=Xr(String.prototype.replace),Ub=Xr(String.prototype.indexOf),zb=Xr(String.prototype.trim),gn=Xr(Object.prototype.hasOwnProperty),Kr=Xr(RegExp.prototype.test),Ts=qb(TypeError);function Xr(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 Sd(e,t,n)}}function qb(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return Td(e,r)}}function Pt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ii;th&&th(e,null);let n=t.length;for(;n--;){let o=t[n];if(typeof o=="string"){let a=r(o);a!==o&&(Ob(t)||(t[n]=a),o=a)}e[o]=!0}return e}function jb(e){for(let t=0;t<e.length;t++)gn(e,t)||(e[t]=null);return e}function Gn(e){let t=Pi(null);for(let[r,n]of dh(e))gn(e,r)&&(Array.isArray(n)?t[r]=jb(n):n&&typeof n=="object"&&n.constructor===Object?t[r]=Gn(n):t[r]=n);return t}function Ms(e,t){for(;e!==null;){let n=Nb(e,t);if(n){if(n.get)return Xr(n.get);if(typeof n.value=="function")return Xr(n.value)}e=_b(e)}function r(){return null}return r}var nh=Jr(["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"]),wd=Jr(["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"]),Cd=Jr(["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"]),Vb=Jr(["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"]),vd=Jr(["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"]),Gb=Jr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),oh=Jr(["#text"]),ah=Jr(["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"]),Ad=Jr(["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"]),sh=Jr(["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=Jr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Kb=Tn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Jb=Tn(/<%[\w\W]*|[\w\W]*%>/gm),Xb=Tn(/\$\{[\w\W]*/gm),Yb=Tn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Qb=Tn(/^aria-[\-\w]+$/),ch=Tn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Zb=Tn(/^(?:\w+script|data):/i),e0=Tn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ph=Tn(/^html$/i),t0=Tn(/^[a-z][.\w]*(-[.\w]+)+$/i),ih=Object.freeze({__proto__:null,ARIA_ATTR:Qb,ATTR_WHITESPACE:e0,CUSTOM_ELEMENT:t0,DATA_ATTR:Yb,DOCTYPE_NAME:ph,ERB_EXPR:Jb,IS_ALLOWED_URI:ch,IS_SCRIPT_OR_DATA:Zb,MUSTACHE_EXPR:Kb,TMPLIT_EXPR:Xb}),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},r0=function(){return typeof window=="undefined"?null:window},n0=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 a="dompurify"+(n?"#"+n:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},lh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function uh(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:r0(),t=Fe=>uh(Fe);if(t.version="3.3.3",t.removed=[],!e||!e.document||e.document.nodeType!==ks.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e,n=r,o=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:m,trustedTypes:f}=e,x=d.prototype,C=Ms(x,"cloneNode"),M=Ms(x,"remove"),T=Ms(x,"nextSibling"),A=Ms(x,"childNodes"),k=Ms(x,"parentNode");if(typeof s=="function"){let Fe=r.createElement("template");Fe.content&&Fe.content.ownerDocument&&(r=Fe.content.ownerDocument)}let v,w="",{implementation:h,createNodeIterator:E,createDocumentFragment:W,getElementsByTagName:R}=r,{importNode:I}=n,H=lh();t.isSupported=typeof dh=="function"&&typeof k=="function"&&h&&h.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:G,ERB_EXPR:ie,TMPLIT_EXPR:ye,DATA_ATTR:Oe,ARIA_ATTR:et,IS_SCRIPT_OR_DATA:be,ATTR_WHITESPACE:xe,CUSTOM_ELEMENT:Ie}=ih,{IS_ALLOWED_URI:Je}=ih,X=null,Te=Pt({},[...nh,...wd,...Cd,...vd,...oh]),K=null,ge=Pt({},[...ah,...Ad,...sh,...Li]),ce=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}})),fe=null,He=null,rt=Object.seal(Pi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Q=!0,de=!0,_e=!1,Y=!0,V=!1,Ce=!0,Be=!1,oe=!1,Ee=!1,we=!1,Dt=!1,U=!1,ae=!0,ze=!1,he="user-content-",Re=!0,ve=!1,ue={},Z=null,O=Pt({},["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"]),me=null,qe=Pt({},["audio","video","img","source","image","track"]),$e=null,Xe=Pt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),mt="http://www.w3.org/1998/Math/MathML",ct="http://www.w3.org/2000/svg",yt="http://www.w3.org/1999/xhtml",jt=yt,N=!1,Me=null,ke=Pt({},[mt,ct,yt],yd),gt=Pt({},["mi","mo","mn","ms","mtext"]),tt=Pt({},["annotation-xml"]),Ut=Pt({},["title","style","font","a","script"]),dr=null,Ot=["application/xhtml+xml","text/html"],It="text/html",lt=null,ht=null,ar=r.createElement("form"),yn=function(P){return P instanceof RegExp||P instanceof Function},Hr=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(ht&&ht===P)){if((!P||typeof P!="object")&&(P={}),P=Gn(P),dr=Ot.indexOf(P.PARSER_MEDIA_TYPE)===-1?It:P.PARSER_MEDIA_TYPE,lt=dr==="application/xhtml+xml"?yd:Ii,X=gn(P,"ALLOWED_TAGS")?Pt({},P.ALLOWED_TAGS,lt):Te,K=gn(P,"ALLOWED_ATTR")?Pt({},P.ALLOWED_ATTR,lt):ge,Me=gn(P,"ALLOWED_NAMESPACES")?Pt({},P.ALLOWED_NAMESPACES,yd):ke,$e=gn(P,"ADD_URI_SAFE_ATTR")?Pt(Gn(Xe),P.ADD_URI_SAFE_ATTR,lt):Xe,me=gn(P,"ADD_DATA_URI_TAGS")?Pt(Gn(qe),P.ADD_DATA_URI_TAGS,lt):qe,Z=gn(P,"FORBID_CONTENTS")?Pt({},P.FORBID_CONTENTS,lt):O,fe=gn(P,"FORBID_TAGS")?Pt({},P.FORBID_TAGS,lt):Gn({}),He=gn(P,"FORBID_ATTR")?Pt({},P.FORBID_ATTR,lt):Gn({}),ue=gn(P,"USE_PROFILES")?P.USE_PROFILES:!1,Q=P.ALLOW_ARIA_ATTR!==!1,de=P.ALLOW_DATA_ATTR!==!1,_e=P.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=P.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=P.SAFE_FOR_TEMPLATES||!1,Ce=P.SAFE_FOR_XML!==!1,Be=P.WHOLE_DOCUMENT||!1,we=P.RETURN_DOM||!1,Dt=P.RETURN_DOM_FRAGMENT||!1,U=P.RETURN_TRUSTED_TYPE||!1,Ee=P.FORCE_BODY||!1,ae=P.SANITIZE_DOM!==!1,ze=P.SANITIZE_NAMED_PROPS||!1,Re=P.KEEP_CONTENT!==!1,ve=P.IN_PLACE||!1,Je=P.ALLOWED_URI_REGEXP||ch,jt=P.NAMESPACE||yt,gt=P.MATHML_TEXT_INTEGRATION_POINTS||gt,tt=P.HTML_INTEGRATION_POINTS||tt,ce=P.CUSTOM_ELEMENT_HANDLING||{},P.CUSTOM_ELEMENT_HANDLING&&yn(P.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ce.tagNameCheck=P.CUSTOM_ELEMENT_HANDLING.tagNameCheck),P.CUSTOM_ELEMENT_HANDLING&&yn(P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ce.attributeNameCheck=P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),P.CUSTOM_ELEMENT_HANDLING&&typeof P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(ce.allowCustomizedBuiltInElements=P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),V&&(de=!1),Dt&&(we=!0),ue&&(X=Pt({},oh),K=Pi(null),ue.html===!0&&(Pt(X,nh),Pt(K,ah)),ue.svg===!0&&(Pt(X,wd),Pt(K,Ad),Pt(K,Li)),ue.svgFilters===!0&&(Pt(X,Cd),Pt(K,Ad),Pt(K,Li)),ue.mathMl===!0&&(Pt(X,vd),Pt(K,sh),Pt(K,Li))),gn(P,"ADD_TAGS")||(rt.tagCheck=null),gn(P,"ADD_ATTR")||(rt.attributeCheck=null),P.ADD_TAGS&&(typeof P.ADD_TAGS=="function"?rt.tagCheck=P.ADD_TAGS:(X===Te&&(X=Gn(X)),Pt(X,P.ADD_TAGS,lt))),P.ADD_ATTR&&(typeof P.ADD_ATTR=="function"?rt.attributeCheck=P.ADD_ATTR:(K===ge&&(K=Gn(K)),Pt(K,P.ADD_ATTR,lt))),P.ADD_URI_SAFE_ATTR&&Pt($e,P.ADD_URI_SAFE_ATTR,lt),P.FORBID_CONTENTS&&(Z===O&&(Z=Gn(Z)),Pt(Z,P.FORBID_CONTENTS,lt)),P.ADD_FORBID_CONTENTS&&(Z===O&&(Z=Gn(Z)),Pt(Z,P.ADD_FORBID_CONTENTS,lt)),Re&&(X["#text"]=!0),Be&&Pt(X,["html","head","body"]),X.table&&(Pt(X,["tbody"]),delete fe.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.');v=P.TRUSTED_TYPES_POLICY,w=v.createHTML("")}else v===void 0&&(v=n0(f,o)),v!==null&&typeof w=="string"&&(w=v.createHTML(""));Jr&&Jr(P),ht=P}},Ln=Pt({},[...wd,...Cd,...Vb]),Rt=Pt({},[...vd,...Gb]),bn=function(P){let ee=k(P);(!ee||!ee.tagName)&&(ee={namespaceURI:jt,tagName:"template"});let pe=Ii(P.tagName),Wt=Ii(ee.tagName);return Me[P.namespaceURI]?P.namespaceURI===ct?ee.namespaceURI===yt?pe==="svg":ee.namespaceURI===mt?pe==="svg"&&(Wt==="annotation-xml"||gt[Wt]):!!Ln[pe]:P.namespaceURI===mt?ee.namespaceURI===yt?pe==="math":ee.namespaceURI===ct?pe==="math"&&tt[Wt]:!!Rt[pe]:P.namespaceURI===yt?ee.namespaceURI===ct&&!tt[Wt]||ee.namespaceURI===mt&&!gt[Wt]?!1:!Rt[pe]&&(Ut[pe]||!Ln[pe]):!!(dr==="application/xhtml+xml"&&Me[P.namespaceURI]):!1},hr=function(P){As(t.removed,{element:P});try{k(P).removeChild(P)}catch{M(P)}},Mr=function(P,ee){try{As(t.removed,{attribute:ee.getAttributeNode(P),from:ee})}catch{As(t.removed,{attribute:null,from:ee})}if(ee.removeAttribute(P),P==="is")if(we||Dt)try{hr(ee)}catch{}else try{ee.setAttribute(P,"")}catch{}},Zr=function(P){let ee=null,pe=null;if(Ee)P="<remove></remove>"+P;else{let Nt=bd(P,/^[\r\n\t ]+/);pe=Nt&&Nt[0]}dr==="application/xhtml+xml"&&jt===yt&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");let Wt=v?v.createHTML(P):P;if(jt===yt)try{ee=new m().parseFromString(Wt,dr)}catch{}if(!ee||!ee.documentElement){ee=h.createDocument(jt,"template",null);try{ee.documentElement.innerHTML=N?w:Wt}catch{}}let Jt=ee.body||ee.documentElement;return P&&pe&&Jt.insertBefore(r.createTextNode(pe),Jt.childNodes[0]||null),jt===yt?R.call(ee,Be?"html":"body")[0]:Be?ee.documentElement:Jt},Tt=function(P){return E.call(P.ownerDocument||P,P,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Pn=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 kr(Fe,P,ee){Ei(Fe,pe=>{pe.call(t,P,ee,ht)})}let Er=function(P){let ee=null;if(kr(H.beforeSanitizeElements,P,null),Pn(P))return hr(P),!0;let pe=lt(P.nodeName);if(kr(H.uponSanitizeElement,P,{tagName:pe,allowedTags:X}),Ce&&P.hasChildNodes()&&!an(P.firstElementChild)&&Kr(/<[/\w!]/g,P.innerHTML)&&Kr(/<[/\w!]/g,P.textContent)||P.nodeType===ks.progressingInstruction||Ce&&P.nodeType===ks.comment&&Kr(/<[/\w]/g,P.data))return hr(P),!0;if(!(rt.tagCheck instanceof Function&&rt.tagCheck(pe))&&(!X[pe]||fe[pe])){if(!fe[pe]&&In(pe)&&(ce.tagNameCheck instanceof RegExp&&Kr(ce.tagNameCheck,pe)||ce.tagNameCheck instanceof Function&&ce.tagNameCheck(pe)))return!1;if(Re&&!Z[pe]){let Wt=k(P)||P.parentNode,Jt=A(P)||P.childNodes;if(Jt&&Wt){let Nt=Jt.length;for(let cr=Nt-1;cr>=0;--cr){let wr=C(Jt[cr],!0);wr.__removalCount=(P.__removalCount||0)+1,Wt.insertBefore(wr,T(P))}}}return hr(P),!0}return P instanceof d&&!bn(P)||(pe==="noscript"||pe==="noembed"||pe==="noframes")&&Kr(/<\/no(script|embed|frames)/i,P.innerHTML)?(hr(P),!0):(V&&P.nodeType===ks.text&&(ee=P.textContent,Ei([G,ie,ye],Wt=>{ee=Ss(ee,Wt," ")}),P.textContent!==ee&&(As(t.removed,{element:P.cloneNode()}),P.textContent=ee)),kr(H.afterSanitizeElements,P,null),!1)},Qn=function(P,ee,pe){if(He[ee]||ae&&(ee==="id"||ee==="name")&&(pe in r||pe in ar))return!1;if(!(de&&!He[ee]&&Kr(Oe,ee))){if(!(Q&&Kr(et,ee))){if(!(rt.attributeCheck instanceof Function&&rt.attributeCheck(ee,P))){if(!K[ee]||He[ee]){if(!(In(P)&&(ce.tagNameCheck instanceof RegExp&&Kr(ce.tagNameCheck,P)||ce.tagNameCheck instanceof Function&&ce.tagNameCheck(P))&&(ce.attributeNameCheck instanceof RegExp&&Kr(ce.attributeNameCheck,ee)||ce.attributeNameCheck instanceof Function&&ce.attributeNameCheck(ee,P))||ee==="is"&&ce.allowCustomizedBuiltInElements&&(ce.tagNameCheck instanceof RegExp&&Kr(ce.tagNameCheck,pe)||ce.tagNameCheck instanceof Function&&ce.tagNameCheck(pe))))return!1}else if(!$e[ee]){if(!Kr(Je,Ss(pe,xe,""))){if(!((ee==="src"||ee==="xlink:href"||ee==="href")&&P!=="script"&&Ub(pe,"data:")===0&&me[P])){if(!(_e&&!Kr(be,Ss(pe,xe,"")))){if(pe)return!1}}}}}}}return!0},In=function(P){return P!=="annotation-xml"&&bd(P,Ie)},wn=function(P){kr(H.beforeSanitizeAttributes,P,null);let{attributes:ee}=P;if(!ee||Pn(P))return;let pe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0},Wt=ee.length;for(;Wt--;){let Jt=ee[Wt],{name:Nt,namespaceURI:cr,value:wr}=Jt,$r=lt(Nt),Lr=wr,pt=Nt==="value"?Lr:zb(Lr);if(pe.attrName=$r,pe.attrValue=pt,pe.keepAttr=!0,pe.forceKeepAttr=void 0,kr(H.uponSanitizeAttribute,P,pe),pt=pe.attrValue,ze&&($r==="id"||$r==="name")&&(Mr(Nt,P),pt=he+pt),Ce&&Kr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,pt)){Mr(Nt,P);continue}if($r==="attributename"&&bd(pt,"href")){Mr(Nt,P);continue}if(pe.forceKeepAttr)continue;if(!pe.keepAttr){Mr(Nt,P);continue}if(!Y&&Kr(/\/>/i,pt)){Mr(Nt,P);continue}V&&Ei([G,ie,ye],Fr=>{pt=Ss(pt,Fr," ")});let Tr=lt(P.nodeName);if(!Qn(Tr,$r,pt)){Mr(Nt,P);continue}if(v&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!cr)switch(f.getAttributeType(Tr,$r)){case"TrustedHTML":{pt=v.createHTML(pt);break}case"TrustedScriptURL":{pt=v.createScriptURL(pt);break}}if(pt!==Lr)try{cr?P.setAttributeNS(cr,Nt,pt):P.setAttribute(Nt,pt),Pn(P)?hr(P):rh(t.removed)}catch{Mr(Nt,P)}}kr(H.afterSanitizeAttributes,P,null)},Et=function Fe(P){let ee=null,pe=Tt(P);for(kr(H.beforeSanitizeShadowDOM,P,null);ee=pe.nextNode();)kr(H.uponSanitizeShadowNode,ee,null),Er(ee),wn(ee),ee.content instanceof a&&Fe(ee.content);kr(H.afterSanitizeShadowDOM,P,null)};return t.sanitize=function(Fe){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ee=null,pe=null,Wt=null,Jt=null;if(N=!Fe,N&&(Fe="<!-->"),typeof Fe!="string"&&!an(Fe))if(typeof Fe.toString=="function"){if(Fe=Fe.toString(),typeof Fe!="string")throw Ts("dirty is not a string, aborting")}else throw Ts("toString is not a function");if(!t.isSupported)return Fe;if(oe||Hr(P),t.removed=[],typeof Fe=="string"&&(ve=!1),ve){if(Fe.nodeName){let wr=lt(Fe.nodeName);if(!X[wr]||fe[wr])throw Ts("root node is forbidden and cannot be sanitized in-place")}}else if(Fe instanceof i)ee=Zr("<!---->"),pe=ee.ownerDocument.importNode(Fe,!0),pe.nodeType===ks.element&&pe.nodeName==="BODY"||pe.nodeName==="HTML"?ee=pe:ee.appendChild(pe);else{if(!we&&!V&&!Be&&Fe.indexOf("<")===-1)return v&&U?v.createHTML(Fe):Fe;if(ee=Zr(Fe),!ee)return we?null:U?w:""}ee&&Ee&&hr(ee.firstChild);let Nt=Tt(ve?Fe:ee);for(;Wt=Nt.nextNode();)Er(Wt),wn(Wt),Wt.content instanceof a&&Et(Wt.content);if(ve)return Fe;if(we){if(Dt)for(Jt=W.call(ee.ownerDocument);ee.firstChild;)Jt.appendChild(ee.firstChild);else Jt=ee;return(K.shadowroot||K.shadowrootmode)&&(Jt=I.call(n,Jt,!0)),Jt}let cr=Be?ee.outerHTML:ee.innerHTML;return Be&&X["!doctype"]&&ee.ownerDocument&&ee.ownerDocument.doctype&&ee.ownerDocument.doctype.name&&Kr(ph,ee.ownerDocument.doctype.name)&&(cr="<!DOCTYPE "+ee.ownerDocument.doctype.name+`>
|
|
51
|
-
`+
|
|
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,mb(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 m=0;m<u.length;m++)d+=this.renderer.tablecell(this.parseInline(u[m].tokens),{header:!1,align:a.align[m]});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 m=a.items[u],f=m.checked,y=m.task,C="";if(m.task){let k=this.renderer.checkbox(!!f);l?m.tokens.length>0&&m.tokens[0].type==="paragraph"?(m.tokens[0].text=k+" "+m.tokens[0].text,m.tokens[0].tokens&&m.tokens[0].tokens.length>0&&m.tokens[0].tokens[0].type==="text"&&(m.tokens[0].tokens[0].text=k+" "+m.tokens[0].tokens[0].text)):m.tokens.unshift({type:"text",text:k+" "}):C+=k+" "}C+=this.parse(m.tokens,l),p+=this.renderer.listitem(C,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<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(m=>l.call(s,m));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 OA=rr.options,_A=rr.setOptions,NA=rr.use,$A=rr.walkTokens,FA=rr.parseInline;var UA=po.parse,zA=co.lex;var qb=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=qb(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(),jb=Ta(),Cd=e=>jb(e),os=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),nh=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),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:Vb,getPrototypeOf:Gb,getOwnPropertyDescriptor:Kb}=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),Jb=Qr(Array.prototype.lastIndexOf),lh=Qr(Array.prototype.pop),Ma=Qr(Array.prototype.push),Xb=Qr(Array.prototype.splice),Hi=Qr(String.prototype.toLowerCase),vd=Qr(String.prototype.toString),Ad=Qr(String.prototype.match),ka=Qr(String.prototype.replace),Yb=Qr(String.prototype.indexOf),Qb=Qr(String.prototype.trim),hn=Qr(Object.prototype.hasOwnProperty),Xr=Qr(RegExp.prototype.test),Ea=Zb(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 Zb(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&&(Vb(t)||(t[n]=s),o=s)}e[o]=!0}return e}function e0(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]=e0(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=Kb(e,t);if(n){if(n.get)return Qr(n.get);if(typeof n.value=="function")return Qr(n.value)}e=Gb(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"]),Sd=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"]),t0=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"]),r0=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"]),n0=Mn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),o0=Mn(/<%[\w\W]*|[\w\W]*%>/gm),s0=Mn(/\$\{[\w\W]*/gm),a0=Mn(/^data-[\-\w.\u00B7-\uFFFF]+$/),i0=Mn(/^aria-[\-\w]+$/),hh=Mn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),l0=Mn(/^(?:\w+script|data):/i),d0=Mn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xh=Mn(/^html$/i),c0=Mn(/^[a-z][.\w]*(-[.\w]+)+$/i),fh=Object.freeze({__proto__:null,ARIA_ATTR:i0,ATTR_WHITESPACE:d0,CUSTOM_ELEMENT:c0,DATA_ATTR:a0,DOCTYPE_NAME:xh,ERB_EXPR:o0,IS_ALLOWED_URI:hh,IS_SCRIPT_OR_DATA:l0,MUSTACHE_EXPR:n0,TMPLIT_EXPR:s0}),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},p0=function(){return typeof window=="undefined"?null:window},u0=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]:p0(),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:m,trustedTypes:f}=e,y=d.prototype,C=La(y,"cloneNode"),k=La(y,"remove"),T=La(y,"nextSibling"),S=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 v,b="",{implementation:x,createNodeIterator:E,createDocumentFragment:B,getElementsByTagName:H}=r,{importNode:W}=n,N=mh();t.isSupported=typeof gh=="function"&&typeof M=="function"&&x&&x.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,...Sd,...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"]),Ae=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),Ae=Wt.indexOf(P.PARSER_MEDIA_TYPE)===-1?sr:P.PARSER_MEDIA_TYPE,Et=Ae==="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,Sd),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.');v=P.TRUSTED_TYPES_POLICY,b=v.createHTML("")}else v===void 0&&(v=u0(f,o)),v!==null&&typeof b=="string"&&(b=v.createHTML(""));Yr&&Yr(P),gr=P}},Lt=Rt({},[...Sd,...Td,...t0]),ar=Rt({},[...Md,...r0]),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]):!!(Ae==="application/xhtml+xml"&&X[P.namespaceURI]):!1},cr=function(P){Ma(t.removed,{element:P});try{M(P).removeChild(P)}catch{k(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=Ad(P,/^[\r\n\t ]+/);Ee=$t&&$t[0]}Ae==="application/xhtml+xml"&&zt===ht&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");let rt=v?v.createHTML(P):P;if(zt===ht)try{oe=new m().parseFromString(rt,Ae)}catch{}if(!oe||!oe.documentElement){oe=x.createDocument(zt,"template",null);try{oe.documentElement.innerHTML=or?b: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 E.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=S(P)||P.childNodes;if(Xt&&rt){let $t=Xt.length;for(let er=$t-1;er>=0;--er){let Pr=C(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"&&Yb(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"&&Ad(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:Qb(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"&&Ad(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(v&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!er)switch(f.getAttributeType(Ft,Nr)){case"TrustedHTML":{Vt=v.createHTML(Vt);break}case"TrustedScriptURL":{Vt=v.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 v&&ne?v.createHTML(me):me;if(oe=Lr(me),!oe)return J?null:ne?b:""}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," ")}),v&&ne?v.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=Jb(N[me],P);return oe===-1?void 0:Xb(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 f0={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"]},m0=/^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:")&&!m0.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),t=>e.sanitize(t,f0)},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)}},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=mw(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 f=typeof document!="undefined"&&!!document.modelContext;return $n(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=_d(t),a;try{a=await o.getTools()}catch(f){let y=f instanceof Error?f.message:String(f);return $n(`Failed to read WebMCP registry: ${y}`)}let i=a.find(f=>f.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),m=()=>l.abort();n&&(n.aborted?l.abort():n.addEventListener("abort",m,{once:!0}));try{let f=await o.executeTool(i,yw(r),{signal:l.signal});return gw(f)}catch(f){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=f instanceof Error?f.message:String(f);return $n(y)}finally{clearTimeout(u),n&&n.removeEventListener("abort",m)}}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:hw;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=>fw(t,n))}},_d=e=>e.startsWith(Ia)?e.slice(Ia.length):e,Ra=e=>e.startsWith(Ia),fw=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},mw=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},gw=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:bw(t)}]}},$n=e=>({isError:!0,content:[{type:"text",text:e}]}),hw=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=xw(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
|
|
52
52
|
|
|
53
53
|
Arguments:
|
|
54
54
|
${t}`:"")+(e.description?`
|
|
55
55
|
|
|
56
|
-
${e.description}`:"");return window.confirm(r)},
|
|
57
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
58
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return
|
|
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 a=r(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},oa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Gi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ki=()=>{var t;let e=xw();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)}},Ji=()=>{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,po.parse)(r,po.STR|po.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?zi(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=zi(o.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Dh=e=>{let t=null,r=0,o=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?zi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?zi(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,po.parse)(a,po.STR|po.OBJ),d=o(i);d!==null&&(t=d)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},Xi=()=>{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 Yi=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 a,s,i;let n=(i=(a=r==null?void 0:r.seq)!=null?a:r==null?void 0:r.sequenceIndex)!=null?i:(s=r==null?void 0:r.agentContext)==null?void 0:s.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 yw="https://api.runtype.com/v1/dispatch",Qi="https://api.runtype.com";function bw(e){var a,s;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=(s=(a=t.slice(o+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Od=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 ww(e){switch(e){case"json":return Ji;case"regex-json":return Ki;case"xml":return Xi;default:return Gi}}var Oh=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Cw(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=Oh(r);if(!Oh(n))return e;if(!o||n===r||n.startsWith(r))return t;let s=oa(e);return oa(t)!==null&&s===null?t:e}var aa=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,n,o,a;this.apiUrl=(r=t.apiUrl)!=null?r:yw,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(n=t.streamParser)!=null?n:ww(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=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Pa(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$/,""))||Qi}/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,(r=(t=this.config).onSessionInit)==null||r.call(t,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let t=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||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}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Qi}/v1/client/feedback`}async sendFeedback(t){var a,s;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,(s=(a=this.config).onSessionExpired)==null||s.call(a),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,a,s,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.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Od).map(f=>{var x,C,M;return{id:f.id,role:f.role,content:(M=(C=(x=f.contentParts)!=null?x:f.llmContent)!=null?C:f.rawContent)!=null?M:f.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},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!m.ok){let f=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(m.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let x=new Error(f.error||"Failed to send message");throw r({type:"error",error:x}),x}if(!m.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}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 a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,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 s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.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 a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,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 s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.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 s;let o=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Qi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,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(),a=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Qi}/resume`,s;o&&(s=(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 s&&(d.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(t){var a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Od).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,i)=>{let d=new Date(s.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(s=>{var i,d,l;return{role:s.role,content:(l=(d=(i=s.contentParts)!=null?i:s.llmContent)!=null?d:s.rawContent)!=null?l:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(s,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(t){var a;let n={messages:t.slice().filter(Od).sort((s,i)=>{let d=new Date(s.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(s=>{var i,d,l;return{role:s.role,content:(l=(d=(i=s.contentParts)!=null?i:s.llmContent)!=null?d:s.rawContent)!=null?l:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(s,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object"){let i=s;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(t,r,n,o,a,s){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:a(),...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&&s.current!==null&&i.partId!==s.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(s.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)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.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 Re,ve,ue,Z;let o=t.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,p=O=>{let me=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,qe=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,$e=O.tools?O.tools.map(Xe=>({...Xe,chunks:Xe.chunks?[...Xe.chunks]:void 0})):void 0;return{...O,reasoning:me,toolCall:qe,tools:$e}},u=O=>{r({type:"message",message:p(O)})},m=null,f=null,x={current:null},C={current:null},M=!1,T=new Map,A=new Map,k=new Map,v=new Map,w={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},E=(O,me,qe="")=>`${O}::${me}::${qe}`,W=(O,me)=>`${O}::${me}::`,R=(O,me,qe,$e)=>{let Xe=E(O,me,qe),mt=k.get(Xe);if(mt)return mt;let ct=qe?`-${qe}`:"",yt={id:`nested-${O}-${me}${ct}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...qe?{partId:qe}:{},agentMetadata:{executionId:$e,parentToolId:O,parentStepId:me}};return k.set(Xe,yt),u(yt),yt},I=O=>{if(O==null)return null;try{return String(O)}catch{return null}},H=O=>{var me,qe,$e,Xe,mt;return I((mt=(Xe=($e=(qe=(me=O.stepId)!=null?me:O.step_id)!=null?qe:O.step)!=null?$e:O.parentId)!=null?Xe:O.flowStepId)!=null?mt:O.flow_step_id)},G=O=>{var me,qe,$e,Xe,mt,ct,yt;return I((yt=(ct=(mt=(Xe=($e=(qe=(me=O.callId)!=null?me:O.call_id)!=null?qe:O.requestId)!=null?$e:O.request_id)!=null?Xe:O.toolCallId)!=null?mt:O.tool_call_id)!=null?ct:O.stepId)!=null?yt:O.step_id)},ie=n,ye=!1,Oe=()=>{if(m)return m;let O;return!ye&&ie?(O=ie,ye=!0):ie&&C.current?O=`${ie}_${C.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},et=(O,me)=>{w.lastId=me,O&&w.byStep.set(O,me)},be=(O,me)=>{var mt;let qe=(mt=O.reasoningId)!=null?mt:O.id,$e=H(O);if(qe){let ct=String(qe);return et($e,ct),ct}if($e){let ct=w.byStep.get($e);if(ct)return w.lastId=ct,ct}if(w.lastId&&!me)return w.lastId;if(!me)return null;let Xe=`reason-${l()}`;return et($e,Xe),Xe},xe=O=>{let me=T.get(O);if(me)return me;let qe={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return T.set(O,qe),u(qe),qe},Ie=(O,me)=>{h.lastId=me,O&&h.byCall.set(O,me)},Je=new Set,X=new Map,Te=new Set,K=new Map,ge=O=>{if(!O)return!1;let me=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},ce=(O,me)=>{var mt;let qe=(mt=O.toolId)!=null?mt:O.id,$e=G(O);if(qe){let ct=String(qe);return Ie($e,ct),ct}if($e){let ct=h.byCall.get($e);if(ct)return h.lastId=ct,ct}if(h.lastId&&!me)return h.lastId;if(!me)return null;let Xe=`tool-${l()}`;return Ie($e,Xe),Xe},fe=O=>{let me=A.get(O);if(me)return me;let qe={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return A.set(O,qe),u(qe),qe},He=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let me=Number(O);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let qe=Date.parse(O);if(!Number.isNaN(qe))return qe}return Date.now()},rt=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},Q=new Map,de=new Map,_e=new Map,Y=new Map,V=null,Ce=(O,me,qe)=>{var yt;let $e=_e.get(O);$e||($e=[],_e.set(O,$e));let Xe=0,mt=$e.length;for(;Xe<mt;){let jt=Xe+mt>>>1;$e[jt].seq<me?Xe=jt+1:mt=jt}((yt=$e[Xe])==null?void 0:yt.seq)===me?$e[Xe]={seq:me,text:qe}:$e.splice(Xe,0,{seq:me,text:qe});let ct="";for(let jt=0;jt<$e.length;jt++)ct+=$e[jt].text;return ct},Be=(O,me)=>{let qe=rt(me),$e=de.get(O.id),Xe=Cw($e,qe);O.rawContent=Xe;let mt=Q.get(O.id),ct=ke=>{var tt;let gt=(tt=O.content)!=null?tt:"";ke.trim()!==""&&(gt.trim().length===0||ke.startsWith(gt)||ke.trimStart().startsWith(gt.trim()))&&(O.content=ke)},yt=()=>{var ke;if(mt){let gt=(ke=mt.close)==null?void 0:ke.call(mt);gt instanceof Promise&>.catch(()=>{})}Q.delete(O.id),de.delete(O.id),O.streaming=!1,u(O)};if(!mt){ct(qe),yt();return}let jt=oa(Xe);if(jt!==null&&jt.trim()!==""){ct(jt),yt();return}let N=ke=>{var Ut;let gt=typeof ke=="string"?ke:(Ut=ke==null?void 0:ke.text)!=null?Ut:null;if(gt!==null&>.trim()!=="")return gt;let tt=mt.getExtractedText();return tt!==null&&tt.trim()!==""?tt:qe},Me;try{Me=mt.processChunk(Xe)}catch{ct(qe),yt();return}if(Me instanceof Promise){Me.then(ke=>{ct(N(ke)),yt()}).catch(()=>{ct(qe),yt()});return}ct(N(Me)),yt()},oe=[],Ee=!1,we,Dt=()=>{Ee||(Ee=!0,queueMicrotask(()=>{Ee=!1,we()}))},U=new Yi((O,me)=>{oe.push({payloadType:O,payload:me}),Dt()}),ae=null,ze=new Map,he=(Re=this.config.iterationDisplay)!=null?Re:"separate";for(we=()=>{var O,me,qe,$e,Xe,mt,ct,yt,jt,N,Me,ke,gt,tt,Ut,dr,Ot,It,lt,ht,ar,yn,Hr,Ln,Rt,bn,hr,Mr,Zr,Tt,Pn,an,kr,Er,Qn,In,wn,Et,Fe,P,ee,pe,Wt,Jt,Nt,cr,wr,$r,Lr,pt,Tr,Fr,yo,Zn,bo,Un,sn,Rn,Lt,pr,ur,ln,wo,Cn,Wn,dn,q,Se,cn,Hn,zn,Ja,Bn,Dn,On,eo,$o,ri,Xa,ni,ha,kt,Ya,vn,en,oi,ai,xa,to,si,Fo,Qa,ro,Za,Co,vo,ii,li,sd,Uo,Ao,di,es,So,ci,ts,To,rs,pi,no,ui,Mo,Kt,ya,ba,ns,qn,fi,os,as,mi,wa,Ca,zo,gi,hi,ss,is,ls,ds,Ur,pn,oo,bt,cs,qo,_n,xi;for(let ko=0;ko<oe.length;ko++){let ot=oe[ko].payloadType,L=oe[ko].payload;if(ot==="reason_start"){let j=(O=be(L,!0))!=null?O:`reason-${l()}`,_=xe(j);_.reasoning=(me=_.reasoning)!=null?me:{id:j,status:"streaming",chunks:[]},_.reasoning.startedAt=($e=_.reasoning.startedAt)!=null?$e:He((qe=L.startedAt)!=null?qe:L.timestamp),_.reasoning.completedAt=void 0,_.reasoning.durationMs=void 0,_.streaming=!0,_.reasoning.status="streaming",u(_)}else if(ot==="reason_delta"||ot==="reason_chunk"){let j=(mt=(Xe=be(L,!1))!=null?Xe:be(L,!0))!=null?mt:`reason-${l()}`,_=xe(j);_.reasoning=(ct=_.reasoning)!=null?ct:{id:j,status:"streaming",chunks:[]},_.reasoning.startedAt=(jt=_.reasoning.startedAt)!=null?jt:He((yt=L.startedAt)!=null?yt:L.timestamp);let se=(ke=(Me=(N=L.reasoningText)!=null?N:L.text)!=null?Me:L.delta)!=null?ke:"";if(se&&L.hidden!==!0){let te=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(te!==void 0){let re=Ce(j,te,String(se));_.reasoning.chunks=[re]}else _.reasoning.chunks.push(String(se))}if(_.reasoning.status=L.done?"complete":"streaming",L.done){_.reasoning.completedAt=He((gt=L.completedAt)!=null?gt:L.timestamp);let te=(tt=_.reasoning.startedAt)!=null?tt:Date.now();_.reasoning.durationMs=Math.max(0,((Ut=_.reasoning.completedAt)!=null?Ut:Date.now())-te)}_.streaming=_.reasoning.status!=="complete",u(_)}else if(ot==="reason_complete"){let j=(Ot=(dr=be(L,!1))!=null?dr:be(L,!0))!=null?Ot:`reason-${l()}`,_=T.get(j);if(_!=null&&_.reasoning){_.reasoning.status="complete",_.reasoning.completedAt=He((It=L.completedAt)!=null?It:L.timestamp);let te=(lt=_.reasoning.startedAt)!=null?lt:Date.now();_.reasoning.durationMs=Math.max(0,((ht=_.reasoning.completedAt)!=null?ht:Date.now())-te),_.streaming=!1,u(_)}let se=H(L);se&&w.byStep.delete(se)}else if(ot==="tool_start"){let j=(ar=ce(L,!0))!=null?ar:`tool-${l()}`,_=(yn=L.toolName)!=null?yn:L.name;if(ge(_)){Je.add(j);continue}let se=fe(j),te=(Hr=se.toolCall)!=null?Hr:{id:j,status:"pending"};te.name=_!=null?_:te.name,te.status="running",L.args!==void 0?te.args=L.args:L.parameters!==void 0&&(te.args=L.parameters),te.startedAt=(Rt=te.startedAt)!=null?Rt:He((Ln=L.startedAt)!=null?Ln:L.timestamp),te.completedAt=void 0,te.durationMs=void 0,se.toolCall=te,se.streaming=!0;let re=L.agentContext;(re||L.executionId)&&(se.agentMetadata={executionId:(bn=re==null?void 0:re.executionId)!=null?bn:L.executionId,iteration:(hr=re==null?void 0:re.iteration)!=null?hr:L.iteration}),u(se)}else if(ot==="tool_chunk"||ot==="tool_delta"){let j=(Zr=(Mr=ce(L,!1))!=null?Mr:ce(L,!0))!=null?Zr:`tool-${l()}`;if(Je.has(j))continue;let _=fe(j),se=(Tt=_.toolCall)!=null?Tt:{id:j,status:"running"};se.startedAt=(an=se.startedAt)!=null?an:He((Pn=L.startedAt)!=null?Pn:L.timestamp);let te=(Qn=(Er=(kr=L.text)!=null?kr:L.delta)!=null?Er:L.message)!=null?Qn:"";te&&(se.chunks=(In=se.chunks)!=null?In:[],se.chunks.push(String(te))),se.status="running",_.toolCall=se,_.streaming=!0;let re=L.agentContext;(re||L.executionId)&&(_.agentMetadata=(Fe=_.agentMetadata)!=null?Fe:{executionId:(wn=re==null?void 0:re.executionId)!=null?wn:L.executionId,iteration:(Et=re==null?void 0:re.iteration)!=null?Et:L.iteration}),u(_)}else if(ot==="tool_complete"){let j=(ee=(P=ce(L,!1))!=null?P:ce(L,!0))!=null?ee:`tool-${l()}`;if(Je.has(j)){Je.delete(j);continue}let _=fe(j),se=(pe=_.toolCall)!=null?pe:{id:j,status:"running"};se.status="complete",L.result!==void 0&&(se.result=L.result),typeof L.duration=="number"&&(se.duration=L.duration),se.completedAt=He((Wt=L.completedAt)!=null?Wt:L.timestamp);let te=(Jt=L.duration)!=null?Jt:L.executionTime;if(typeof te=="number")se.durationMs=te;else{let Ze=(Nt=se.startedAt)!=null?Nt:Date.now();se.durationMs=Math.max(0,((cr=se.completedAt)!=null?cr:Date.now())-Ze)}_.toolCall=se,_.streaming=!1;let re=L.agentContext;(re||L.executionId)&&(_.agentMetadata=(Lr=_.agentMetadata)!=null?Lr:{executionId:(wr=re==null?void 0:re.executionId)!=null?wr:L.executionId,iteration:($r=re==null?void 0:re.iteration)!=null?$r:L.iteration}),u(_);let dt=G(L);dt&&h.byCall.delete(dt)}else if(ot==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let j=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,_=(pt=j!=null?j:L.toolId)!=null?pt:`local-${l()}`,se=fe(_),te=(Tr=se.toolCall)!=null?Tr:{id:_,status:"pending"};te.name=L.toolName,te.args=L.parameters,te.status="complete",te.chunks=(Fr=te.chunks)!=null?Fr:[],te.startedAt=(Zn=te.startedAt)!=null?Zn:He((yo=L.startedAt)!=null?yo:L.timestamp),te.completedAt=(bo=te.completedAt)!=null?bo:te.startedAt,se.toolCall=te,se.streaming=!1,se.agentMetadata={...se.agentMetadata,executionId:(sn=L.executionId)!=null?sn:(Un=se.agentMetadata)==null?void 0:Un.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},u(se)}else if(ot==="text_start"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let j=L.partId;if(j!==void 0&&C.current!==null&&j!==C.current){let _=m;_&&(_.streaming=!1,u(_),V=_,m=null,M=!0)}j!==void 0&&(C.current=j)}else if(ot==="text_end"){if((Lt=L.toolContext)!=null&&Lt.toolId)continue;let j=m;j&&(j.streaming=!1,u(j),V=j,m=null,M=!0)}else if(ot==="step_chunk"||ot==="step_delta"){let j=L.stepType,_=L.executionType;if(j==="tool"||_==="context")continue;let se=L.toolContext;if(se!=null&&se.toolId){let Ze=String((ur=(pr=L.id)!=null?pr:se.stepId)!=null?ur:`step-${l()}`),ft=L.partId!==void 0&&L.partId!==null?String(L.partId):"",je=`${se.toolId}::${Ze}`,st=v.get(je);if(ft!==""&&st!==void 0&&st!==""&&st!==ft){let $t=k.get(E(se.toolId,Ze,st));$t&&$t.streaming!==!1&&($t.streaming=!1,u($t))}ft!==""&&v.set(je,ft);let Vt=R(se.toolId,Ze,ft,se.executionId),Cr=(Wn=(Cn=(wo=(ln=L.text)!=null?ln:L.delta)!=null?wo:L.content)!=null?Cn:L.chunk)!=null?Wn:"";Cr&&(Vt.content+=String(Cr),Vt.streaming=!0,u(Vt)),L.isComplete&&(Vt.streaming=!1,u(Vt));continue}let te=L.partId;if(te!==void 0&&C.current!==null&&te!==C.current){let Ze=m;Ze&&(Ze.streaming=!1,u(Ze),V=Ze,m=null,M=!0)}te!==void 0&&(C.current=te);let re=te!==void 0&&(dn=Y.get(te))!=null?dn:Oe();te!==void 0&&(re.partId||(re.partId=te),Y.set(te,re));let dt=(Hn=(cn=(Se=(q=L.text)!=null?q:L.delta)!=null?Se:L.content)!=null?cn:L.chunk)!=null?Hn:"";if(dt){let Ze=typeof L.seq=="number"?L.seq:void 0,ft=te!=null?te:re.id,je=Ze!==void 0?Ce(ft,Ze,String(dt)):((zn=de.get(re.id))!=null?zn:"")+dt;re.rawContent=je,Q.has(re.id)||Q.set(re.id,this.createStreamParser());let st=Q.get(re.id),Vt=je.trim().startsWith("{")||je.trim().startsWith("[");if(Vt&&de.set(re.id,je),st.__isPlainTextParser===!0){re.content=Ze!==void 0?je:re.content+dt,de.delete(re.id),Q.delete(re.id),re.rawContent=void 0,u(re);continue}let $t=st.processChunk(je);if($t instanceof Promise)$t.then(zt=>{var Br;let vr=typeof zt=="string"?zt:(Br=zt==null?void 0:zt.text)!=null?Br:null;if(vr!==null&&vr.trim()!=="")re.content=vr,u(re);else if(!Vt&&!je.trim().startsWith("<")){let zr=m,fr=zr&&zr.id===re.id?zr:re;fr.id===re.id&&(fr.content=Ze!==void 0?je:fr.content+dt,de.delete(fr.id),Q.delete(fr.id),fr.rawContent=void 0,u(fr))}}).catch(()=>{re.content=Ze!==void 0?je:re.content+dt,de.delete(re.id),Q.delete(re.id),re.rawContent=void 0,u(re)});else{let zt=typeof $t=="string"?$t:(Ja=$t==null?void 0:$t.text)!=null?Ja:null;zt!==null&&zt.trim()!==""?(re.content=zt,u(re)):!Vt&&!je.trim().startsWith("<")&&(re.content=Ze!==void 0?je:re.content+dt,de.delete(re.id),Q.delete(re.id),re.rawContent=void 0,u(re))}}if(L.isComplete){let Ze=(Dn=(Bn=L.result)==null?void 0:Bn.response)!=null?Dn:re.content;if(Ze){let ft=de.get(re.id),je=ft!=null?ft:rt(Ze);re.rawContent=je;let st=Q.get(re.id),Vt=null,Cr=!1;if(st&&(Vt=st.getExtractedText(),Vt===null&&(Vt=oa(je)),Vt===null)){let $t=st.processChunk(je);$t instanceof Promise?(Cr=!0,$t.then(zt=>{var Br;let vr=typeof zt=="string"?zt:(Br=zt==null?void 0:zt.text)!=null?Br:null;if(vr!==null){let zr=m;zr&&zr.id===re.id&&(zr.content=vr,zr.streaming=!1,Q.delete(zr.id),de.delete(zr.id),u(zr))}})):Vt=typeof $t=="string"?$t:(On=$t==null?void 0:$t.text)!=null?On:null}if(!Cr){Vt!==null&&Vt.trim()!==""?re.content=Vt:de.has(re.id)||(re.content=rt(Ze));let $t=Q.get(re.id);if($t){let zt=(eo=$t.close)==null?void 0:eo.call($t);zt instanceof Promise&&zt.catch(()=>{}),Q.delete(re.id)}de.delete(re.id),re.streaming=!1,u(re)}}}}else if(ot==="step_complete"){let j=L.stepType,_=L.executionType;if(j==="tool"||_==="context")continue;let se=L.toolContext;if(se!=null&&se.toolId){let Ze=String((ri=($o=L.id)!=null?$o:se.stepId)!=null?ri:"");if(Ze){let ft=W(se.toolId,Ze);for(let[je,st]of k)je.startsWith(ft)&&st.streaming!==!1&&(st.streaming=!1,u(st));v.delete(`${se.toolId}::${Ze}`)}continue}let te=L.stopReason;if(M){if(m!==null){let je=m;te&&(je.stopReason=te),Q.delete(je.id),de.delete(je.id),je.streaming!==!1&&(je.streaming=!1,u(je))}let Ze=(Xa=L.result)==null?void 0:Xa.response,ft=V;ft&&(te&&(ft.stopReason=te),Ze!=null?Be(ft,Ze):(Q.delete(ft.id),de.delete(ft.id))),V=null;continue}let re=(ni=L.result)==null?void 0:ni.response,dt=Oe();if(te&&(dt.stopReason=te),re!=null){let Ze=Q.get(dt.id),ft=!1,je=!1;if(Ze){let st=Ze.getExtractedText(),Vt=de.get(dt.id),Cr=Vt!=null?Vt:rt(re);if(dt.rawContent=Cr,st!==null&&st.trim()!=="")dt.content=st,ft=!0;else{let $t=oa(Cr);if($t!==null)dt.content=$t,ft=!0;else{let zt=Ze.processChunk(Cr);if(zt instanceof Promise)je=!0,zt.then(vr=>{var zr;let Br=typeof vr=="string"?vr:(zr=vr==null?void 0:vr.text)!=null?zr:null;if(Br!==null&&Br.trim()!==""){let fr=m;fr&&fr.id===dt.id&&(fr.content=Br,fr.streaming=!1,Q.delete(fr.id),de.delete(fr.id),u(fr))}else{let fr=Ze.getExtractedText(),An=m;An&&An.id===dt.id&&(fr!==null&&fr.trim()!==""?An.content=fr:de.has(An.id)||(An.content=rt(re)),An.streaming=!1,Q.delete(An.id),de.delete(An.id),u(An))}});else{let vr=typeof zt=="string"?zt:(ha=zt==null?void 0:zt.text)!=null?ha:null;if(vr!==null&&vr.trim()!=="")dt.content=vr,ft=!0;else{let Br=Ze.getExtractedText();Br!==null&&Br.trim()!==""&&(dt.content=Br,ft=!0)}}}}}if(!je){if(!dt.rawContent){let st=de.get(dt.id);dt.rawContent=st!=null?st:rt(re)}if(!ft&&!de.has(dt.id)&&(dt.content=rt(re)),Ze){let st=(kt=Ze.close)==null?void 0:kt.call(Ze);st instanceof Promise&&st.catch(()=>{})}Q.delete(dt.id),de.delete(dt.id),dt.streaming=!1,u(dt)}}else Q.delete(dt.id),de.delete(dt.id),dt.streaming=!1,u(dt)}else if(ot==="flow_complete"){let j=(Ya=L.result)==null?void 0:Ya.response;if(M){if(m!==null){let _=m;Q.delete(_.id),de.delete(_.id),_.streaming!==!1&&(_.streaming=!1,u(_))}}else if(j!=null){let _=Oe(),se=de.get(_.id),te=se!=null?se:rt(j);_.rawContent=te;let re=rt(j),dt=Q.get(_.id);if(dt){let je=oa(te);if(je!==null)re=je;else{let st=dt.processChunk(te);st instanceof Promise&&st.then(Cr=>{var zt;let $t=typeof Cr=="string"?Cr:(zt=Cr==null?void 0:Cr.text)!=null?zt:null;$t!==null&&(_.content=$t,_.streaming=!1,u(_))});let Vt=dt.getExtractedText();Vt!==null&&(re=Vt)}}Q.delete(_.id),de.delete(_.id);let Ze=re!==_.content,ft=_.streaming!==!1;Ze&&(_.content=re),_.streaming=!1,(Ze||ft)&&u(_)}else if(m!==null){let _=m;Q.delete(_.id),de.delete(_.id),_.streaming!==!1&&(_.streaming=!1,u(_))}r({type:"status",status:"idle"})}else if(ot==="agent_start")ae={executionId:L.executionId,agentId:(vn=L.agentId)!=null?vn:"virtual",agentName:(en=L.agentName)!=null?en:"",status:"running",currentIteration:0,maxTurns:(oi=L.maxTurns)!=null?oi:1,startedAt:He(L.startedAt)};else if(ot==="agent_iteration_start"){if(ae&&(ae.currentIteration=L.iteration),he==="separate"&&L.iteration>1){let j=m;j&&(j.streaming=!1,u(j),ze.set(L.iteration-1,j),m=null)}}else if(ot==="agent_turn_start")f=null;else if(ot==="agent_turn_delta"){if(L.contentType==="text"){let j=Oe();j.content+=(ai=L.delta)!=null?ai:"",j.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:ae==null?void 0:ae.agentName},f=j,u(j)}else if(L.contentType==="thinking"){let j=(xa=L.turnId)!=null?xa:`agent-think-${L.iteration}`,_=xe(j);_.reasoning=(to=_.reasoning)!=null?to:{id:j,status:"streaming",chunks:[]},_.reasoning.chunks.push((si=L.delta)!=null?si:""),_.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(_)}else if(L.contentType==="tool_input"){let j=(Fo=L.toolCallId)!=null?Fo:h.lastId;if(j){let _=A.get(j);_!=null&&_.toolCall&&(_.toolCall.chunks=(Qa=_.toolCall.chunks)!=null?Qa:[],_.toolCall.chunks.push((ro=L.delta)!=null?ro:""),u(_))}}}else if(ot==="agent_turn_complete"){let j=L.turnId;if(j){let te=T.get(j);if(te!=null&&te.reasoning){te.reasoning.status="complete",te.reasoning.completedAt=He(L.completedAt);let re=(Za=te.reasoning.startedAt)!=null?Za:Date.now();te.reasoning.durationMs=Math.max(0,((Co=te.reasoning.completedAt)!=null?Co:Date.now())-re),te.streaming=!1,u(te)}}let _=L.stopReason,se=m!=null?m:f;if(_&&se!==null){let te=L.turnId;(!te||((vo=se.agentMetadata)==null?void 0:vo.turnId)===te)&&(se.stopReason=_,u(se))}}else if(ot==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let j=(ii=L.toolCallId)!=null?ii:`agent-tool-${l()}`;Ie(G(L),j);let _=fe(j),se=(li=_.toolCall)!=null?li:{id:j,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=(sd=L.toolName)!=null?sd:L.name)!=null?Uo:se.name,se.status="running",L.parameters!==void 0&&(se.args=L.parameters),se.startedAt=He((Ao=L.startedAt)!=null?Ao:L.timestamp),_.toolCall=se,_.streaming=!0,_.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(_)}else if(ot==="agent_tool_delta"){let j=(di=L.toolCallId)!=null?di:h.lastId;if(j){let _=(es=A.get(j))!=null?es:fe(j);_.toolCall&&(_.toolCall.chunks=(So=_.toolCall.chunks)!=null?So:[],_.toolCall.chunks.push((ci=L.delta)!=null?ci:""),_.toolCall.status="running",_.streaming=!0,u(_))}}else if(ot==="agent_tool_complete"){let j=(ts=L.toolCallId)!=null?ts:h.lastId;if(j){let _=(To=A.get(j))!=null?To:fe(j);if(_.toolCall){_.toolCall.status="complete",L.result!==void 0&&(_.toolCall.result=L.result),typeof L.executionTime=="number"&&(_.toolCall.durationMs=L.executionTime),_.toolCall.completedAt=He((rs=L.completedAt)!=null?rs:L.timestamp),_.streaming=!1,u(_);let se=G(L);se&&h.byCall.delete(se)}}}else if(ot==="agent_media"){let j=Array.isArray(L.media)?L.media:[],_=[];for(let se of j){if(!se||typeof se!="object")continue;let te=se,re=typeof te.type=="string"?te.type:void 0,dt=typeof te.mediaType=="string"?te.mediaType.toLowerCase():"",Ze=null,ft="";if(re==="media"){let je=typeof te.data=="string"?te.data:void 0;if(!je)continue;ft=dt.length>0?dt:"application/octet-stream",Ze=`data:${ft};base64,${je}`}else if(re==="image-url"){let je=typeof te.url=="string"?te.url:void 0;if(!je)continue;ft=dt,Ze=je}else if(re==="file-url"){let je=typeof te.url=="string"?te.url:void 0;if(!je)continue;ft=dt,Ze=je}else continue;if(Ze)if(re==="image-url"||ft.startsWith("image/"))_.push({type:"image",image:Ze,...ft?{mimeType:ft}:{}});else if(ft.startsWith("audio/"))_.push({type:"audio",audio:Ze,mimeType:ft});else if(ft.startsWith("video/"))_.push({type:"video",video:Ze,mimeType:ft});else{let je=ft||"application/octet-stream";_.push({type:"file",data:Ze,mimeType:je,filename:bw(je)})}}if(_.length>0){let se=l(),te=L.toolCallId,dt={id:`agent-media-${typeof te=="string"&&te.length>0?`${te}-${se}`:String(se)}`,role:"assistant",content:"",contentParts:_,createdAt:new Date().toISOString(),streaming:!1,sequence:se,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(dt);let Ze=m;Ze&&(Ze.streaming=!1,u(Ze)),m=null,x.current=null}}else if(ot!=="agent_iteration_complete"){if(ot==="agent_reflection"||ot==="agent_reflect"){let j=`agent-reflection-${L.executionId}-${L.iteration}`,_={id:j,role:"assistant",content:(pi=L.reflection)!=null?pi:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(no=L.reflection)!=null?no:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(_)}else if(ot==="agent_complete"){ae&&(ae.status=L.success?"complete":"error",ae.completedAt=He(L.completedAt),ae.stopReason=L.stopReason);let j=m;j&&(j.streaming=!1,u(j)),r({type:"status",status:"idle"})}else if(ot==="agent_error"){let j=typeof L.error=="string"?L.error:(Mo=(ui=L.error)==null?void 0:ui.message)!=null?Mo:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):r({type:"error",error:new Error(j)})}else if(ot!=="agent_ping"){if(ot==="agent_approval_start"){let j=(Kt=L.approvalId)!=null?Kt:`approval-${l()}`,_={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(ya=ae==null?void 0:ae.agentId)!=null?ya:"virtual",executionId:(ns=(ba=L.executionId)!=null?ba:ae==null?void 0:ae.executionId)!=null?ns:"",toolName:(qn=L.toolName)!=null?qn:"",toolType:L.toolType,description:(os=L.description)!=null?os:`Execute ${(fi=L.toolName)!=null?fi:"tool"}`,parameters:L.parameters}};u(_)}else if(ot==="step_await"&&L.awaitReason==="approval_required"){let j=(as=L.approvalId)!=null?as:`approval-${l()}`,_={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(mi=ae==null?void 0:ae.agentId)!=null?mi:"virtual",executionId:(Ca=(wa=L.executionId)!=null?wa:ae==null?void 0:ae.executionId)!=null?Ca:"",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(_)}else if(ot==="agent_approval_complete"){let j=L.approvalId;if(j){let se={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(ss=L.decision)!=null?ss:"approved",agentId:(is=ae==null?void 0:ae.agentId)!=null?is:"virtual",executionId:(ds=(ls=L.executionId)!=null?ls:ae==null?void 0:ae.executionId)!=null?ds:"",toolName:(Ur=L.toolName)!=null?Ur:"",description:(pn=L.description)!=null?pn:"",resolvedAt:Date.now()}};u(se)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=L.artifactType,_=String(L.id),se=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:_,artifactType:j,title:se,component:typeof L.component=="string"?L.component:void 0}),K.set(_,{markdown:"",title:se}),!Te.has(_)){Te.add(_);let te={id:`artifact-ref-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:_,title:se,artifactType:j,status:"streaming"}})};X.set(_,te),u(te)}}else if(ot==="artifact_delta"){let j=String(L.id),_=typeof L.delta=="string"?L.delta:String((oo=L.delta)!=null?oo:"");r({type:"artifact_delta",id:j,artDelta:_});let se=K.get(j);se&&(se.markdown+=_)}else if(ot==="artifact_update"){let j=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:j,component:typeof L.component=="string"?L.component:void 0})}else if(ot==="artifact_complete"){let j=String(L.id);r({type:"artifact_complete",id:j});let _=X.get(j);if(_){_.streaming=!1;try{let se=JSON.parse((bt=_.rawContent)!=null?bt:"{}");if(se.props){se.props.status="complete";let te=K.get(j);te!=null&&te.markdown&&(se.props.markdown=te.markdown)}_.rawContent=JSON.stringify(se)}catch{}K.delete(j),u(_),X.delete(j)}}}else if(ot==="transcript_insert"){let j=L.message;if(!j||typeof j!="object")continue;let _=String((cs=j.id)!=null?cs:`msg-${l()}`),se=j.role,re={id:_,role:se==="user"?"user":se==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(u(re),re.rawContent)try{let dt=JSON.parse(re.rawContent),Ze=(qo=dt==null?void 0:dt.props)==null?void 0:qo.artifactId;typeof Ze=="string"&&Te.add(Ze)}catch{}m=null,x.current=null,Q.delete(_),de.delete(_)}else if(ot==="error"||ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(L.error instanceof Error)j=L.error;else if(ot==="dispatch_error"){let _=(_n=L.message)!=null?_n:L.error;_!=null&&_!==""&&(j=new Error(String(_)))}else if(ot==="step_error"||ot==="flow_error"){let _=L.error;typeof _=="string"&&_!==""?j=new Error(_):_!=null&&typeof _=="object"&&"message"in _&&(j=new Error(String((xi=_.message)!=null?xi:_)))}else ot==="error"&&L.error!=null&&L.error!==""&&(j=new Error(String(L.error)));if(j){r({type:"error",error:j});let _=m;_&&_.streaming&&(_.streaming=!1,u(_)),r({type:"status",status:"idle"})}}}}}oe.length=0};;){let{done:O,value:me}=await o.read();if(O)break;s+=a.decode(me,{stream:!0});let qe=s.split(`
|
|
56
|
+
${e.description}`:"");return window.confirm(r)},xw=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)}},yw=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},bw=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)}},Sw=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`},$h=e=>e.status==="complete"?Sw(e):e.status==="pending"?"Waiting":"",Tw=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 Fh=e=>e.status==="complete"?Tw(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})},Mw=()=>{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,`
|
|
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=Mw();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:()=>{}}},Uh=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 kw="https://api.runtype.com/v1/dispatch",tl="https://api.runtype.com";function Ew(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 Lw(e){switch(e){case"json":return Qi;case"regex-json":return Yi;case"xml":return Zi;default:return Xi}}var zh=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Pw(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=zh(r);if(!zh(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;var r,n,o,s;this.apiUrl=(r=t.apiUrl)!=null?r:kw,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(n=t.streamParser)!=null?n:Lw(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,(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}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.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Fd).map(f=>{var y,C,k;return{id:f.id,role:f.role,content:(k=(C=(y=f.contentParts)!=null?y:f.llmContent)!=null?C:f.rawContent)!=null?k:f.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},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!m.ok){let f=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(m.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let y=new Error(f.error||"Failed to send message");throw r({type:"error",error:y}),y}if(!m.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}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)})},m=null,f=null,y={current:null},C={current:null},k=!1,T=new Map,S=new Map,M=new Map,v=new Map,b={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},E=(I,te,qe="")=>`${I}::${te}::${qe}`,B=(I,te)=>`${I}::${te}::`,H=(I,te,qe,tt)=>{let Xe=E(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(m)return m;let I;return!ve&&se?(I=se,ve=!0):se&&C.current?I=`${se}_${C.current}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:I,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},je=(I,te)=>{b.lastId=te,I&&b.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=b.byStep.get(tt);if(pt)return b.lastId=pt,pt}if(b.lastId&&!te)return b.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)=>{x.lastId=te,I&&x.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=x.byCall.get(tt);if(pt)return x.lastId=pt,pt}if(x.lastId&&!te)return x.lastId;if(!te)return null;let Xe=`tool-${l()}`;return We(tt,Xe),Xe},he=I=>{let te=S.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 S.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=Pw(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,Ae,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,An,tn,li,di,bs,no,ci,Uo,ta,oo,ra,Ao,So,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,As,qo,bi,wi,da,ca,pa,ua,jr,un,ao,yt,fa,jo,_n;for(let Ss=0;Ss<Me.length;Ss++){let ot=Me[Ss].payloadType,L=Me[Ss].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=(Ae=we(L,!1))!=null?Ae: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&&b.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&&x.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&&C.current!==null&&z!==C.current){let O=m;O&&(O.streaming=!1,u(O),pe=O,m=null,k=!0)}z!==void 0&&(C.current=z)}else if(ot==="text_end"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let z=m;z&&(z.streaming=!1,u(z),pe=z,m=null,k=!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=v.get(it);if(wt!==""&<!==void 0&<!==""&<!==wt){let Nt=M.get(E(ie.toolId,et,lt));Nt&&Nt.streaming!==!1&&(Nt.streaming=!1,u(Nt))}wt!==""&&v.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&&C.current!==null&&de!==C.current){let et=m;et&&(et.streaming=!1,u(et),pe=et,m=null,k=!0)}de!==void 0&&(C.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=m,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=m;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)&<.streaming!==!1&&(lt.streaming=!1,u(lt));v.delete(`${ie.toolId}::${et}`)}continue}let de=L.stopReason;if(k){if(m!==null){let it=m;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&<.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=m;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(),Sn=m;Sn&&Sn.id===st.id&&(vr!==null&&vr.trim()!==""?Sn.content=vr:ee.has(Sn.id)||(Sn.content=Ve(re)),Sn.streaming=!1,G.delete(Sn.id),ee.delete(Sn.id),u(Sn))}});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&<.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(k){if(m!==null){let O=m;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&<.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(m!==null){let O=m;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:(An=L.agentName)!=null?An:"",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=m;z&&(z.streaming=!1,u(z),Q.set(L.iteration-1,z),m=null)}}else if(ot==="agent_turn_start")f=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},f=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:x.lastId;if(z){let O=S.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=m!=null?m:f;if(O&&ie!==null){let de=L.turnId;(!de||((Ao=ie.agentMetadata)==null?void 0:Ao.turnId)===de)&&(ie.stopReason=O,u(ie))}}else if(ot==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let z=(So=L.toolCallId)!=null?So:`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:x.lastId;if(z){let O=(fi=S.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:x.lastId;if(z){let O=(oa=S.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&&x.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:Ew(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=m;et&&(et.streaming=!1,u(et)),m=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=m;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:(As=L.toolName)!=null?As:"",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{}m=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=m;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(`
|
|
60
60
|
|
|
61
|
-
`);
|
|
62
|
-
`),mt="message",ct="";for(let N of Xe)N.startsWith("event:")?mt=N.replace("event:","").trim():N.startsWith("data:")&&(ct+=N.replace("data:","").trim());if(!ct)continue;let yt;try{yt=JSON.parse(ct)}catch(N){r({type:"error",error:N instanceof Error?N:new Error("Failed to parse chat stream payload")});continue}let jt=mt!=="message"?mt:(ue=yt.type)!=null?ue:"message";if((Z=this.onSSEEvent)==null||Z.call(this,jt,yt),this.parseSSEEvent){x.current=m;let N=await this.handleCustomSSEEvent(yt,r,x,u,l,C);if(x.current&&x.current!==m&&(m=x.current),N)continue}U.push(jt,yt),we()}}U.flushPending(),we(),U.destroy()}};function _h(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ra(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Zi="[Image]";function Nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function $h(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Uh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Rs(e){return{type:"text",text:e}}function zh(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 jh(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 Vh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vw=["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"],uo=[...Vh,...vw];function Aw(e){return Vh.includes(e)||e.startsWith("image/")}function el(e){return Aw(e.type)}async function Gh(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;el(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 Kh(e,t=uo,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 Sw(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Jh(e,t){let r=Sw(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 tl=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),a=n.createBuffer(1,o.length,this.sampleRate);a.getChannelData(0).set(o);let s=n.createBufferSource();s.buffer=a,s.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=a.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,s.onended=()=>{let d=this.activeSources.indexOf(s);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 a=0;a<r;a++){let s=o.getInt16(a*2,!0);n[a]=s/32768}return n}};var rl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,r,n,o,a){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 s=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(s);let i=0;for(let p=0;p<s.length;p++)i+=s[p]*s[p];let d=Math.sqrt(i/s.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,a()):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(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 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(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 a=o.location.protocol==="https:"?"wss:":"ws:",s=(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(!s)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${a}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${a}//${s}/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((m,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let x=!1,C=T=>{x||(x=!0,clearTimeout(M),f(new Error(T)))},M=setTimeout(()=>C("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(M),m())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!x){let A=T.code!==1006?` (code ${T.code})`:"";C("WebSocket connection failed"+A+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("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(a=>a(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 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(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 a=this.w;this.audioContext||(this.audioContext=new(a.AudioContext||a.webkitAudioContext));let s=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(s,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(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());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(a){throw this.errorCallbacks.forEach(s=>s(a)),this.statusCallbacks.forEach(s=>s("error")),a}}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 a,s;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=(s=(a=this.config)==null?void 0:a.silenceThreshold)!=null?s:.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),a=this.generateRequestId();this.currentRequestId=a,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:a}))}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 s=o.result.split(",")[1];r(s)},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",a=o==="mp3"?"audio/mpeg":`audio/${o}`,s=new Blob([n],{type:a}),i=URL.createObjectURL(s),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 ia=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 a=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(a=>a(new Error(o.error))),this.statusCallbacks.forEach(a=>a("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 la(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ws(e.runtype);case"browser":if(!ia.isSupported())throw new Error("Browser speech recognition not supported");return new ia(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function nl(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return la({type:"runtype",runtype:e.runtype});if(ia.isSupported())return la({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Hs(e){try{return nl(e),!0}catch{return!1}}function Xh(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=(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=m;let or=await this.handleCustomSSEEvent(ht,r,y,u,l,C);if(y.current&&y.current!==m&&(m=y.current),or)continue}ne.push(zt,ht),J()}}ne.flushPending(),J(),ne.destroy()}};function qh(){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 jh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Vh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Gh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Kh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ba(e){return{type:"text",text:e}}function Jh(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 Xh(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 Yh(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 Qh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Iw=["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=[...Qh,...Iw];function Rw(e){return Qh.includes(e)||e.startsWith("image/")}function nl(e){return Rw(e.type)}async function Zh(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 ex(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 Ww(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function tx(e,t){let r=Ww(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((m,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let y=!1,C=T=>{y||(y=!0,clearTimeout(k),f(new Error(T)))},k=setTimeout(()=>C("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(k),m())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!y){let S=T.code!==1006?` (code ${T.code})`:"";C("WebSocket connection failed"+S+"."+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(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());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 rx(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}
|
|
63
63
|
|
|
64
|
-
_Details: ${r.message}_`:n}var Wa=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,a,s,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)&&Ls(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:(a=t.message.agentMetadata.iteration)!=null?a: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;((s=this.agentExecution)==null?void 0:s.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(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new aa(t),this.wireDefaultWebMcpConfirm();for(let a of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(a.id,{...a,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 Hs((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 a=t||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=la(a);let s=(r=this.config.voiceRecognition)!=null?r:{},i=(n=s.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=s.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,m,f,x,C;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&&((m=l.text)!=null&&m.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 M=(C=this.pendingVoiceAssistantMessageId)!=null?C:(x=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:x.id;M&&this.ttsSpokenMessageIds.add(M)}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(a){console.error("Failed to setup voice:",a)}}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,a,s,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:(a=t.runtype)==null?void 0:a.host,voiceId:(s=t.runtype)==null?void 0:s.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 aa(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:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:s!=null?s: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},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}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:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:m,rawContent:f}=n,C={id:d!=null?d:o==="user"?Ra():o==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:n={},text:o="",llmContent:a,id:s,createdAt:i,sequence:d}=t,l={text:o,component:r,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,r){var l,p,u,m,f;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=Ra(),a=sa(),s={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(s),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:a},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let M=Xh(x,this.config.errorMessage);if(M){let T={id:a,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,x):(f=(m=this.callbacks).onError)==null||f.call(m,new Error(String(x))))}}async continueConversation(){var o,a,s,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=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: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=Xh(l,this.config.errorMessage);if(u){let m={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,r){var o,a,s;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),(s=(a=this.callbacks).onError)==null||s.call(a,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,a,s;try{if(((a=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:a.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:(s=t.description)!=null?s:`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(a=>a.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()},a={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(a),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let s=this.config.approval,i=s&&typeof s=="object"?s.onDecision:void 0;try{let m;if(i?m=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):m=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),m){let f=null;if(m instanceof Response){if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((l=x==null?void 0:x.error)!=null?l:`Approval request failed: ${m.status}`)}f=m.body}else m instanceof ReadableStream&&(f=m);f?await this.connectStream(f,{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(m){let f=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||(u=(p=this.callbacks).onError)==null||u.call(p,m instanceof Error?m:new Error(String(m)))}}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,m,f,x,C,M,T,A,k,v,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,a=(m=t.toolCall)==null?void 0:m.name;if(!o||!a){(x=(f=this.callbacks).onError)==null||x.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let h=(C=t.toolCall)==null?void 0:C.args,E=Array.isArray(h==null?void 0:h.questions)?h.questions:[];if(E.length===1){let W=typeof((M=E[0])==null?void 0:M.question)=="string"?E[0].question:"";W&&(s={[W]:r})}}this.markAskUserQuestionResolved(t,s),(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(([E,W])=>`${E}: ${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=s!=null?s:{};l.forEach((E,W)=>{let R=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!R)return;let I=h[R],H=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";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:H||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let h=await this.client.resumeFlow(o,{[a]:r});if(!h.ok){let E=await h.json().catch(()=>null);throw new Error((k=E==null?void 0:E.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 E=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(w=(v=this.callbacks).onError)==null||w.call(v,h instanceof Error?h:new Error(String(h)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,n=(s=t.toolCall)==null?void 0:s.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=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async p=>{var A,k,v,w,h,E,W;let u=(A=p.toolCall)==null?void 0:A.name,m=(k=p.toolCall)==null?void 0:k.id;if(!u||!m)return null;let f=`${t}:${m}`;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 x=new AbortController;this.webMcpResolveControllers.add(x),o.push(x);let C=(w=(v=p.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?w:u,M=this.client.executeWebMcpToolCall(u,(h=p.toolCall)==null?void 0:h.args,x.signal),T;if(!M)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await M}catch(R){return R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"))||(W=(E=this.callbacks).onError)==null||W.call(E,R instanceof Error?R:new Error(String(R))),this.webMcpInflightKeys.delete(f),null}return x.signal.aborted?(this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:C,output:T}}));try{let p=s.filter(f=>f!==null);if(p.length===0)return;let u={};for(let f of p)u[f.resumeKey]=f.output;let m=await this.client.resumeFlow(t,u,{signal:a.signal});if(!m.ok){let f=await m.json().catch(()=>null);throw new Error((i=f==null?void 0:f.error)!=null?i:`Resume failed: ${m.status}`)}for(let f of p)this.webMcpResolvedKeys.add(f.dedupeKey);m.body&&await this.connectStream(m.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(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,u,m,f,x,C,M,T,A,k,v,w;let r=(p=t.agentMetadata)==null?void 0:p.executionId,n=(u=t.toolCall)==null?void 0:u.name,o=(m=t.toolCall)==null?void 0:m.id;if(!r){(x=(f=this.callbacks).onError)==null||x.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(E){(M=(C=this.callbacks).onError)==null||M.call(C,E instanceof Error?E:new Error(String(E)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${r}:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let s=new AbortController;this.webMcpResolveControllers.add(s);let{signal:i}=s;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 E=(k=(A=t.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?k:n;await this.resumeWithToolOutput(r,E,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a)},signal:i})}catch(h){h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))||(w=(v=this.callbacks).onError)==null||w.call(v,h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,n,o){var s,i;let a=await this.client.resumeFlow(t,{[r]:n},{signal:o==null?void 0:o.signal});if(!a.ok){let d=await a.json().catch(()=>null);throw new Error((s=d==null?void 0:d.error)!=null?s:`Resume failed: ${a.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),a.body?await this.connectStream(a.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.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 a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}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(a=>a.role==="assistant"&&a.content&&!a.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),a=n.getVoices();if(r.voice){let s=a.find(i=>i.name===r.voice);s&&(o.voice=s)}else a.length>0&&(o.voice=r.pickVoice?r.pickVoice(a):e.pickBestVoice(a));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 a=t.find(s=>s.name===o);if(a)return a}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,a)=>{var p,u,m,f,x,C;if(a!==n)return o;let s={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.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=(m=r.agentMetadata)==null?void 0:m.executionId,l=(f=r.toolCall)==null?void 0:f.id;if(i&&Ls(i)&&d&&l&&((x=r.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(s.agentMetadata={...(C=s.agentMetadata)!=null?C:{},awaitingLocalTool:!1})}return s}),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(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(a)&&o!==a)return o-a;let s=(d=r.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return s!==i?s-i:r.id.localeCompare(n.id)})}};var y=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Xn=(e,t,r)=>{let n=e.createElement(t);return r&&(n.className=r),n};var _d=[["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 Nd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var $d=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Fd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Ud=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var zd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var qd=[["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 Vd=[["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 Gd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var Kd=[["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 Jd=[["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 Xd=[["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 Yd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Qd=[["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 Zd=[["path",{d:"M20 6 9 17l-5-5"}]];var ec=[["path",{d:"m6 9 6 6 6-6"}]];var tc=[["path",{d:"m15 18-6-6 6-6"}]];var rc=[["path",{d:"m9 18 6-6-6-6"}]];var nc=[["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 oc=[["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 ac=[["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 sc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var ic=[["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 lc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["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 mc=[["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 gc=[["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 hc=[["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 xc=[["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 yc=[["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 bc=[["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 wc=[["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 Cc=[["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 vc=[["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 Ac=[["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 Sc=[["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 Tc=[["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 Mc=[["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 kc=[["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 Ec=[["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 Lc=[["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 Pc=[["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 Ic=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Rc=[["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 Wc=[["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 Hc=[["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 Bc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Dc=[["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 Oc=[["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 _c=[["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 Nc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var $c=[["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 Fc=[["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 Uc=[["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 zc=[["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 qc=[["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 Vc=[["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 Gc=[["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 Kc=[["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 Jc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Xc=[["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 Yc=[["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 Qc=[["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 Zc=[["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 ep=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var tp=[["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 rp=[["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 np=[["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 op=[["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 ap=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var sp=[["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 ip=[["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 lp=[["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 dp=[["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 cp=[["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 pp=[["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 up=[["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 fp=[["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 mp=[["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 gp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var hp=[["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 xp=[["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 yp=[["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 bp=[["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 wp=[["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 Cp=[["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 vp=[["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 Ap=[["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 Sp=[["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 Tp=[["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 Mp=[["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 kp=[["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 Ep=[["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 Lp=[["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 Pp=[["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 Ip=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Rp=[["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 Tw={activity:_d,"arrow-down":Nd,"arrow-up":zd,"arrow-up-right":Ud,bot:Kd,"chevron-down":ec,"chevron-up":nc,"chevron-right":rc,"chevron-left":tc,check:Zd,clipboard:ac,"clipboard-copy":oc,copy:ic,file:xc,"file-code":mc,"file-spreadsheet":gc,"file-text":hc,"image-plus":Lc,loader:Hc,"loader-circle":cl,mic:Uc,paperclip:Kc,"refresh-cw":rp,search:ap,send:sp,"shield-alert":dp,"shield-check":cp,"shield-x":pl,square:gp,"thumbs-down":wp,"thumbs-up":Cp,upload:Mp,"volume-2":Ep,x:Ip,user:kp,mail:Dc,phone:Qc,calendar:Yd,clock:sc,building:Jd,"map-pin":Oc,lock:Bc,key:Rc,"credit-card":lc,"at-sign":qd,hash:Tc,globe:Sc,link:Wc,"circle-check":ol,"circle-x":al,"triangle-alert":fl,info:Ic,ban:jd,shield:pp,"arrow-left":$d,"arrow-right":Fd,"external-link":pc,ellipsis:il,"ellipsis-vertical":sl,menu:Nc,house:dl,plus:ep,minus:qc,pencil:Xc,trash:Sp,"trash-2":Ap,save:op,download:cc,share:lp,funnel:ll,settings:ip,"rotate-cw":np,maximize:_c,minimize:zc,"shopping-cart":fp,"shopping-bag":up,package:Gc,truck:Tp,tag:bp,gift:Ac,receipt:tp,wallet:Pp,store:xp,"dollar-sign":dc,percent:Yc,play:Zc,pause:Jc,"volume-x":Lp,camera:Qd,image:Pc,film:bc,headphones:Mc,"message-circle":$c,"message-square":Fc,bell:Vd,heart:kc,star:hp,eye:fc,"eye-off":uc,bookmark:Gd,"calendar-days":Xd,history:Ec,timer:vp,folder:vc,"folder-open":Cc,files:yc,sparkles:ul,zap:Rp,sun:yp,moon:Vc,flag:wc,monitor:jc,smartphone:mp},Pe=(e,t=24,r="currentColor",n=2)=>{let o=Tw[e];return o?Mw(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 Mw(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(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var ml={allowedTypes:uo,maxFileSize:10*1024*1024,maxFiles:4};function kw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ew(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 da=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:ml.allowedTypes,maxFileSize:(n=t.maxFileSize)!=null?n:ml.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ml.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:ml.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,a,s,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=Kh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,u);continue}try{let u=await Gh(l),m=el(l)?URL.createObjectURL(l):null,f={id:kw(),file:l,previewUrl:m,contentPart:u};this.attachments.push(f),this.renderPreview(f)}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 a,s,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=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,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=el(t.file),n=y("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 s=y("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",n.appendChild(s)}else{let s=y("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=Ew(t.file.type),d=Pe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=y("span");l.textContent=Jh(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",s.appendChild(l),n.appendChild(s)}let o=y("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 a=Pe("x",10,"var(--persona-text-inverse, #ffffff)",2);a?o.appendChild(a):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",s=>{s.preventDefault(),s.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 Yh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[n,o]of Object.entries(t)){let a=r[n];Yh(a)&&Yh(o)?r[n]=Bs(a,o):r[n]=o}return r}var xn="min(440px, calc(100vw - 24px))",gl="440px",Qt={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:xn,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 Qh(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function hl(e){var t,r,n,o,a,s,i,d,l,p,u,m,f,x,C,M,T,A,k,v,w;return e?{...Qt,...e,theme:Qh(Qt.theme,e.theme),darkTheme:Qh(Qt.darkTheme,e.darkTheme),launcher:{...Qt.launcher,...e.launcher,dock:{...(t=Qt.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(n=Qt.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Qt.copy,...e.copy},sendButton:{...Qt.sendButton,...e.sendButton},statusIndicator:{...Qt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Qt.voiceRecognition,...e.voiceRecognition},features:(()=>{var xe,Ie,Je,X,Te,K,ge,ce;let h=(xe=Qt.features)==null?void 0:xe.artifacts,E=(Ie=e.features)==null?void 0:Ie.artifacts,W=(Je=Qt.features)==null?void 0:Je.scrollToBottom,R=(X=e.features)==null?void 0:X.scrollToBottom,I=(Te=Qt.features)==null?void 0:Te.streamAnimation,H=(K=e.features)==null?void 0:K.streamAnimation,G=(ge=Qt.features)==null?void 0:ge.askUserQuestion,ie=(ce=e.features)==null?void 0:ce.askUserQuestion,ye=h===void 0&&E===void 0?void 0:{...h,...E,layout:{...h==null?void 0:h.layout,...E==null?void 0:E.layout}},Oe=W===void 0&&R===void 0?void 0:{...W,...R},et=I===void 0&&H===void 0?void 0:{...I,...H},be=G===void 0&&ie===void 0?void 0:{...G,...ie,styles:{...G==null?void 0:G.styles,...ie==null?void 0:ie.styles}};return{...Qt.features,...e.features,...Oe!==void 0?{scrollToBottom:Oe}:{},...ye!==void 0?{artifacts:ye}:{},...et!==void 0?{streamAnimation:et}:{},...be!==void 0?{askUserQuestion:be}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Qt.suggestionChips,suggestionChipsConfig:{...Qt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Qt.layout,...e.layout,header:{...(s=Qt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Qt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Qt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(m=e.layout)==null?void 0:m.messages)==null?void 0:f.avatar},timestamp:{...(C=(x=Qt.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(T=(M=e.layout)==null?void 0:M.messages)==null?void 0:T.timestamp}},slots:{...(A=Qt.layout)==null?void 0:A.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Qt.markdown,...e.markdown,options:{...(v=Qt.markdown)==null?void 0:v.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{...Qt.messageActions,...e.messageActions}}:Qt}var Wp={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"}},Hp={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"}},Bp={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:xn,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 Ha(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."))?Ha(e,n):n}function xl(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let i=`${o}.${a}`;if(typeof s=="string"){let d=Ha(e,s);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 s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Dp(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 Zh(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let a=r[n];a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?r[n]=Zh(a,o):r[n]=o}return r}function Lw(e,t){return t?Zh(e,t):e}function Ba(e,t={}){var o,a,s,i,d,l,p,u,m,f,x,C,M;let r={palette:Wp,semantic:Hp,components:Bp},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,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.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,...(m=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:m.interactive},feedback:{...r.semantic.colors.feedback,...(x=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:Lw(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=Dp(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 yl(e){var C,M,T,A,k,v,w,h,E,W,R,I,H,G,ie,ye,Oe,et,be,xe,Ie,Je,X,Te,K,ge,ce,fe,He,rt,Q,de,_e,Y,V,Ce,Be,oe,Ee,we,Dt,U,ae,ze,he,Re,ve,ue,Z,O,me,qe,$e,Xe,mt,ct,yt,jt,N,Me,ke,gt,tt,Ut,dr,Ot,It,lt,ht,ar,yn,Hr,Ln,Rt,bn,hr,Mr,Zr,Tt,Pn,an,kr,Er,Qn,In,wn,Et,Fe,P,ee,pe,Wt,Jt,Nt,cr,wr,$r,Lr,pt,Tr,Fr,yo,Zn,bo,Un,sn,Rn,Lt,pr,ur,ln,wo,Cn,Wn,dn,q;let t=xl(e),r={};for(let[Se,cn]of Object.entries(t)){let Hn=Se.replace(/\./g,"-");r[`--persona-${Hn}`]=cn.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(M=r["--persona-semantic-colors-secondary"])!=null?M: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"]=(k=r["--persona-semantic-colors-background"])!=null?k:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(v=r["--persona-semantic-colors-container"])!=null?v: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"]=(E=r["--persona-semantic-colors-text-inverse"])!=null?E: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"]=(I=r["--persona-components-voice-recording-indicator"])!=null?I:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(H=r["--persona-components-voice-recording-background"])!=null?H:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(G=r["--persona-components-voice-processing-icon"])!=null?G:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(ie=r["--persona-components-voice-speaking-icon"])!=null?ie:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(ye=r["--persona-components-approval-requested-background"])!=null?ye:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Oe=r["--persona-components-approval-requested-border"])!=null?Oe:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(et=r["--persona-components-approval-requested-text"])!=null?et:r["--persona-palette-colors-gray-900"],r["--persona-approval-approve-bg"]=(be=r["--persona-components-approval-approve-background"])!=null?be:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(xe=r["--persona-components-approval-deny-background"])!=null?xe:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(Ie=r["--persona-components-attachment-image-background"])!=null?Ie:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(Je=r["--persona-components-attachment-image-border"])!=null?Je: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"]=(Te=r["--persona-semantic-typography-fontSize"])!=null?Te: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"]=(ge=r["--persona-semantic-typography-lineHeight"])!=null?ge: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"]=(ce=r["--persona-palette-radius-sm"])!=null?ce:"0.125rem",r["--persona-radius-md"]=(fe=r["--persona-palette-radius-md"])!=null?fe:"0.375rem",r["--persona-radius-lg"]=(He=r["--persona-palette-radius-lg"])!=null?He:"0.5rem",r["--persona-radius-xl"]=(rt=r["--persona-palette-radius-xl"])!=null?rt:"0.75rem",r["--persona-radius-full"]=(Q=r["--persona-palette-radius-full"])!=null?Q:"9999px",r["--persona-launcher-radius"]=(_e=(de=r["--persona-components-launcher-borderRadius"])!=null?de:r["--persona-palette-radius-full"])!=null?_e:"9999px",r["--persona-launcher-bg"]=(Y=r["--persona-components-launcher-background"])!=null?Y:r["--persona-primary"],r["--persona-launcher-fg"]=(V=r["--persona-components-launcher-foreground"])!=null?V:r["--persona-text-inverse"],r["--persona-launcher-border"]=(Ce=r["--persona-components-launcher-border"])!=null?Ce:r["--persona-border"],r["--persona-button-primary-bg"]=(Be=r["--persona-components-button-primary-background"])!=null?Be:r["--persona-primary"],r["--persona-button-primary-fg"]=(oe=r["--persona-components-button-primary-foreground"])!=null?oe:r["--persona-text-inverse"],r["--persona-button-radius"]=(we=(Ee=r["--persona-components-button-primary-borderRadius"])!=null?Ee:r["--persona-palette-radius-full"])!=null?we:"9999px",r["--persona-panel-radius"]=(U=(Dt=r["--persona-components-panel-borderRadius"])!=null?Dt:r["--persona-radius-xl"])!=null?U:"0.75rem",r["--persona-panel-border"]=(ae=r["--persona-components-panel-border"])!=null?ae:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(he=(ze=r["--persona-components-panel-shadow"])!=null?ze:r["--persona-palette-shadows-xl"])!=null?he:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-input-radius"]=(ve=(Re=r["--persona-components-input-borderRadius"])!=null?Re:r["--persona-radius-lg"])!=null?ve:"0.5rem",r["--persona-message-user-radius"]=(Z=(ue=r["--persona-components-message-user-borderRadius"])!=null?ue:r["--persona-radius-lg"])!=null?Z:"0.5rem",r["--persona-message-assistant-radius"]=(me=(O=r["--persona-components-message-assistant-borderRadius"])!=null?O:r["--persona-radius-lg"])!=null?me:"0.5rem",r["--persona-header-bg"]=(qe=r["--persona-components-header-background"])!=null?qe:r["--persona-surface"],r["--persona-header-border"]=($e=r["--persona-components-header-border"])!=null?$e:r["--persona-divider"],r["--persona-header-icon-bg"]=(Xe=r["--persona-components-header-iconBackground"])!=null?Xe:r["--persona-primary"],r["--persona-header-icon-fg"]=(mt=r["--persona-components-header-iconForeground"])!=null?mt:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(ct=r["--persona-components-header-titleForeground"])!=null?ct:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(yt=r["--persona-components-header-subtitleForeground"])!=null?yt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(jt=r["--persona-components-header-actionIconForeground"])!=null?jt:r["--persona-muted"];let n=(N=e.components)==null?void 0:N.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(Me=e.components)==null?void 0:Me.introCard;r["--persona-intro-card-bg"]=(ke=r["--persona-components-introCard-background"])!=null?ke:r["--persona-surface"],r["--persona-intro-card-radius"]=(gt=r["--persona-components-introCard-borderRadius"])!=null?gt:"1rem",r["--persona-intro-card-padding"]=(tt=r["--persona-components-introCard-padding"])!=null?tt:"1.5rem",r["--persona-intro-card-shadow"]=(dr=(Ut=o==null?void 0:o.shadow)!=null?Ut:r["--persona-components-introCard-shadow"])!=null?dr:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Ot=r["--persona-components-input-background"])!=null?Ot:r["--persona-surface"],r["--persona-input-placeholder"]=(It=r["--persona-components-input-placeholder"])!=null?It:r["--persona-text-muted"],r["--persona-message-user-bg"]=(lt=r["--persona-components-message-user-background"])!=null?lt:r["--persona-accent"],r["--persona-message-user-text"]=(ht=r["--persona-components-message-user-text"])!=null?ht:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(ar=r["--persona-components-message-user-shadow"])!=null?ar:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(yn=r["--persona-components-message-assistant-background"])!=null?yn:r["--persona-surface"],r["--persona-message-assistant-text"]=(Hr=r["--persona-components-message-assistant-text"])!=null?Hr:r["--persona-text"],r["--persona-message-assistant-border"]=(Ln=r["--persona-components-message-assistant-border"])!=null?Ln:r["--persona-border"],r["--persona-message-assistant-shadow"]=(Rt=r["--persona-components-message-assistant-shadow"])!=null?Rt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(hr=(bn=r["--persona-components-scrollToBottom-background"])!=null?bn:r["--persona-button-primary-bg"])!=null?hr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Zr=(Mr=r["--persona-components-scrollToBottom-foreground"])!=null?Mr:r["--persona-button-primary-fg"])!=null?Zr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(Tt=r["--persona-components-scrollToBottom-border"])!=null?Tt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(Pn=r["--persona-components-scrollToBottom-size"])!=null?Pn:"40px",r["--persona-scroll-to-bottom-radius"]=(Er=(kr=(an=r["--persona-components-scrollToBottom-borderRadius"])!=null?an:r["--persona-button-radius"])!=null?kr:r["--persona-radius-full"])!=null?Er:"9999px",r["--persona-scroll-to-bottom-shadow"]=(In=(Qn=r["--persona-components-scrollToBottom-shadow"])!=null?Qn:r["--persona-palette-shadows-sm"])!=null?In:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(wn=r["--persona-components-scrollToBottom-padding"])!=null?wn:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(Et=r["--persona-components-scrollToBottom-gap"])!=null?Et:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(P=(Fe=r["--persona-components-scrollToBottom-fontSize"])!=null?Fe: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"]=(pe=r["--persona-components-toolBubble-shadow"])!=null?pe:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(Wt=r["--persona-components-reasoningBubble-shadow"])!=null?Wt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Jt=r["--persona-components-composer-shadow"])!=null?Jt:"none",r["--persona-md-inline-code-bg"]=(Nt=r["--persona-components-markdown-inlineCode-background"])!=null?Nt:r["--persona-container"],r["--persona-md-inline-code-color"]=(cr=r["--persona-components-markdown-inlineCode-foreground"])!=null?cr:r["--persona-text"],r["--persona-md-link-color"]=($r=(wr=r["--persona-components-markdown-link-foreground"])!=null?wr:r["--persona-accent"])!=null?$r:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);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"]=(Lr=r["--persona-components-markdown-codeBlock-background"])!=null?Lr:r["--persona-container"],r["--persona-md-code-block-border-color"]=(pt=r["--persona-components-markdown-codeBlock-borderColor"])!=null?pt:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Tr=r["--persona-components-markdown-codeBlock-textColor"])!=null?Tr:"inherit",r["--persona-md-table-header-bg"]=(Fr=r["--persona-components-markdown-table-headerBackground"])!=null?Fr:r["--persona-container"],r["--persona-md-table-border-color"]=(yo=r["--persona-components-markdown-table-borderColor"])!=null?yo:r["--persona-border"],r["--persona-md-hr-color"]=(Zn=r["--persona-components-markdown-hr-color"])!=null?Zn:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(bo=r["--persona-components-markdown-blockquote-borderColor"])!=null?bo:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(Un=r["--persona-components-markdown-blockquote-background"])!=null?Un:"transparent",r["--persona-md-blockquote-text-color"]=(sn=r["--persona-components-markdown-blockquote-textColor"])!=null?sn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(Rn=r["--persona-components-collapsibleWidget-container"])!=null?Rn:r["--persona-surface"],r["--cw-surface"]=(Lt=r["--persona-components-collapsibleWidget-surface"])!=null?Lt:r["--persona-surface"],r["--cw-border"]=(pr=r["--persona-components-collapsibleWidget-border"])!=null?pr:r["--persona-border"],r["--persona-message-border"]=(ur=r["--persona-components-message-border"])!=null?ur: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 m=p==null?void 0:p.labelButton;m&&(m.background&&(r["--persona-label-btn-bg"]=m.background),m.border&&(r["--persona-label-btn-border"]=m.border),m.color&&(r["--persona-label-btn-color"]=m.color),m.padding&&(r["--persona-label-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-label-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-label-btn-hover-bg"]=m.hoverBackground),m.fontSize&&(r["--persona-label-btn-font-size"]=m.fontSize),m.gap&&(r["--persona-label-btn-gap"]=m.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 x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let Se=x.toolbar;Se.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=Se.iconHoverColor),Se.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=Se.iconHoverBackground),Se.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=Se.iconPadding),Se.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=Se.iconBorderRadius),Se.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=Se.iconBorder),Se.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=Se.toggleGroupGap),Se.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=Se.toggleBorderRadius),Se.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=Se.copyBackground),Se.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=Se.copyBorder),Se.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=Se.copyColor),Se.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=Se.copyBorderRadius),Se.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=Se.copyPadding),Se.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=Se.copyMenuBackground,r["--persona-dropdown-bg"]=(ln=r["--persona-dropdown-bg"])!=null?ln:Se.copyMenuBackground),Se.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=Se.copyMenuBorder,r["--persona-dropdown-border"]=(wo=r["--persona-dropdown-border"])!=null?wo:Se.copyMenuBorder),Se.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=Se.copyMenuShadow,r["--persona-dropdown-shadow"]=(Cn=r["--persona-dropdown-shadow"])!=null?Cn:Se.copyMenuShadow),Se.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=Se.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Wn=r["--persona-dropdown-radius"])!=null?Wn:Se.copyMenuBorderRadius),Se.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Se.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(dn=r["--persona-dropdown-item-hover-bg"])!=null?dn:Se.copyMenuItemHoverBackground),Se.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=Se.iconBackground),Se.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=Se.toolbarBorder)}if(x!=null&&x.tab){let Se=x.tab;Se.background&&(r["--persona-artifact-tab-bg"]=Se.background),Se.activeBackground&&(r["--persona-artifact-tab-active-bg"]=Se.activeBackground),Se.activeBorder&&(r["--persona-artifact-tab-active-border"]=Se.activeBorder),Se.borderRadius&&(r["--persona-artifact-tab-radius"]=Se.borderRadius),Se.textColor&&(r["--persona-artifact-tab-color"]=Se.textColor),Se.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=Se.hoverBackground),Se.listBackground&&(r["--persona-artifact-tab-list-bg"]=Se.listBackground),Se.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=Se.listBorderColor),Se.listPadding&&(r["--persona-artifact-tab-list-padding"]=Se.listPadding)}if(x!=null&&x.pane){let Se=x.pane;if(Se.toolbarBackground){let cn=(q=Ha(e,Se.toolbarBackground))!=null?q:Se.toolbarBackground;r["--persona-artifact-toolbar-bg"]=cn}}return r}var ex={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 Pw={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"}}},tx=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ds=()=>{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"},Iw=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ds()},Op=e=>Iw(e),Rw=e=>Ba(e),Ww=e=>{var r;let t=Ba(void 0,{validate:!1});return Ba({...e,palette:{...t.palette,colors:{...Pw.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Da=e=>{let t=Op(e),r=tx(e==null?void 0:e.theme),n=tx(e==null?void 0:e.darkTheme);return t==="dark"?Ww(Bs(r!=null?r:{},n!=null?n:{})):Rw(r)},Hw=e=>yl(e),Po=(e,t)=>{var a;let r=Da(t),n=Hw(r);for(let[s,i]of Object.entries(n))e.style.setProperty(s,i);let o=(a=t==null?void 0:t.toolCall)==null?void 0:a.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},bl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ds())});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(Ds());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 rx=(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:m=>m.getAttribute("im-preserve")==="true",shouldReAppend:m=>m.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(m,f,x={}){m=p(m);let C=u(f),M=l(m,C,x),T=o(M,()=>i(M,m,C,A=>A.morphStyle==="innerHTML"?(a(A,m,C),Array.from(m.childNodes)):n(A,m,C)));return M.pantry.remove(),T}function n(m,f,x){let C=u(f);return a(m,C,x,f,f.nextSibling),Array.from(C.childNodes)}function o(m,f){var k;if(!m.config.restoreFocus)return f();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return f();let{id:C,selectionStart:M,selectionEnd:T}=x,A=f();return C&&C!==((k=document.activeElement)==null?void 0:k.getAttribute("id"))&&(x=m.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&T&&x.setSelectionRange(M,T),A}let a=(function(){function m(v,w,h,E=null,W=null){w instanceof HTMLTemplateElement&&h instanceof HTMLTemplateElement&&(w=w.content,h=h.content),E||(E=w.firstChild);for(let R of h.childNodes){if(E&&E!=W){let H=x(v,R,E,W);if(H){H!==E&&M(v,E,H),s(H,R,v),E=H.nextSibling;continue}}if(R instanceof Element){let H=R.getAttribute("id");if(v.persistentIds.has(H)){let G=T(w,H,E,v);s(G,R,v),E=G.nextSibling;continue}}let I=f(w,R,E,v);I&&(E=I.nextSibling)}for(;E&&E!=W;){let R=E;E=E.nextSibling,C(v,R)}}function f(v,w,h,E){if(E.callbacks.beforeNodeAdded(w)===!1)return null;if(E.idMap.has(w)){let W=document.createElement(w.tagName);return v.insertBefore(W,h),s(W,w,E),E.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(w,!0);return v.insertBefore(W,h),E.callbacks.afterNodeAdded(W),W}}let x=(function(){function v(E,W,R,I){let H=null,G=W.nextSibling,ie=0,ye=R;for(;ye&&ye!=I;){if(h(ye,W)){if(w(E,ye,W))return ye;H===null&&(E.idMap.has(ye)||(H=ye))}if(H===null&&G&&h(ye,G)&&(ie++,G=G.nextSibling,ie>=2&&(H=void 0)),E.activeElementAndParents.includes(ye))break;ye=ye.nextSibling}return H||null}function w(E,W,R){let I=E.idMap.get(W),H=E.idMap.get(R);if(!H||!I)return!1;for(let G of I)if(H.has(G))return!0;return!1}function h(E,W){var H,G,ie;let R=E,I=W;return R.nodeType===I.nodeType&&R.tagName===I.tagName&&(!((H=R.getAttribute)!=null&&H.call(R,"id"))||((G=R.getAttribute)==null?void 0:G.call(R,"id"))===((ie=I.getAttribute)==null?void 0:ie.call(I,"id")))}return v})();function C(v,w){var h;if(v.idMap.has(w))k(v.pantry,w,null);else{if(v.callbacks.beforeNodeRemoved(w)===!1)return;(h=w.parentNode)==null||h.removeChild(w),v.callbacks.afterNodeRemoved(w)}}function M(v,w,h){let E=w;for(;E&&E!==h;){let W=E;E=E.nextSibling,C(v,W)}return E}function T(v,w,h,E){var R,I;let W=((I=(R=E.target).getAttribute)==null?void 0:I.call(R,"id"))===w&&E.target||E.target.querySelector(`[id="${w}"]`)||E.pantry.querySelector(`[id="${w}"]`);return A(W,E),k(v,W,h),W}function A(v,w){let h=v.getAttribute("id");for(;v=v.parentNode;){let E=w.idMap.get(v);E&&(E.delete(h),E.size||w.idMap.delete(v))}}function k(v,w,h){if(v.moveBefore)try{v.moveBefore(w,h)}catch{v.insertBefore(w,h)}else v.insertBefore(w,h)}return m})(),s=(function(){function m(A,k,v){return v.ignoreActive&&A===document.activeElement?null:(v.callbacks.beforeNodeMorphed(A,k)===!1||(A instanceof HTMLHeadElement&&v.head.ignore||(A instanceof HTMLHeadElement&&v.head.style!=="morph"?d(A,k,v):(f(A,k,v),T(A,v)||a(v,A,k))),v.callbacks.afterNodeMorphed(A,k)),A)}function f(A,k,v){let w=k.nodeType;if(w===1){let h=A,E=k,W=h.attributes,R=E.attributes;for(let I of R)M(I.name,h,"update",v)||h.getAttribute(I.name)!==I.value&&h.setAttribute(I.name,I.value);for(let I=W.length-1;0<=I;I--){let H=W[I];if(H&&!E.hasAttribute(H.name)){if(M(H.name,h,"remove",v))continue;h.removeAttribute(H.name)}}T(h,v)||x(h,E,v)}(w===8||w===3)&&A.nodeValue!==k.nodeValue&&(A.nodeValue=k.nodeValue)}function x(A,k,v){if(A instanceof HTMLInputElement&&k instanceof HTMLInputElement&&k.type!=="file"){let w=k.value,h=A.value;C(A,k,"checked",v),C(A,k,"disabled",v),k.hasAttribute("value")?h!==w&&(M("value",A,"update",v)||(A.setAttribute("value",w),A.value=w)):M("value",A,"remove",v)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&k instanceof HTMLOptionElement)C(A,k,"selected",v);else if(A instanceof HTMLTextAreaElement&&k instanceof HTMLTextAreaElement){let w=k.value,h=A.value;if(M("value",A,"update",v))return;w!==h&&(A.value=w),A.firstChild&&A.firstChild.nodeValue!==w&&(A.firstChild.nodeValue=w)}}function C(A,k,v,w){let h=k[v],E=A[v];if(h!==E){let W=M(v,A,"update",w);W||(A[v]=k[v]),h?W||A.setAttribute(v,""):M(v,A,"remove",w)||A.removeAttribute(v)}}function M(A,k,v,w){return A==="value"&&w.ignoreActiveValue&&k===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(A,k,v)===!1}function T(A,k){return!!k.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return m})();function i(m,f,x,C){if(m.head.block){let M=f.querySelector("head"),T=x.querySelector("head");if(M&&T){let A=d(M,T,m);return Promise.all(A).then(()=>{let k=Object.assign(m,{head:{block:!1,ignore:!0}});return C(k)})}}return C(m)}function d(m,f,x){let C=[],M=[],T=[],A=[],k=new Map;for(let w of f.children)k.set(w.outerHTML,w);for(let w of m.children){let h=k.has(w.outerHTML),E=x.head.shouldReAppend(w),W=x.head.shouldPreserve(w);h||W?E?M.push(w):(k.delete(w.outerHTML),T.push(w)):x.head.style==="append"?E&&(M.push(w),A.push(w)):x.head.shouldRemove(w)!==!1&&M.push(w)}A.push(...k.values());let v=[];for(let w of A){let h=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(h)!==!1){if("href"in h&&h.href||"src"in h&&h.src){let E,W=new Promise(function(R){E=R});h.addEventListener("load",function(){E()}),v.push(W)}m.appendChild(h),x.callbacks.afterNodeAdded(h),C.push(h)}}for(let w of M)x.callbacks.beforeNodeRemoved(w)!==!1&&(m.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(m,{added:C,kept:T,removed:M}),v}let l=(function(){function m(v,w,h){let{persistentIds:E,idMap:W}=A(v,w),R=f(h),I=R.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(I))throw`Do not understand how to morph style ${I}`;return{target:v,newContent:w,config:R,morphStyle:I,ignoreActive:R.ignoreActive,ignoreActiveValue:R.ignoreActiveValue,restoreFocus:R.restoreFocus,idMap:W,persistentIds:E,pantry:x(),activeElementAndParents:C(v),callbacks:R.callbacks,head:R.head}}function f(v){let w=Object.assign({},t);return Object.assign(w,v),w.callbacks=Object.assign({},t.callbacks,v.callbacks),w.head=Object.assign({},t.head,v.head),w}function x(){let v=document.createElement("div");return v.hidden=!0,document.body.insertAdjacentElement("afterend",v),v}function C(v){let w=[],h=document.activeElement;if((h==null?void 0:h.tagName)!=="BODY"&&v.contains(h))for(;h&&(w.push(h),h!==v);)h=h.parentElement;return w}function M(v){var h;let w=Array.from(v.querySelectorAll("[id]"));return(h=v.getAttribute)!=null&&h.call(v,"id")&&w.push(v),w}function T(v,w,h,E){for(let W of E){let R=W.getAttribute("id");if(w.has(R)){let I=W;for(;I;){let H=v.get(I);if(H==null&&(H=new Set,v.set(I,H)),H.add(R),I===h)break;I=I.parentElement}}}}function A(v,w){let h=M(v),E=M(w),W=k(h,E),R=new Map;T(R,W,v,h);let I=w.__idiomorphRoot||w;return T(R,W,I,E),{persistentIds:W,idMap:R}}function k(v,w){let h=new Set,E=new Map;for(let{id:R,tagName:I}of v)E.has(R)?h.add(R):E.set(R,I);let W=new Set;for(let{id:R,tagName:I}of w)W.has(R)?h.add(R):E.get(R)===I&&W.add(R);for(let R of h)W.delete(R);return W}return m})(),{normalizeElement:p,normalizeParent:u}=(function(){let m=new WeakSet;function f(T){return T instanceof Document?T.documentElement:T}function x(T){if(T==null)return document.createElement("div");if(typeof T=="string")return x(M(T));if(m.has(T))return T;if(T instanceof Node){if(T.parentNode)return new C(T);{let A=document.createElement("div");return A.append(T),A}}else{let A=document.createElement("div");for(let k of[...T])A.append(k);return A}}class C{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],k=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;k&&k!=this.nextSibling;)A.push(k),k=k.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((k,v)=>{if(v instanceof Element){v.matches(A)&&k.push(v);let w=v.querySelectorAll(A);for(let h=0;h<w.length;h++)k.push(w[h])}return k},[])}insertBefore(A,k){return this.realParentNode.insertBefore(A,k)}moveBefore(A,k){return this.realParentNode.moveBefore(A,k)}get __idiomorphRoot(){return this.originalNode}}function M(T){let A=new DOMParser,k=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(k.match(/<\/html>/)||k.match(/<\/head>/)||k.match(/<\/body>/)){let v=A.parseFromString(T,"text/html");if(k.match(/<\/html>/))return m.add(v),v;{let w=v.firstChild;return w&&m.add(w),w}}else{let w=A.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return m.add(w),w}}return{normalizeElement:f,normalizeParent:x}})();return{morph:r,defaults:t}})();var wl=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;rx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,a){var s,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(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let d=(s=o.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Cl={index:-1,draft:""};function nx(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!o)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:n}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Cl}}}function ox(e,t){var r,n,o,a,s,i,d,l,p,u,m,f,x,C,M,T,A,k,v,w,h,E,W,R,I,H,G,ie,ye,Oe,et,be,xe,Ie,Je,X,Te,K;return[e.id,e.role,(n=(r=e.content)==null?void 0:r.length)!=null?n:0,(a=(o=e.content)==null?void 0:o.slice(-32))!=null?a:"",e.streaming?"1":"0",(s=e.variant)!=null?s:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(m=(u=e.approval)==null?void 0:u.status)!=null?m:"",(x=(f=e.toolCall)==null?void 0:f.status)!=null?x:"",(M=(C=e.toolCall)==null?void 0:C.name)!=null?M:"",(k=(A=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:A.length)!=null?k:0,(E=(h=(w=(v=e.toolCall)==null?void 0:v.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:h.slice(-32))!=null?E:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(R=e.toolCall)!=null&&R.args?JSON.stringify(e.toolCall.args).length:0,(G=(H=(I=e.reasoning)==null?void 0:I.chunks)==null?void 0:H.length)!=null?G:0,(et=(Oe=(ye=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Oe.length)!=null?et:0,(Je=(Ie=(xe=(be=e.reasoning)==null?void 0:be.chunks)==null?void 0:xe[e.reasoning.chunks.length-1])==null?void 0:Ie.slice(-32))!=null?Je:"",(Te=(X=e.contentParts)==null?void 0:X.length)!=null?Te:0,(K=e.stopReason)!=null?K:"",t].join("\0")}function ax(){return new Map}function sx(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}function ix(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}function lx(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function vl(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Os(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,t){return Os(e)-e.scrollTop<=t}function Al(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=r-n;return s||Math.abs(p)<a?{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 Sl(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 _r={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Nr=1e5,Io=Nr+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Bw=["pre","code","a","script","style"],Tl=e=>{var t,r,n,o,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ns.placeholder,speed:(n=e==null?void 0:e.speed)!=null?n:Ns.speed,duration:(o=e==null?void 0:e.duration)!=null?o:Ns.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ns.buffer}},cx=[{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"}],$s=new Map;for(let e of cx)$s.set(e.name,e);var ca=e=>{$s.set(e.name,e)},$p=e=>{cx.some(t=>t.name===e)||$s.delete(e)},Fp=()=>Array.from($s.keys()),Fs=(e,t)=>{var r,n;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(n=$s.get(e))!=null?n:null},Ml=(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 a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
65
|
-
`);return
|
|
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,m,f,y,C;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&&((m=l.text)!=null&&m.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 k=(C=this.pendingVoiceAssistantMessageId)!=null?C:(y=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:y.id;k&&this.ttsSpokenMessageIds.add(k)}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,f={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(f),f}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:m,rawContent:f}=n,C={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},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};r.push(C)}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,m,f;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 C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!C){let k=rx(y,this.config.errorMessage);if(k){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:k,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(y instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,y):(f=(m=this.callbacks).onError)==null||f.call(m,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=rx(l,this.config.errorMessage);if(u){let m={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(m)}}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 m;if(i?m=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):m=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),m){let f=null;if(m instanceof Response){if(!m.ok){let y=await m.json().catch(()=>null);throw new Error((l=y==null?void 0:y.error)!=null?l:`Approval request failed: ${m.status}`)}f=m.body}else m instanceof ReadableStream&&(f=m);f?await this.connectStream(f,{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(m){let f=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||(u=(p=this.callbacks).onError)==null||u.call(p,m instanceof Error?m:new Error(String(m)))}}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,m,f,y,C,k,T,S,M,v,b;let n=this.messages.find(x=>x.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=(m=t.toolCall)==null?void 0:m.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 x=(C=t.toolCall)==null?void 0:C.args,E=Array.isArray(x==null?void 0:x.questions)?x.questions:[];if(E.length===1){let B=typeof((k=E[0])==null?void 0:k.question)=="string"?E[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=(S=t.toolCall)==null?void 0:S.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let x=typeof r=="string"?r:Object.entries(r).map(([E,B])=>`${E}: ${Array.isArray(B)?B.join(", "):B}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let x=a!=null?a:{};l.forEach((E,B)=>{let H=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!H)return;let W=x[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 x=await this.client.resumeFlow(o,{[s]:r});if(!x.ok){let E=await x.json().catch(()=>null);throw new Error((M=E==null?void 0:E.error)!=null?M:`Resume failed: ${x.status}`)}x.body?await this.connectStream(x.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(b=(v=this.callbacks).onError)==null||b.call(v,x instanceof Error?x:new Error(String(x)))}}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 S,M,v,b,x,E,B;let u=(S=p.toolCall)==null?void 0:S.name,m=(M=p.toolCall)==null?void 0:M.id;if(!u||!m)return null;let f=`${t}:${m}`;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 C=(b=(v=p.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?b:u,k=this.client.executeWebMcpToolCall(u,(x=p.toolCall)==null?void 0:x.args,y.signal),T;if(!k)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await k}catch(H){return H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"))||(B=(E=this.callbacks).onError)==null||B.call(E,H instanceof Error?H:new Error(String(H))),this.webMcpInflightKeys.delete(f),null}return y.signal.aborted?(this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:C,output:T}}));try{let p=a.filter(f=>f!==null);if(p.length===0)return;let u={};for(let f of p)u[f.resumeKey]=f.output;let m=await this.client.resumeFlow(t,u,{signal:s.signal});if(!m.ok){let f=await m.json().catch(()=>null);throw new Error((i=f==null?void 0:f.error)!=null?i:`Resume failed: ${m.status}`)}for(let f of p)this.webMcpResolvedKeys.add(f.dedupeKey);m.body&&await this.connectStream(m.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,m,f,y,C,k,T,S,M,v,b;let r=(p=t.agentMetadata)==null?void 0:p.executionId,n=(u=t.toolCall)==null?void 0:u.name,o=(m=t.toolCall)==null?void 0:m.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 x=`${r}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x))return;this.webMcpInflightKeys.add(x);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(x)}catch(E){(k=(C=this.callbacks).onError)==null||k.call(C,E instanceof Error?E:new Error(String(E)))}finally{this.webMcpInflightKeys.delete(x)}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 x;if(l?x=await l:x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let E=(M=(S=t.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?M:n;await this.resumeWithToolOutput(r,E,x,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(x){x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"))||(b=(v=this.callbacks).onError)==null||b.call(v,x instanceof Error?x:new Error(String(x)))}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.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,m,f,y,C;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=(m=r.agentMetadata)==null?void 0:m.executionId,l=(f=r.toolCall)==null?void 0:f.id;if(i&&Ra(i)&&d&&l&&((y=r.agentMetadata)==null?void 0:y.awaitingLocalTool)===!0){let k=`${d}:${l}`;(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))&&(a.agentMetadata={...(C=a.agentMetadata)!=null?C:{},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 h=(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 Ac=[["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 Sc=[["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 Ap=[["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 Sp=[["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 Hw={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":Sp,"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:Ap,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:Ac,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:Sc,monitor:Jc,smartphone:yp},Pe=(e,t=24,r="currentColor",n=2)=>{let o=Hw[e];return o?Bw(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 Bw(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 Dw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ow(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=ex(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 Zh(l),m=nl(l)?URL.createObjectURL(l):null,f={id:Dw(),file:l,previewUrl:m,contentPart:u};this.attachments.push(f),this.renderPreview(f)}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=h("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=h("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=h("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=Ow(t.file.type),d=Pe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=tx(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=h("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 nx=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];nx(s)&&nx(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 ox(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,m,f,y,C,k,T,S,M,v,b;return e?{...Zt,...e,theme:ox(Zt.theme,e.theme),darkTheme:ox(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 x=(Te=Zt.features)==null?void 0:Te.artifacts,E=(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=x===void 0&&E===void 0?void 0:{...x,...E,layout:{...x==null?void 0:x.layout,...E==null?void 0:E.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,...(f=(m=e.layout)==null?void 0:m.messages)==null?void 0:f.avatar},timestamp:{...(C=(y=Zt.layout)==null?void 0:y.messages)==null?void 0:C.timestamp,...(T=(k=e.layout)==null?void 0:k.messages)==null?void 0:T.timestamp}},slots:{...(S=Zt.layout)==null?void 0:S.slots,...(M=e.layout)==null?void 0:M.slots}},markdown:{...Zt.markdown,...e.markdown,options:{...(v=Zt.markdown)==null?void 0:v.options,...(b=e.markdown)==null?void 0:b.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 sx(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]=sx(s,o):r[n]=o}return r}function _w(e,t){return t?sx(e,t):e}function _s(e,t={}){var o,s,a,i,d,l,p,u,m,f,y,C,k;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,...(m=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:m.interactive},feedback:{...r.semantic.colors.feedback,...(y=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:y.feedback}},spacing:{...r.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:_w(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(S=>S.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)n=T.transform(n);return n}function Cl(e){var C,k,T,S,M,v,b,x,E,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,Ae,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"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(k=r["--persona-semantic-colors-secondary"])!=null?k: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"]=(M=r["--persona-semantic-colors-background"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(v=r["--persona-semantic-colors-container"])!=null?v: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"]=(x=r["--persona-semantic-colors-text-muted"])!=null?x:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(E=r["--persona-semantic-colors-text-inverse"])!=null?E: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"]=(Ae=(fe=o==null?void 0:o.shadow)!=null?fe:r["--persona-components-introCard-shadow"])!=null?Ae:"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 m=p==null?void 0:p.labelButton;m&&(m.background&&(r["--persona-label-btn-bg"]=m.background),m.border&&(r["--persona-label-btn-border"]=m.border),m.color&&(r["--persona-label-btn-color"]=m.color),m.padding&&(r["--persona-label-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-label-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-label-btn-hover-bg"]=m.hoverBackground),m.fontSize&&(r["--persona-label-btn-font-size"]=m.fontSize),m.gap&&(r["--persona-label-btn-gap"]=m.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 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 ax={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 Nw={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"}}},ix=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"},$w=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=>$w(e),Fw=e=>_s(e),Uw=e=>{var r;let t=_s(void 0,{validate:!1});return _s({...e,palette:{...t.palette,colors:{...Nw.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ns=e=>{let t=Fp(e),r=ix(e==null?void 0:e.theme),n=ix(e==null?void 0:e.darkTheme);return t==="dark"?Uw(_a(r!=null?r:{},n!=null?n:{})):Fw(r)},zw=e=>Cl(e),Io=(e,t)=>{var s;let r=Ns(t),n=zw(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 lx=(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:m=>m.getAttribute("im-preserve")==="true",shouldReAppend:m=>m.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(m,f,y={}){m=p(m);let C=u(f),k=l(m,C,y),T=o(k,()=>i(k,m,C,S=>S.morphStyle==="innerHTML"?(s(S,m,C),Array.from(m.childNodes)):n(S,m,C)));return k.pantry.remove(),T}function n(m,f,y){let C=u(f);return s(m,C,y,f,f.nextSibling),Array.from(C.childNodes)}function o(m,f){var M;if(!m.config.restoreFocus)return f();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return f();let{id:C,selectionStart:k,selectionEnd:T}=y,S=f();return C&&C!==((M=document.activeElement)==null?void 0:M.getAttribute("id"))&&(y=m.target.querySelector(`[id="${C}"]`),y==null||y.focus()),y&&!y.selectionEnd&&T&&y.setSelectionRange(k,T),S}let s=(function(){function m(v,b,x,E=null,B=null){b instanceof HTMLTemplateElement&&x instanceof HTMLTemplateElement&&(b=b.content,x=x.content),E||(E=b.firstChild);for(let H of x.childNodes){if(E&&E!=B){let N=y(v,H,E,B);if(N){N!==E&&k(v,E,N),a(N,H,v),E=N.nextSibling;continue}}if(H instanceof Element){let N=H.getAttribute("id");if(v.persistentIds.has(N)){let q=T(b,N,E,v);a(q,H,v),E=q.nextSibling;continue}}let W=f(b,H,E,v);W&&(E=W.nextSibling)}for(;E&&E!=B;){let H=E;E=E.nextSibling,C(v,H)}}function f(v,b,x,E){if(E.callbacks.beforeNodeAdded(b)===!1)return null;if(E.idMap.has(b)){let B=document.createElement(b.tagName);return v.insertBefore(B,x),a(B,b,E),E.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(b,!0);return v.insertBefore(B,x),E.callbacks.afterNodeAdded(B),B}}let y=(function(){function v(E,B,H,W){let N=null,q=B.nextSibling,se=0,ve=H;for(;ve&&ve!=W;){if(x(ve,B)){if(b(E,ve,B))return ve;N===null&&(E.idMap.has(ve)||(N=ve))}if(N===null&&q&&x(ve,q)&&(se++,q=q.nextSibling,se>=2&&(N=void 0)),E.activeElementAndParents.includes(ve))break;ve=ve.nextSibling}return N||null}function b(E,B,H){let W=E.idMap.get(B),N=E.idMap.get(H);if(!N||!W)return!1;for(let q of W)if(N.has(q))return!0;return!1}function x(E,B){var N,q,se;let H=E,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 v})();function C(v,b){var x;if(v.idMap.has(b))M(v.pantry,b,null);else{if(v.callbacks.beforeNodeRemoved(b)===!1)return;(x=b.parentNode)==null||x.removeChild(b),v.callbacks.afterNodeRemoved(b)}}function k(v,b,x){let E=b;for(;E&&E!==x;){let B=E;E=E.nextSibling,C(v,B)}return E}function T(v,b,x,E){var H,W;let B=((W=(H=E.target).getAttribute)==null?void 0:W.call(H,"id"))===b&&E.target||E.target.querySelector(`[id="${b}"]`)||E.pantry.querySelector(`[id="${b}"]`);return S(B,E),M(v,B,x),B}function S(v,b){let x=v.getAttribute("id");for(;v=v.parentNode;){let E=b.idMap.get(v);E&&(E.delete(x),E.size||b.idMap.delete(v))}}function M(v,b,x){if(v.moveBefore)try{v.moveBefore(b,x)}catch{v.insertBefore(b,x)}else v.insertBefore(b,x)}return m})(),a=(function(){function m(S,M,v){return v.ignoreActive&&S===document.activeElement?null:(v.callbacks.beforeNodeMorphed(S,M)===!1||(S instanceof HTMLHeadElement&&v.head.ignore||(S instanceof HTMLHeadElement&&v.head.style!=="morph"?d(S,M,v):(f(S,M,v),T(S,v)||s(v,S,M))),v.callbacks.afterNodeMorphed(S,M)),S)}function f(S,M,v){let b=M.nodeType;if(b===1){let x=S,E=M,B=x.attributes,H=E.attributes;for(let W of H)k(W.name,x,"update",v)||x.getAttribute(W.name)!==W.value&&x.setAttribute(W.name,W.value);for(let W=B.length-1;0<=W;W--){let N=B[W];if(N&&!E.hasAttribute(N.name)){if(k(N.name,x,"remove",v))continue;x.removeAttribute(N.name)}}T(x,v)||y(x,E,v)}(b===8||b===3)&&S.nodeValue!==M.nodeValue&&(S.nodeValue=M.nodeValue)}function y(S,M,v){if(S instanceof HTMLInputElement&&M instanceof HTMLInputElement&&M.type!=="file"){let b=M.value,x=S.value;C(S,M,"checked",v),C(S,M,"disabled",v),M.hasAttribute("value")?x!==b&&(k("value",S,"update",v)||(S.setAttribute("value",b),S.value=b)):k("value",S,"remove",v)||(S.value="",S.removeAttribute("value"))}else if(S instanceof HTMLOptionElement&&M instanceof HTMLOptionElement)C(S,M,"selected",v);else if(S instanceof HTMLTextAreaElement&&M instanceof HTMLTextAreaElement){let b=M.value,x=S.value;if(k("value",S,"update",v))return;b!==x&&(S.value=b),S.firstChild&&S.firstChild.nodeValue!==b&&(S.firstChild.nodeValue=b)}}function C(S,M,v,b){let x=M[v],E=S[v];if(x!==E){let B=k(v,S,"update",b);B||(S[v]=M[v]),x?B||S.setAttribute(v,""):k(v,S,"remove",b)||S.removeAttribute(v)}}function k(S,M,v,b){return S==="value"&&b.ignoreActiveValue&&M===document.activeElement?!0:b.callbacks.beforeAttributeUpdated(S,M,v)===!1}function T(S,M){return!!M.ignoreActiveValue&&S===document.activeElement&&S!==document.body}return m})();function i(m,f,y,C){if(m.head.block){let k=f.querySelector("head"),T=y.querySelector("head");if(k&&T){let S=d(k,T,m);return Promise.all(S).then(()=>{let M=Object.assign(m,{head:{block:!1,ignore:!0}});return C(M)})}}return C(m)}function d(m,f,y){let C=[],k=[],T=[],S=[],M=new Map;for(let b of f.children)M.set(b.outerHTML,b);for(let b of m.children){let x=M.has(b.outerHTML),E=y.head.shouldReAppend(b),B=y.head.shouldPreserve(b);x||B?E?k.push(b):(M.delete(b.outerHTML),T.push(b)):y.head.style==="append"?E&&(k.push(b),S.push(b)):y.head.shouldRemove(b)!==!1&&k.push(b)}S.push(...M.values());let v=[];for(let b of S){let x=document.createRange().createContextualFragment(b.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(x)!==!1){if("href"in x&&x.href||"src"in x&&x.src){let E,B=new Promise(function(H){E=H});x.addEventListener("load",function(){E()}),v.push(B)}m.appendChild(x),y.callbacks.afterNodeAdded(x),C.push(x)}}for(let b of k)y.callbacks.beforeNodeRemoved(b)!==!1&&(m.removeChild(b),y.callbacks.afterNodeRemoved(b));return y.head.afterHeadMorphed(m,{added:C,kept:T,removed:k}),v}let l=(function(){function m(v,b,x){let{persistentIds:E,idMap:B}=S(v,b),H=f(x),W=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(W))throw`Do not understand how to morph style ${W}`;return{target:v,newContent:b,config:H,morphStyle:W,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:B,persistentIds:E,pantry:y(),activeElementAndParents:C(v),callbacks:H.callbacks,head:H.head}}function f(v){let b=Object.assign({},t);return Object.assign(b,v),b.callbacks=Object.assign({},t.callbacks,v.callbacks),b.head=Object.assign({},t.head,v.head),b}function y(){let v=document.createElement("div");return v.hidden=!0,document.body.insertAdjacentElement("afterend",v),v}function C(v){let b=[],x=document.activeElement;if((x==null?void 0:x.tagName)!=="BODY"&&v.contains(x))for(;x&&(b.push(x),x!==v);)x=x.parentElement;return b}function k(v){var x;let b=Array.from(v.querySelectorAll("[id]"));return(x=v.getAttribute)!=null&&x.call(v,"id")&&b.push(v),b}function T(v,b,x,E){for(let B of E){let H=B.getAttribute("id");if(b.has(H)){let W=B;for(;W;){let N=v.get(W);if(N==null&&(N=new Set,v.set(W,N)),N.add(H),W===x)break;W=W.parentElement}}}}function S(v,b){let x=k(v),E=k(b),B=M(x,E),H=new Map;T(H,B,v,x);let W=b.__idiomorphRoot||b;return T(H,B,W,E),{persistentIds:B,idMap:H}}function M(v,b){let x=new Set,E=new Map;for(let{id:H,tagName:W}of v)E.has(H)?x.add(H):E.set(H,W);let B=new Set;for(let{id:H,tagName:W}of b)B.has(H)?x.add(H):E.get(H)===W&&B.add(H);for(let H of x)B.delete(H);return B}return m})(),{normalizeElement:p,normalizeParent:u}=(function(){let m=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(k(T));if(m.has(T))return T;if(T instanceof Node){if(T.parentNode)return new C(T);{let S=document.createElement("div");return S.append(T),S}}else{let S=document.createElement("div");for(let M of[...T])S.append(M);return S}}class C{constructor(S){this.originalNode=S,this.realParentNode=S.parentNode,this.previousSibling=S.previousSibling,this.nextSibling=S.nextSibling}get childNodes(){let S=[],M=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;M&&M!=this.nextSibling;)S.push(M),M=M.nextSibling;return S}querySelectorAll(S){return this.childNodes.reduce((M,v)=>{if(v instanceof Element){v.matches(S)&&M.push(v);let b=v.querySelectorAll(S);for(let x=0;x<b.length;x++)M.push(b[x])}return M},[])}insertBefore(S,M){return this.realParentNode.insertBefore(S,M)}moveBefore(S,M){return this.realParentNode.moveBefore(S,M)}get __idiomorphRoot(){return this.originalNode}}function k(T){let S=new DOMParser,M=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(M.match(/<\/html>/)||M.match(/<\/head>/)||M.match(/<\/body>/)){let v=S.parseFromString(T,"text/html");if(M.match(/<\/html>/))return m.add(v),v;{let b=v.firstChild;return b&&m.add(b),b}}else{let b=S.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return m.add(b),b}}return{normalizeElement:f,normalizeParent:y}})();return{morph:r,defaults:t}})();var Al=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;lx.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 Sl={index:-1,draft:""};function dx(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:{...Sl}}}function cx(e,t){var r,n,o,s,a,i,d,l,p,u,m,f,y,C,k,T,S,M,v,b,x,E,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,(m=(u=e.approval)==null?void 0:u.status)!=null?m:"",(y=(f=e.toolCall)==null?void 0:f.status)!=null?y:"",(k=(C=e.toolCall)==null?void 0:C.name)!=null?k:"",(M=(S=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:S.length)!=null?M:0,(E=(x=(b=(v=e.toolCall)==null?void 0:v.chunks)==null?void 0:b[e.toolCall.chunks.length-1])==null?void 0:x.slice(-32))!=null?E:"",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 px(){return new Map}function ux(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}function fx(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}function mx(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"},qw=["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}},hx=[{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 hx)za.set(e.name,e);var ps=e=>{za.set(e.name,e)},qp=e=>{hx.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},jw=(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},Vw=(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/,Gw=(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},Kw=(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(jw(n,s[p],t,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Jw=(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(Vw(n,l,t,r.value)),r.value+=1));o.replaceChild(a,e)},ja=(e,t,r,n)=>{var u,m;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:qw).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Gw(d,s)||i.push(d),d=a.nextNode();let l={value:(m=n==null?void 0:n.startIndex)!=null?m:0},p=t==="char"?Kw:Jw;for(let f of i)p(f,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},gx=new WeakMap,Xw=(e,t)=>{var s;if(!e.styles)return;let r=gx.get(t);if(r||(r=new Set,gx.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,Yw=(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)},xx=e=>{let t=zp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Vp=(e,t)=>{Xw(e,t),Yw(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=h("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 Wa=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=a=>{var k,v,w,h,E,W,R,I,H,G,ie,ye,Oe,et;let s=(k=a.launcher)!=null?k:{},i=br(a),d=r.querySelector("[data-role='launcher-title']");if(d){let be=(v=s.title)!=null?v:"Chat Assistant";d.textContent=be,d.setAttribute("title",be)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let be=(w=s.subtitle)!=null?w:"Get answers fast";l.textContent=be,l.setAttribute("title",be)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let be=(h=s.agentIconSize)!=null?h:"40px";if(u.style.height=be,u.style.width=be,u.innerHTML="",s.agentIconName){let xe=parseFloat(be)||24,Ie=Pe(s.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(u.appendChild(Ie),u.style.display=""):(u.textContent=(E=s.agentIconText)!=null?E:"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",u.style.display="")}let m=r.querySelector("[data-role='launcher-image']");if(m){let be=(R=s.agentIconSize)!=null?R:"40px";m.style.height=be,m.style.width=be,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(m.src=s.iconUrl,m.style.display="block"):m.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let be=(I=s.callToActionIconSize)!=null?I:"32px";f.style.height=be,f.style.width=be,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let xe=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,xe=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",s.callToActionIconName){let Ie=parseFloat(be)||24,Je=Math.max(Ie-xe,8),X=Pe(s.callToActionIconName,Je,"currentColor",2);X?f.appendChild(X):f.textContent=(H=s.callToActionIconText)!=null?H:"\u2197"}else f.textContent=(G=s.callToActionIconText)!=null?G:"\u2197"}let x=s.position&&Fn[s.position]?Fn[s.position]:Fn["bottom-right"],C="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",M="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?M:`${C} ${x}`,i||(r.style.zIndex=String((ie=s.zIndex)!=null?ie:Nr));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=(ye=s.border)!=null?ye:T,r.style.boxShadow=(Oe=s.shadow)!=null?Oe: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=(et=s.collapsedMaxWidth)!=null?et:"",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 zw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ll=(e,t={})=>{var C,M,T,A,k,v;let{showClose:r=!0,wrapperClassName:n=zw,buttonSize:o,iconSize:a="28px"}=t,s=(C=e==null?void 0:e.launcher)!=null?C:{},i=(M=o!=null?o:s.closeButtonSize)!=null?M:"32px",d=y("div",n),l=y("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=s.closeButtonTooltipText)!=null?T:"Close chat",u=(A=s.closeButtonShowTooltip)!=null?A:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let m=(k=s.closeButtonIconName)!=null?k:"x",f=(v=s.closeButtonIconText)!=null?v:"\xD7";l.style.color=s.closeButtonColor||Qr.actionIconColor;let x=Pe(m,a,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):l.textContent=f,s.closeButtonBackgroundColor?(l.style.backgroundColor=s.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let w=s.closeButtonBorderWidth||"0px",h=s.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(s.closeButtonBorderRadius?(l.style.borderRadius=s.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(l.style.paddingLeft=s.closeButtonPaddingX,l.style.paddingRight=s.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),s.closeButtonPaddingY?(l.style.paddingTop=s.closeButtonPaddingY,l.style.paddingBottom=s.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&p){let w=null,h=()=>{if(w)return;let W=l.ownerDocument,R=W.body;if(!R)return;w=Xn(W,"div","persona-clear-chat-tooltip"),w.textContent=p;let I=Xn(W,"div");I.className="persona-clear-chat-tooltip-arrow",w.appendChild(I);let H=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(Io),w.style.left=`${H.left+H.width/2}px`,w.style.top=`${H.top-8}px`,w.style.transform="translate(-50%, -100%)",R.appendChild(w)},E=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};d.addEventListener("mouseenter",h),d.addEventListener("mouseleave",E),l.addEventListener("focus",h),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",h),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",h),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},qw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pl=(e,t={})=>{var w,h,E,W,R,I,H,G,ie,ye,Oe,et,be;let{wrapperClassName:r=qw,buttonSize:n,iconSize:o="20px"}=t,s=(h=((w=e==null?void 0:e.launcher)!=null?w:{}).clearChat)!=null?h:{},i=(E=n!=null?n:s.size)!=null?E:"32px",d=(W=s.iconName)!=null?W:"refresh-cw",l=(R=s.iconColor)!=null?R:"",p=(I=s.backgroundColor)!=null?I:"",u=(H=s.borderWidth)!=null?H:"",m=(G=s.borderColor)!=null?G:"",f=(ie=s.borderRadius)!=null?ie:"",x=(ye=s.paddingX)!=null?ye:"",C=(Oe=s.paddingY)!=null?Oe:"",M=(et=s.tooltipText)!=null?et:"Clear chat",T=(be=s.showTooltip)!=null?be:!0,A=y("div",r),k=y("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",M),k.style.color=l||Qr.actionIconColor;let v=Pe(d,o,"currentColor",1);if(v&&(v.style.display="block",k.appendChild(v)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),u||m){let xe=u||"0px",Ie=m||"transparent";k.style.border=`${xe} solid ${Ie}`,k.classList.remove("persona-border-none")}if(f&&(k.style.borderRadius=f,k.classList.remove("persona-rounded-full")),x&&(k.style.paddingLeft=x,k.style.paddingRight=x),C&&(k.style.paddingTop=C,k.style.paddingBottom=C),A.appendChild(k),T&&M){let xe=null,Ie=()=>{if(xe)return;let X=k.ownerDocument,Te=X.body;if(!Te)return;xe=Xn(X,"div","persona-clear-chat-tooltip"),xe.textContent=M;let K=Xn(X,"div");K.className="persona-clear-chat-tooltip-arrow",xe.appendChild(K);let ge=k.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(Io),xe.style.left=`${ge.left+ge.width/2}px`,xe.style.top=`${ge.top-8}px`,xe.style.transform="translate(-50%, -100%)",Te.appendChild(xe)},Je=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};A.addEventListener("mouseenter",Ie),A.addEventListener("mouseleave",Je),k.addEventListener("focus",Ie),k.addEventListener("blur",Je),A._cleanupTooltip=()=>{Je(),A.removeEventListener("mouseenter",Ie),A.removeEventListener("mouseleave",Je),k.removeEventListener("focus",Ie),k.removeEventListener("blur",Je)}}return{button:k,wrapper:A}};var Qr={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))"},fo=e=>{var w,h,E,W,R,I,H,G,ie,ye,Oe,et,be,xe,Ie,Je;let{config:t,showClose:r=!0}=e,n=y("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:{},a=(h=o.headerIconSize)!=null?h:"48px",s=(E=o.closeButtonPlacement)!=null?E:"inline",i=(W=o.headerIconHidden)!=null?W:!1,d=o.headerIconName,l=y("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=a,l.style.width=a,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(a)||24,Te=Pe(d,X*.6,"currentColor",1);Te?l.replaceChildren(Te):l.textContent=(I=(R=t==null?void 0:t.launcher)==null?void 0:R.agentIconText)!=null?I:"\u{1F4AC}"}else if((H=t==null?void 0:t.launcher)!=null&&H.iconUrl){let X=y("img");X.src=t.launcher.iconUrl,X.alt="",X.className="persona-rounded-xl persona-object-cover",X.style.height=a,X.style.width=a,l.replaceChildren(X)}else l.textContent=(ie=(G=t==null?void 0:t.launcher)==null?void 0:G.agentIconText)!=null?ie:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=y("span","persona-text-base persona-font-semibold");u.style.color=Qr.titleColor,u.textContent=(Oe=(ye=t==null?void 0:t.launcher)==null?void 0:ye.title)!=null?Oe:"Chat Assistant";let m=y("span","persona-text-xs");m.style.color=Qr.subtitleColor,m.textContent=(be=(et=t==null?void 0:t.launcher)==null?void 0:et.subtitle)!=null?be:"Here to help you get answers fast",p.append(u,m),i?n.append(p):n.append(l,p);let f=(xe=o.clearChat)!=null?xe:{},x=(Ie=f.enabled)!=null?Ie:!0,C=(Je=f.placement)!=null?Je:"inline",M=null,T=null;if(x){let Te=Pl(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Te.button,T=Te.wrapper,C==="top-right"&&(T.style.right="48px"),C==="inline"&&n.appendChild(T)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="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:v}=Ll(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&n.appendChild(v),{header:n,iconHolder:l,headerTitle:u,headerSubtitle:m,closeButton:k,closeButtonWrapper:v,clearChatButton:M,clearChatButtonWrapper:T}},pa=(e,t,r)=>{var s,i,d,l;let n=(s=r==null?void 0:r.launcher)!=null?s:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",a=(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&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Ho(e){let{items:t,onSelect:r,anchor:n,position:o="bottom-left",portal:a}=e,s=y("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Io)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",o==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let M=document.createElement("hr");s.appendChild(M)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",f.id),f.destructive&&x.setAttribute("data-destructive",""),f.icon){let M=Pe(f.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let C=document.createElement("span");C.textContent=f.label,x.appendChild(C),x.addEventListener("click",M=>{M.stopPropagation(),p(),r(f.id)}),s.appendChild(x)}let i=null;function d(){if(!a)return;let f=n.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,o==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function l(){d(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=x=>{!s.contains(x.target)&&!n.contains(x.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function u(){s.classList.contains("persona-hidden")?l():p()}function m(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:u,destroy:m}}function rr(e){let{icon:t,label:r,size:n,strokeWidth:o,className:a,onClick:s,aria:i}=e,d=y("button","persona-icon-btn"+(a?" "+a:""));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),s&&d.addEventListener("click",s),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Vs(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:d}=e,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,s&&(l+=" "+s);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let m=Pe(t,a!=null?a:14,"currentColor",2);m&&p.appendChild(m)}let u=y("span");if(u.textContent=r,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[m,f]of Object.entries(d))p.setAttribute(m,f);return p}function Gs(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,a=y("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let u;p.icon?u=rr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,d(),n(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{s=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:u}),a.appendChild(u)}function l(p){s=p,d()}return{element:a,setSelected:l}}function Il(e){var f,x;let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:d}=e,l=y("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=y("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=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(x=d.padding)!=null?x:"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 C,M;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let m=Ho({items:n,onSelect:C=>{l.setAttribute("aria-expanded","false"),o(C)},anchor:l,position:a,portal:s});return s||l.appendChild(m.element),l.addEventListener("click",C=>{C.stopPropagation();let M=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),m.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{p.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),m.show()},close:()=>{l.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let C=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),l.remove()}}}var jp=e=>{var n;let t=fo({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",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function jw(e,t,r){var n,o,a;if(t!=null&&t.length)for(let s of t){let i=y("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=s.ariaLabel)!=null?n:s.label)!=null?o:s.id),s.icon){let d=Pe(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let d=y("div","persona-relative");d.appendChild(i);let l=Ho({items:s.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(s.id)),e.appendChild(i)}}var Vp=e=>{var A,k,v,w,h,E,W,R,I;let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=y("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=s.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Qr.titleColor,p=(v=l.querySelector(".persona-combo-btn-label"))!=null?v:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Qr.titleColor,p.textContent=(w=s.title)!=null?w:"Chat Assistant",l.appendChild(p),jw(l,o==null?void 0:o.trailingActions,(h=o==null?void 0:o.onAction)!=null?h:a),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let G=o.onTitleClick;l.addEventListener("click",ie=>{ie.target.closest("button")||G()}),l.addEventListener("keydown",ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),G())})}let H=o==null?void 0:o.titleRowHover;H&&(l.style.borderRadius=(E=H.borderRadius)!=null?E:"10px",l.style.padding=(W=H.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 G,ie;l.style.backgroundColor=(G=H.background)!=null?G:"",l.style.borderColor=(ie=H.border)!=null?ie:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(R=s.closeButtonSize)!=null?R:"32px",m=y("div",""),f=y("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=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=s.closeButtonColor||Qr.actionIconColor;let x=(I=s.closeButtonIconName)!=null?I:"x",C=Pe(x,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",n&&f.addEventListener("click",n),m.appendChild(f),i.appendChild(m);let M=y("div");M.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}},Rl={default:jp,minimal:Vp},Gp=e=>{var t;return(t=Rl[e])!=null?t:Rl.default},Oa=(e,t,r)=>{var s,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=y("div");p.style.display="none";let u=y("span"),m=y("span"),f=y("button");f.style.display="none";let x=y("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:m,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(s=t==null?void 0:t.layout)!=null?s:"default",a=Gp(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&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Wl=e=>{var s,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.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},a=()=>{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:a}},Hl=e=>{var w,h,E,W,R,I,H,G,ie,ye,Oe,et;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(h=t.useIcon)!=null?h:!1,n=(E=t.iconText)!=null?E:"\u2191",o=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(R=t.tooltipText)!=null?R:"Send message",i=(I=t.stopTooltipText)!=null?I:"Stop generating",d=(G=(H=e==null?void 0:e.copy)==null?void 0:H.sendButtonLabel)!=null?G:"Send",l=(ye=(ie=e==null?void 0:e.copy)==null?void 0:ie.stopButtonLabel)!=null?ye:"Stop",p=(Oe=t.showTooltip)!=null?Oe:!1,u=(et=t.size)!=null?et:"40px",m=t.backgroundColor,f=t.textColor,x=y("div","persona-send-button-wrapper"),C=y("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");C.type="submit",C.setAttribute("data-persona-composer-submit","");let M=null,T=null;if(r){C.style.width=u,C.style.height=u,C.style.minWidth=u,C.style.minHeight=u,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",f?C.style.color=f:C.style.color="var(--persona-button-primary-fg, #ffffff)";let be=parseFloat(u)||24,xe=(f==null?void 0:f.trim())||"currentColor";o?(M=Pe(o,be,xe,2),M?C.appendChild(M):C.textContent=n):C.textContent=n,T=Pe(a,be,xe,2),m?C.style.backgroundColor=m:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,f?C.style.color=f:C.classList.add("persona-text-white");t.borderWidth&&(C.style.borderWidth=t.borderWidth,C.style.borderStyle="solid"),t.borderColor&&(C.style.borderColor=t.borderColor),t.paddingX?(C.style.paddingLeft=t.paddingX,C.style.paddingRight=t.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),t.paddingY?(C.style.paddingTop=t.paddingY,C.style.paddingBottom=t.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let A=null;p&&s&&(A=y("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),C.setAttribute("aria-label",s),x.appendChild(C);let k="send";return{button:C,wrapper:x,setMode:be=>{if(be===k)return;k=be;let xe=be==="stop"?i:s;if(C.setAttribute("aria-label",xe),A&&(A.textContent=xe),r){if(M&&T){let Ie=be==="stop"?T:M;C.replaceChildren(Ie)}}else C.textContent=be==="stop"?l:d}}},Bl=e=>{var A,k,v,w,h,E,W,R,I,H,G,ie;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=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(n||o))return null;let s=(w=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?w:"40px",i=y("div","persona-send-button-wrapper"),d=y("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=(E=t.iconSize)!=null?E:s,u=parseFloat(p)||24,m=(R=t.backgroundColor)!=null?R:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,f=(H=t.iconColor)!=null?H:(I=e==null?void 0:e.sendButton)==null?void 0:I.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 C=Pe(l,u,f||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",m&&(d.style.backgroundColor=m),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 M=(G=t.tooltipText)!=null?G:"Start voice recognition";if(((ie=t.showTooltip)!=null?ie:!1)&&M){let ye=y("div","persona-send-button-tooltip");ye.textContent=M,i.appendChild(ye)}return{button:d,wrapper:i}},Dl=e=>{var x,C,M,T,A,k,v,w;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(M=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?M:"40px",n=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=y("input");o.type="file",o.accept=((T=t.allowedTypes)!=null?T:uo).join(","),o.multiple=((A=t.maxFiles)!=null?A:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let a=y("div","persona-send-button-wrapper"),s=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");s.type="button",s.setAttribute("aria-label",(k=t.buttonTooltipText)!=null?k:"Attach file");let i=(v=t.buttonIconName)!=null?v:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);s.style.width=d,s.style.height=d,s.style.minWidth=d,s.style.minHeight=d,s.style.fontSize="18px",s.style.lineHeight="1",s.style.backgroundColor="transparent",s.style.color="var(--persona-primary, #111827)",s.style.border="none",s.style.borderRadius="6px",s.style.transition="background-color 0.15s ease",s.addEventListener("mouseenter",()=>{s.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),s.addEventListener("mouseleave",()=>{s.style.backgroundColor="transparent"});let u=Pe(i,p,"currentColor",1.5);u?s.appendChild(u):s.textContent="\u{1F4CE}",s.addEventListener("click",h=>{h.preventDefault(),o.click()}),a.appendChild(s);let m=(w=t.buttonTooltipText)!=null?w:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=m,a.appendChild(f),{button:s,wrapper:a,input:o,previewsContainer:n}},Ol=e=>{var s,i,d;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=y("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 a=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=a;return n},_l=()=>y("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var _a=e=>{var x,C,M,T,A,k;let{config:t}=e,r=y("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=y("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:a,attachAutoResize:s}=Wl(t);s();let i=Hl(t),d=Bl(t),l=Dl(t),p=Ol(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(a);let u=y("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),m=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&m.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(m,f),o.append(u),o.addEventListener("click",v=>{v.target!==i.button&&v.target!==i.wrapper&&v.target!==(d==null?void 0:d.button)&&v.target!==(d==null?void 0:d.wrapper)&&v.target!==(l==null?void 0:l.button)&&v.target!==(l==null?void 0:l.wrapper)&&a.focus()}),r.append(n,o,p),{footer:r,suggestions:n,composerForm:o,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var ux=()=>{let e=y("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=y("span","persona-pill-peek__icon"),r=Pe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let n=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),a=Pe("chevron-up",16,"currentColor",1.5);return a&&o.appendChild(a),e.append(t,n,o),{root:e,textNode:n}},fx=e=>{var x,C,M,T,A,k;let{config:t}=e,r=y("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(t);o.style.display="none";let{textarea:a,attachAutoResize:s}=Wl(t);a.style.maxHeight="100px",s();let i=Hl(t),d=Bl(t),l=Dl(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=y("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let m=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&m.append(d.wrapper),m.append(i.wrapper),p.addEventListener("click",v=>{v.target!==i.button&&v.target!==i.wrapper&&v.target!==(d==null?void 0:d.button)&&v.target!==(d==null?void 0:d.wrapper)&&v.target!==(l==null?void 0:l.button)&&v.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&p.append(l.input),p.append(u,a,m),l&&r.append(l.previewsContainer),r.append(p,n,o);let f=p;return{footer:r,suggestions:n,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:o,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var mx=e=>{var p,u,m,f,x,C,M,T,A,k,v,w,h,E,W,R,I;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,r=br(e);if(Wo(e)){let H=(f=(m=e==null?void 0:e.launcher)==null?void 0:m.composerBar)!=null?f:{},G=y("div","persona-widget-wrapper persona-fixed persona-transition");G.setAttribute("data-persona-composer-bar",""),G.dataset.state="collapsed",G.dataset.expandedSize=(x=H.expandedSize)!=null?x:"anchored",G.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:Nr);let ie=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ie.style.width="100%",G.appendChild(ie);let ye=y("div","persona-widget-pill-root");return ye.setAttribute("data-persona-composer-bar",""),ye.dataset.state="collapsed",ye.dataset.expandedSize=(T=H.expandedSize)!=null?T:"anchored",ye.style.zIndex=String((k=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?k:Nr),{wrapper:G,panel:ie,pillRoot:ye}}if(r){let H=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),G=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return H.appendChild(G),{wrapper:H,panel:G}}if(!t){let H=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),G=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ie=(w=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?w:"100%";return H.style.width=ie,G.style.width="100%",H.appendChild(G),{wrapper:H,panel:G}}let o=(h=e==null?void 0:e.launcher)!=null?h:{},a=o.position&&Fn[o.position]?Fn[o.position]:Fn["bottom-right"],s=y("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((W=(E=e==null?void 0:e.launcher)==null?void 0:E.zIndex)!=null?W:Nr);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(I=(R=e==null?void 0:e.launcher)==null?void 0:R.width)!=null?I:e==null?void 0:e.launcherWidth,l=d!=null?d:xn;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},Vw=(e,t)=>{var v,w,h,E,W,R,I,H,G;let r=y("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(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 a=(h=(w=(v=e==null?void 0:e.launcher)==null?void 0:v.clearChat)==null?void 0:w.enabled)!=null?h:!0,s=null,i=null;if(a){let ie=Pl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=ie.button,i=ie.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=y("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=y("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=y("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=y("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(W=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeTitle)!=null?W:"Hello \u{1F44B}";let m=y("p","persona-mt-2 persona-text-sm persona-text-persona-muted");m.textContent=(I=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",p.append(u,m);let f=y("div","persona-flex persona-flex-col persona-gap-3"),x=(H=e==null?void 0:e.layout)==null?void 0:H.contentMaxWidth;x&&(f.style.maxWidth=x,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((G=e==null?void 0:e.copy)==null?void 0:G.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,f);let M=y("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let T=fx({config:e}),{root:A,textNode:k}=ux();return r.append(d,o,l,M),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:f,composerOverlay:M,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:m,closeButton:n,closeButtonWrapper:o,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("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:k}},gx=(e,t=!0)=>{var M,T,A,k,v,w,h,E,W;if(Wo(e))return Vw(e,t);let r=y("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=(M=e==null?void 0:e.layout)==null?void 0:M.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,a=n?Oa(e,n,{showClose:t}):fo({config:e,showClose:t}),s=y("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");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages");let i=y("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=br(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=y("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=y("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(v=e==null?void 0:e.copy)==null?void 0:v.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let p=y("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",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,p);let f=_a({config:e}),x=((W=e==null?void 0:e.layout)==null?void 0:W.showFooter)!==!1;o?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let C=y("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",x||(f.footer.style.display="none"),r.append(f.footer),r.append(C),{container:r,body:s,messagesWrapper:p,composerOverlay:C,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:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.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 Gw=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}},Kw=(e,t)=>{if(!e)return null;let r=Gw(e);if(r===null)return null;let n=t==null?void 0:t[e],o=n!==void 0?n:r;return o||null},Jw=(e,t)=>{let r=y("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},Xw=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Kp=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(":"))},Jp=320,xx=320,Yw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Qw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Zw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),eC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),tC=(e,t,r)=>{if(e.length===0)return null;try{let n=y("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r==null||r())};return e.forEach((i,d)=>{var u;let l=y("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=`${Jp}px`,l.style.maxHeight=`${xx}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&&s())}),l.addEventListener("load",()=>{p=!0}),Xw(i.image)?(l.src=i.image,n.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(s(),null):n}catch{return r==null||r(),null}},rC=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(n=>{if(!Kp(n.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Jp}px`,t.appendChild(o),r+=1}),r===0?(t.remove(),null):t}catch{return null}},nC=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(n=>{if(!Kp(n.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Jp}px`,o.style.maxHeight=`${xx}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}},oC=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(n=>{if(!Kp(n.data))return;let o=y("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}},ua=()=>{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},Xp=(e,t,r)=>{let n={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let o=t(n);if(o!==null)return o}return ua()},aC=(e,t)=>{let r=y("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=y("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},hx=(e,t)=>{let r=y("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},sC=(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},Yp=(e,t,r)=>{var f,x,C,M,T,A;let n=(f=t.showCopy)!=null?f:!0,o=(x=t.showUpvote)!=null?x:!0,a=(C=t.showDownvote)!=null?C:!0;if(!n&&!o&&!a){let k=y("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let s=(M=t.visibility)!=null?M:"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=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${s==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let m=(k,v,w)=>{let h=rr({icon:k,label:v,size:14,className:"persona-message-action-btn"});return h.setAttribute("data-action",w),h};return n&&u.appendChild(m("copy","Copy message","copy")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),a&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},Na=(e,t,r,n,o,a)=>{var X,Te,K,ge,ce,fe,He,rt,Q,de,_e,Y,V,Ce,Be,oe,Ee;let s=r!=null?r:{},i=(X=s.layout)!=null?X:"bubble",d=s.avatar,l=s.timestamp,p=(Te=d==null?void 0:d.show)!=null?Te:!1,u=(K=l==null?void 0:l.show)!=null?K:!1,m=(ge=d==null?void 0:d.position)!=null?ge:"left",f=(ce=l==null?void 0:l.position)!=null?ce:"below",x=sC(e.role,i),C=y("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Yw(e),T=(He=(fe=e.content)==null?void 0:fe.trim())!=null?He:"",k=M.length>0&&T===Zi,v=Tl((Q=(rt=a==null?void 0:a.widgetConfig)==null?void 0:rt.features)==null?void 0:Q.streamAnimation),w=(Y=(_e=(de=a==null?void 0:a.widgetConfig)==null?void 0:de.features)==null?void 0:_e.streamAnimation)==null?void 0:Y.plugins,h=e.role==="assistant"&&v.type!=="none"?Fs(v.type,w):null,E=e.role==="assistant"&&((V=h==null?void 0:h.isAnimating)==null?void 0:V.call(h,e))===!0,W=e.role==="assistant"&&h!==null&&(!!e.streaming||E);W&&(h!=null&&h.bubbleClass)&&C.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",`${v.speed}ms`),R.style.setProperty("--persona-stream-duration",`${v.duration}ms`));let I=W?Ml((Ce=e.content)!=null?Ce:"",v.buffer,h,e,!!e.streaming):(Be=e.content)!=null?Be:"",H=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent}),G=H;W&&(h==null?void 0:h.wrap)==="char"?G=Us(H,"char",e.id,{skipTags:h.skipTags}):W&&(h==null?void 0:h.wrap)==="word"&&(G=Us(H,"word",e.id,{skipTags:h.skipTags}));let ie=null;if(k?(ie=document.createElement("div"),ie.innerHTML=G,ie.style.display="none",R.appendChild(ie)):R.innerHTML=G,W&&(h!=null&&h.useCaret)&&!k&&T){let we=kl(),Dt=R.querySelectorAll(".persona-stream-char, .persona-stream-word"),U=Dt[Dt.length-1];if(U!=null&&U.parentNode)U.parentNode.insertBefore(we,U.nextSibling);else{let ae=R.lastElementChild;ae?ae.appendChild(we):R.appendChild(we)}}if(u&&f==="inline"&&e.createdAt){let we=hx(e,l);we.classList.add("persona-ml-2","persona-inline"),R.appendChild(we)}if(M.length>0){let we=tC(M,!k&&!!T,()=>{k&&ie&&(ie.style.display="")});we?C.appendChild(we):k&&ie&&(ie.style.display="")}let ye=Qw(e);if(ye.length>0){let we=rC(ye);we&&C.appendChild(we)}let Oe=Zw(e);if(Oe.length>0){let we=nC(Oe);we&&C.appendChild(we)}let et=eC(e);if(et.length>0){let we=oC(et);we&&C.appendChild(we)}if(C.appendChild(R),u&&f==="below"&&e.createdAt){let we=hx(e,l);we.classList.add("persona-mt-1"),C.appendChild(we)}let be=e.role==="assistant"?Kw(e.stopReason,(Ee=(oe=a==null?void 0:a.widgetConfig)==null?void 0:oe.copy)==null?void 0:Ee.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let we=!!(I&&I.trim()),Dt=v.placeholder==="skeleton",U=Dt&&v.buffer==="line"&&we;if(we)U&&C.appendChild(zs());else if(Dt)C.appendChild(zs());else{let ae=Xp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);ae&&C.appendChild(ae)}}if(be&&e.stopReason&&!e.streaming&&(T||(R.style.display="none"),C.appendChild(Jw(e.stopReason,be))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let we=Yp(e,n,o);C.appendChild(we)}if(!p||e.role==="system")return C;let Ie=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Je=aC(d,e.role);return m==="right"||m==="left"&&e.role==="user"?Ie.append(C,Je):Ie.append(Je,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ie},yx=(e,t,r,n,o,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Na(e,t,r,n,o,a)};var $a=new Set,iC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),lC=(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(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
74
|
-
`):""},
|
|
75
|
-
`);let o=
|
|
76
|
-
`):""},pC=(e,t)=>{var p,u,m,f,x;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",a=cC(e,(m=n==null?void 0:n.previewMaxLines)!=null?m:3),s=r?Bh(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=s;return o==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||s:o==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=Dd(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Dd(r,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},wx=(e,t,r)=>{var p;let n=Fa.has(e),o=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",n?"true":"false");let d=a.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",m=Pe(n?"chevron-up":"chevron-down",16,u,2);m?l.appendChild(m):l.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Zp=(e,t)=>{var G,ie,ye,Oe,et,be,xe,Ie,Je;let r=e.toolCall,n=(G=t==null?void 0:t.toolCall)!=null?G:{},o=y("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 a=(ye=(ie=t==null?void 0:t.features)==null?void 0:ie.toolCallDisplay)!=null?ye:{},s=a.expandable!==!1,i=s&&Fa.has(e.id),{summary:d,previewText:l,isActive:p}=pC(e,t),u=y("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");u.type="button",s&&(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 m=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let x=String((Oe=r.startedAt)!=null?Oe:Date.now()),C=()=>{let X=y("span","");return X.setAttribute("data-tool-elapsed",x),X.textContent=Is(r),X},M=(be=n.renderCollapsedSummary)==null?void 0:be.call(n,{message:e,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(et=a.collapsedMode)!=null?et:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Is(r),createElapsedElement:C});typeof M=="string"&&M.trim()?(f.textContent=M,m.appendChild(f)):M instanceof HTMLElement?m.appendChild(M):(f.textContent=d,m.appendChild(f));let T=(xe=a.loadingAnimation)!=null?xe:"none",A=n.activeTextTemplate,k=n.completeTextTemplate,v=p?A:k,w=M instanceof HTMLElement,h=(X,Te,K)=>{let ge=K;for(let ce of Te){let fe=y("span","persona-tool-char");fe.style.setProperty("--char-index",String(ge)),fe.textContent=ce===" "?"\xA0":ce,X.appendChild(fe),ge++}return ge},E=(X,Te)=>{var fe;f.textContent="";let K=((fe=r.name)==null?void 0:fe.trim())||"tool",ge=Vi(X,K),ce=0;for(let He of ge){let rt=He.styles.length>0?(()=>{let Q=y("span",He.styles.map(de=>`persona-tool-text-${de}`).join(" "));return f.appendChild(Q),Q})():f;if(He.isDuration&&p)rt.appendChild(C());else{let Q=He.isDuration?Is(r):He.text;Te?ce=h(rt,Q,ce):rt.appendChild(document.createTextNode(Q))}}};if(!w)if(p&&T!=="none"){let X=(Ie=n.loadingAnimationDuration)!=null?Ie: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`),v&&E(v,!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)),v)E(v,!0);else{let Te=f.textContent||d;f.textContent="",h(f,Te,0)}}else v&&E(v,!1);let W=null;if(s){W=y("div","persona-flex persona-items-center");let X=n.toggleTextColor||n.headerTextColor||"currentColor",Te=Pe(i?"chevron-up":"chevron-down",16,X,2);Te?W.appendChild(Te):W.textContent=i?"Hide":"Show";let K=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(W),u.append(m,K)}else u.append(m);let R=y("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&&a.activePreview&&l){let X=(Je=n.renderCollapsedPreview)==null?void 0:Je.call(n,{message:e,toolCall:r,defaultPreview:l,isActive:p,config:t!=null?t:{}});dC(R,X)||(R.textContent=l),R.style.display=""}if(!i&&p&&a.activeMinHeight&&(o.style.minHeight=a.activeMinHeight),!s)return o.append(u,R),o;let I=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=i?"":"none",n.contentBackgroundColor&&(I.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(I.style.color=n.contentTextColor),n.contentPaddingX&&(I.style.paddingLeft=n.contentPaddingX,I.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(I.style.paddingTop=n.contentPaddingY,I.style.paddingBottom=n.contentPaddingY),r.name){let X=y("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,I.appendChild(X)}if(r.args!==void 0){let X=y("div","persona-space-y-1"),Te=y("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Te.style.color=n.labelTextColor),Te.textContent="Arguments";let K=y("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(Te,K),I.appendChild(X)}if(r.chunks&&r.chunks.length){let X=y("div","persona-space-y-1"),Te=y("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Te.style.color=n.labelTextColor),Te.textContent="Activity";let K=y("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(Te,K),I.appendChild(X)}if(r.status==="complete"&&r.result!==void 0){let X=y("div","persona-space-y-1"),Te=y("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Te.style.color=n.labelTextColor),Te.textContent="Result";let K=y("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(Te,K),I.appendChild(X)}if(r.status==="complete"&&typeof r.duration=="number"){let X=y("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(X.style.color=n.contentTextColor),X.textContent=`Duration: ${r.duration}ms`,I.appendChild(X)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let X=n.toggleTextColor||n.headerTextColor||"currentColor",Te=Pe(i?"chevron-up":"chevron-down",16,X,2);Te?W.appendChild(Te):W.textContent=i?"Hide":"Show"}I.style.display=i?"":"none",R.style.display=i?"none":R.textContent||R.childNodes.length?"":"none"})(),o.append(u,R,I),o};var Bo=ld(Ui(),1);var tu="ask_user_question",eu=8,Ua="data-persona-ask-sheet-for",uC="Other",fC="Other\u2026",vx="Type your own answer here",Ax="Send",mC="Next",gC="Back",hC="Submit all",xC="Skip",yC=3,ru="data-ask-current-index",nu="data-ask-question-count",Sx="data-ask-answers",ou="data-ask-grouped",Tx="data-ask-layout",bC=e=>e.layout==="pills"?"pills":"rows",wC=e=>e.getAttribute(Tx)==="pills"?"pills":"rows",Cx=!1,Mx=e=>e.replace(/["\\]/g,"\\$&"),mo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===tu,Nl=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},go=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(""),a=(0,Bo.parse)(o,Bo.STR|Bo.OBJ|Bo.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},Ks=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>eu&&!Cx&&(Cx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${eu}.`)),t.slice(0,eu)},CC=e=>{var t;return(t=Ks(e)[0])!=null?t:null},vC=(e,t)=>{var r;return(r=Ks(e)[t])!=null?r:null},kx=(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))},Ex=(e,t,r)=>{if(e!=="rows")return null;let n=y("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");n.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},AC=(e,t,r,n)=>{let a=y("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let d=Ex(r,n,t);d&&a.appendChild(d)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},SC=e=>{let r=y("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},TC=(e,t,r,n)=>{var p,u,m;let a=y("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!r){for(let f=0;f<yC;f++)a.appendChild(SC(n));return a}if(d.forEach((f,x)=>{a.appendChild(AC(f,x,n,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=n==="rows"?uC:fC;if(n==="rows"){let x=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let C=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:vx,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),C.appendChild(M),x.appendChild(C);let T=Ex(n,s,d.length);T&&x.appendChild(T),a.appendChild(x)}else{let x=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(m=t.freeTextLabel)!=null?m:f,a.appendChild(x)}}return a},Lx=(e,t)=>{var a,s;let n=y("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=(a=e.freeTextPlaceholder)!=null?a:vx,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Ax,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},MC=e=>{var n;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=y("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=e.submitLabel)!=null?n:Ax,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},kC=(e,t,r)=>{var l,p,u,m;let n=y("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=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:gC,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,n.appendChild(o);let a=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=y("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:xC,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=y("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:hC:(m=r.nextLabel)!=null?m:mC,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n},fa=e=>{let t=e.getAttribute(Sx);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Px=(e,t)=>{e.setAttribute(Sx,JSON.stringify(t))},kn=e=>{var r;let t=Number((r=e.getAttribute(ru))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},EC=(e,t)=>{e.setAttribute(ru,String(Math.max(0,Math.floor(t))))},za=e=>{var r;let t=Number((r=e.getAttribute(nu))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Do=e=>e.getAttribute(ou)==="true",LC=(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((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let d=r[i];(typeof d=="string"||Array.isArray(d))&&(n[s]=d)}}),n},PC=(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)))},$l=(e,t)=>{let{payload:r}=go(t),n=Ks(r),o=fa(e),a={},s=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(a[l]=o[d]))}),a},Ix=e=>{let t=fa(e),r=kn(e),n=t[r],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.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 s=new Set(Array.from(a).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&&!s.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=""},Rx=e=>{if(!Do(e))return;let t=fa(e),r=kn(e),n=t[r],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!o);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},au=(e,t,r)=>{let n=Nl(r),o=wC(e),{payload:a,complete:s}=go(t),i=Do(e),d=kn(e),l=za(e),p=i?vC(a,d):CC(a),u=!!(p!=null&&p.multiSelect),m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let A=TC(p,n,s,o);C.replaceWith(A)}if(o!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Lx(n,o))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(MC(n)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=kC(d,l,n);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();Ix(e),Rx(e)},IC=(e,t,r)=>{let n=Nl(t),o=bC(n),a=e.toolCall.id,s=Ks(r),i=Math.max(1,s.length),d=i>1,l=LC(e,s),p=d?PC(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ua,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(nu,String(i)),u.setAttribute(ru,String(p)),u.setAttribute(ou,d?"true":"false"),u.setAttribute(Tx,o),Px(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`),kx(u,n);let m=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",m.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",m.appendChild(x),u.appendChild(m);let M=y("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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),o!=="rows"&&u.appendChild(Lx(n,o)),au(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},RC=(e,t,r)=>{let{payload:n}=go(t),o=Math.max(1,Ks(n).length);o>za(e)&&(e.setAttribute(nu,String(o)),o>1&&!Do(e)&&e.setAttribute(ou,"true")),au(e,t,r)},Wx=(e,t)=>{let r=y("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=Nl(t);kx(r,n);let o=y("span","persona-ask-stub-label"),{complete:a}=go(e);return o.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},qa=(e,t,r)=>{if(!r||!mo(e)||Nl(t).enabled===!1)return;let o=e.toolCall.id;r.querySelectorAll(`[${Ua}]`).forEach(l=>{l.getAttribute(Ua)!==o&&l.remove()});let s=r.querySelector(`[${Ua}="${Mx(o)}"]`);if(s){RC(s,e,t);return}let{payload:i}=go(e),d=IC(e,t,i);r.appendChild(d)},Oo=(e,t)=>{if(!e)return;let r=t?`[${Ua}="${Mx(t)}"]`:`[${Ua}]`;e.querySelectorAll(r).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(a)?a:180)})},su=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),_o=(e,t)=>{let r=fa(e),n=kn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[n]:r[n]=t,Px(e,r),Ix(e),Rx(e)},Fl=(e,t,r,n)=>{let o=za(e),a=Math.max(0,Math.min(o-1,n));EC(e,a),au(e,t,r)};var iu=(e,t)=>{var C,M,T,A,k,v,w,h,E,W,R,I;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",a=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(C=n==null?void 0:n.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(M=n==null?void 0:n.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!r)return a;let s=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("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=y("div","persona-flex-1 persona-min-w-0"),m=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(A=n==null?void 0:n.title)!=null?A:"Approval Required",m.appendChild(f),!o){let H=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");H.setAttribute("data-approval-status",r.status),r.status==="approved"?(H.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",H.style.color="var(--persona-palette-colors-success-700, #15803d)",H.textContent="Approved"):r.status==="denied"?(H.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",H.style.color="var(--persona-palette-colors-error-700, #b91c1c)",H.textContent="Denied"):r.status==="timeout"&&(H.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",H.style.color="var(--persona-palette-colors-warning-700, #b45309)",H.textContent="Timeout"),m.appendChild(H)}u.appendChild(m);let x=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(x.style.color=n.descriptionColor),x.textContent=r.description,u.appendChild(x),r.parameters){let H=y("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&&(H.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(H.style.color=n.parameterTextColor),H.style.fontSize="0.75rem",H.style.lineHeight="1rem",H.textContent=Ia(r.parameters),u.appendChild(H)}if(o){let H=y("div","persona-flex persona-gap-2 persona-mt-2");H.setAttribute("data-approval-buttons","true");let G=y("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");G.type="button",G.style.backgroundColor=(k=n==null?void 0:n.approveButtonColor)!=null?k:"var(--persona-approval-approve-bg, #22c55e)",G.style.color=(v=n==null?void 0:n.approveButtonTextColor)!=null?v:"#ffffff",G.setAttribute("data-approval-action","approve");let ie=Pe("shield-check",14,(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",2);ie&&(ie.style.marginRight="4px",G.appendChild(ie));let ye=document.createTextNode((h=n==null?void 0:n.approveLabel)!=null?h:"Approve");G.appendChild(ye);let Oe=y("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");Oe.type="button",Oe.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",Oe.style.color=(W=n==null?void 0:n.denyButtonTextColor)!=null?W:"var(--persona-feedback-error, #dc2626)",Oe.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Oe.setAttribute("data-approval-action","deny");let et=Pe("shield-x",14,(R=n==null?void 0:n.denyButtonTextColor)!=null?R:"var(--persona-feedback-error, #dc2626)",2);et&&(et.style.marginRight="4px",Oe.appendChild(et));let be=document.createTextNode((I=n==null?void 0:n.denyLabel)!=null?I:"Deny");Oe.appendChild(be),H.append(G,Oe),u.appendChild(H)}return s.append(i,u),a.appendChild(s),a};var Hx=e=>{let t=[];return{buttons:t,render:(n,o,a,s,i)=>{if(e.innerHTML="",t.length=0,!n||!n.length||(s!=null?s:o?o.getMessages():[]).some(f=>f.role==="user"))return;let p=document.createDocumentFragment(),u=o?o.isStreaming():!1,m=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 x=y("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");x.type="button",x.textContent=f,x.disabled=u,i!=null&&i.fontFamily&&(x.style.fontFamily=m(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",o.sendMessage(f))}),p.appendChild(x),t.push(x)}),e.appendChild(p)}}};var Js=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 Xs=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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(n){r(n)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.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{}}};function ja(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var WC={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)"}},HC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},BC=["flowName","stepName","reasoningText","text","name","tool","toolName"],DC=100;function OC(e,t){let r={...WC,...t};if(r[e])return r[e];for(let n of Object.keys(r))if(n.endsWith("_")&&e.startsWith(n))return r[n];return HC}function _C(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function NC(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"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${n}:${o}.${a}`}function $C(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("."),a=r;for(let s of o)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function FC(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 UC(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 zC(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 a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:o});if(i)return i}return s();function s(){let i=y("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=y("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 lu(e,t,r,n,o,a,s,i){var m;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");ja(l,(m=n.classNames)==null?void 0:m.eventRow);let p=s.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>a(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var G,ie;let f=y("div",""),x=y("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");x.setAttribute("data-event-id",e.id);let C=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Pe(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&C.appendChild(M);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(G=n.timestampFormat)!=null?G:"relative";T.textContent=A==="relative"?_C(e.timestamp,r):NC(e.timestamp);let k=null;n.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let v=OC(e.type,n.badgeColors),w=y("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=v.bg,w.style.color=v.text,w.style.borderColor=v.text+"50",w.textContent=e.type;let h=(ie=n.descriptionFields)!=null?ie:BC,E=$C(e.payload,h),W=null;E&&(W=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=E);let R=y("div","persona-flex-1 persona-min-w-0"),I=y("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"),H=Pe("clipboard","12px","currentColor",1.5);return H&&I.appendChild(H),I.addEventListener("click",async ye=>{ye.stopPropagation(),await FC(UC(e)),I.innerHTML="";let Oe=Pe("check","12px","currentColor",1.5);Oe&&I.appendChild(Oe),setTimeout(()=>{I.innerHTML="";let et=Pe("clipboard","12px","currentColor",1.5);et&&I.appendChild(et)},1500)}),x.appendChild(C),x.appendChild(T),k&&x.appendChild(k),x.appendChild(w),W&&x.appendChild(W),x.appendChild(R),x.appendChild(I),f.appendChild(x),d&&f.appendChild(zC(e,s,i)),f}}function Bx(e){var f,x,C,M,T;let{buffer:t,getFullHistory:r,onClose:n,config:o,plugins:a=[]}=e,s=(f=o==null?void 0:o.features)==null?void 0:f.scrollToBottom,i=(s==null?void 0:s.enabled)!==!1,d=(x=s==null?void 0:s.iconName)!=null?x:"arrow-down",l=(C=s==null?void 0:s.label)!=null?C:"",p=(T=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?T:{},u=a.find(A=>A.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let A=u.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:n});if(A)return{element:A,update:()=>{},destroy:()=>{}}}return m();function m(){let A=p.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ja(k,A==null?void 0:A.panel);let v=[],w="",h="",E=null,W=[],R={},I=0,H=vl(),G=0,ie=0,ye=!1,Oe=null,et=!1,be=0,xe=new Set,Ie=new Map,Je="",X="",Te=null,K,ge,ce,fe,He;function rt(){let N=y("div","persona-flex persona-flex-col persona-flex-shrink-0"),Me=y("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");ja(Me,A==null?void 0:A.headerBar);let ke=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");ke.textContent="Events",K=y("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"),K.textContent="0";let gt=y("div","persona-flex-1");ge=y("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 tt=y("option","");tt.value="",tt.textContent="All events",ge.appendChild(tt),ce=y("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"),ce.type="button",ce.title="Copy All";let dr=Pe("clipboard-copy","12px","currentColor",1.5);dr&&ce.appendChild(dr);let Ot=y("span","persona-text-xs");Ot.textContent="Copy All",ce.appendChild(Ot),Me.appendChild(ke),Me.appendChild(K),Me.appendChild(gt),Me.appendChild(ge),Me.appendChild(ce);let It=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ja(It,A==null?void 0:A.searchBar);let lt=Pe("search","14px","var(--persona-muted, #9ca3af)",1.5),ht=y("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&&ht.appendChild(lt),fe=y("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"),ja(fe,A==null?void 0:A.searchInput),fe.type="text",fe.placeholder="Search event payloads...",He=y("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"),He.type="button",He.style.display="none";let ar=Pe("x","12px","currentColor",2);return ar&&He.appendChild(ar),It.appendChild(ht),It.appendChild(fe),It.appendChild(He),N.appendChild(Me),N.appendChild(It),N}let Q,de=a.find(N=>N.renderEventStreamToolbar);if(de!=null&&de.renderEventStreamToolbar&&o){let N=de.renderEventStreamToolbar({config:o,defaultRenderer:()=>rt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Me=>{w=Me,ae(),Re()},onSearchChange:Me=>{h=Me,ae(),Re()}});Q=N!=null?N:rt()}else Q=rt();let _e=y("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");_e.style.display="none";let Y=y("div","persona-flex-1 persona-min-h-0 persona-relative"),V=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let Ce=y("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");ja(Ce,A==null?void 0:A.scrollIndicator),Ce.style.display="none",Ce.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let Be=Pe(d,"14px","currentColor",2);Be&&Ce.appendChild(Be);let oe=y("span","");oe.textContent=l,Ce.appendChild(oe);let Ee=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ee.style.display="none",Y.appendChild(V),Y.appendChild(Ee),Y.appendChild(Ce),k.setAttribute("tabindex","0"),k.appendChild(Q),k.appendChild(_e),k.appendChild(Y);function we(){let N=t.getAll(),Me={};for(let Ot of N)Me[Ot.type]=(Me[Ot.type]||0)+1;let ke=Object.keys(Me).sort(),gt=ke.length!==W.length||!ke.every((Ot,It)=>Ot===W[It]),tt=!gt&&ke.some(Ot=>Me[Ot]!==R[Ot]),Ut=N.length!==Object.values(R).reduce((Ot,It)=>Ot+It,0);if(!gt&&!tt&&!Ut||(W=ke,R=Me,!ge))return;let dr=ge.value;if(ge.options[0].textContent="All events",gt){for(;ge.options.length>1;)ge.remove(1);for(let Ot of ke){let It=y("option","");It.value=Ot,It.textContent=`${Ot} (${Me[Ot]||0})`,ge.appendChild(It)}dr&&ke.includes(dr)?ge.value=dr:dr&&(ge.value="",w="")}else for(let Ot=1;Ot<ge.options.length;Ot++){let It=ge.options[Ot];It.textContent=`${It.value} (${Me[It.value]||0})`}}function Dt(){let N=t.getAll();if(w&&(N=N.filter(Me=>Me.type===w)),h){let Me=h.toLowerCase();N=N.filter(ke=>ke.type.toLowerCase().includes(Me)||ke.payload.toLowerCase().includes(Me))}return N}function U(){return w!==""||h!==""}function ae(){I=0,G=0,H.resume(),Ce.style.display="none"}function ze(N){xe.has(N)?xe.delete(N):xe.add(N),Te=N;let Me=V.scrollTop,ke=H.isFollowing();et=!0,H.pause(),Re(),V.scrollTop=Me,ke&&H.resume(),et=!1}function he(){return _s(V,50)}function Re(){ie=Date.now(),ye=!1,we();let N=t.getEvictedCount();N>0?(_e.textContent=`${N.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",v=Dt();let Me=v.length,ke=t.getSize()>0;K&&(K.textContent=String(t.getSize())),Me===0&&ke&&U()?(Ee.textContent=h?`No events matching '${h}'`:"No events matching filter",Ee.style.display="",V.style.display="none"):(Ee.style.display="none",V.style.display=""),ce&&(ce.title=U()?`Copy Filtered (${Me})`:"Copy All"),i&&!H.isFollowing()&&Me>I&&(G+=Me-I,oe.textContent=l?`${l}${G>0?` (${G})`:""}`:"",Ce.style.display=""),I=Me;let gt=t.getAll(),tt=gt.length>0?gt[0].timestamp:0,Ut=new Set(v.map(It=>It.id));for(let It of xe)Ut.has(It)||xe.delete(It);let dr=w!==Je||h!==X,Ot=Ie.size===0&&v.length>0;if(dr||Ot||v.length===0){V.innerHTML="",Ie.clear();let It=document.createDocumentFragment();for(let lt=0;lt<v.length;lt++){let ht=lu(v[lt],lt,tt,p,xe,ze,a,o);Ie.set(v[lt].id,ht),It.appendChild(ht)}V.appendChild(It),Je=w,X=h,Te=null}else{if(Te!==null){let lt=Ie.get(Te);if(lt&<.parentNode===V){let ht=v.findIndex(ar=>ar.id===Te);if(ht>=0){let ar=lu(v[ht],ht,tt,p,xe,ze,a,o);V.insertBefore(ar,lt),lt.remove(),Ie.set(Te,ar)}}Te=null}let It=new Set(v.map(lt=>lt.id));for(let[lt,ht]of Ie)It.has(lt)||(ht.remove(),Ie.delete(lt));for(let lt=0;lt<v.length;lt++){let ht=v[lt];if(!Ie.has(ht.id)){let ar=lu(ht,lt,tt,p,xe,ze,a,o);Ie.set(ht.id,ar),V.appendChild(ar)}}}H.isFollowing()&&(V.scrollTop=V.scrollHeight)}function ve(){if(Date.now()-ie>=DC){Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),Re();return}ye||(ye=!0,Oe=requestAnimationFrame(()=>{Oe=null,Re()}))}let ue=(N,Me)=>{if(!ce)return;ce.innerHTML="";let ke=Pe(N,"12px","currentColor",1.5);ke&&ce.appendChild(ke);let gt=y("span","persona-text-xs");gt.textContent="Copy All",ce.appendChild(gt),setTimeout(()=>{ce.innerHTML="";let tt=Pe("clipboard-copy","12px","currentColor",1.5);tt&&ce.appendChild(tt);let Ut=y("span","persona-text-xs");Ut.textContent="Copy All",ce.appendChild(Ut),ce.disabled=!1},Me)},Z=async()=>{if(ce){ce.disabled=!0;try{let N;U()?N=v:r?(N=await r(),N.length===0&&(N=t.getAll())):N=t.getAll();let Me=N.map(ke=>{try{return JSON.parse(ke.payload)}catch{return ke.payload}});await navigator.clipboard.writeText(JSON.stringify(Me,null,2)),ue("check",1500)}catch{ue("x",1500)}}},O=()=>{ge&&(w=ge.value,ae(),Re())},me=()=>{!fe||!He||(He.style.display=fe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{h=fe.value,ae(),Re()},150))},qe=()=>{!fe||!He||(fe.value="",h="",He.style.display="none",E&&clearTimeout(E),ae(),Re())},$e=()=>{if(et)return;let N=V.scrollTop,{action:Me,nextLastScrollTop:ke}=Al({following:H.isFollowing(),currentScrollTop:N,lastScrollTop:be,nearBottom:he(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=ke,Me==="resume"?(H.resume(),G=0,Ce.style.display="none"):Me==="pause"&&(H.pause(),i&&(oe.textContent=l,Ce.style.display=""))},Xe=N=>{let Me=Sl({following:H.isFollowing(),deltaY:N.deltaY,nearBottom:he(),resumeWhenNearBottom:!0});Me==="pause"?(H.pause(),i&&(oe.textContent=l,Ce.style.display="")):Me==="resume"&&(H.resume(),G=0,Ce.style.display="none")},mt=()=>{i&&(V.scrollTop=V.scrollHeight,H.resume(),G=0,Ce.style.display="none")},ct=N=>{let Me=N.target;if(!Me||Me.closest("button"))return;let ke=Me.closest("[data-event-id]");if(!ke)return;let gt=ke.getAttribute("data-event-id");gt&&ze(gt)},yt=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}N.key==="Escape"&&(fe&&document.activeElement===fe?(qe(),fe.blur(),k.focus()):n&&n())};ce&&ce.addEventListener("click",Z),ge&&ge.addEventListener("change",O),fe&&fe.addEventListener("input",me),He&&He.addEventListener("click",qe),V.addEventListener("scroll",$e),V.addEventListener("wheel",Xe,{passive:!0}),V.addEventListener("click",ct),Ce.addEventListener("click",mt),k.addEventListener("keydown",yt);function jt(){E&&clearTimeout(E),Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),ye=!1,Ie.clear(),ce&&ce.removeEventListener("click",Z),ge&&ge.removeEventListener("change",O),fe&&fe.removeEventListener("input",me),He&&He.removeEventListener("click",qe),V.removeEventListener("scroll",$e),V.removeEventListener("wheel",Xe),V.removeEventListener("click",ct),Ce.removeEventListener("click",mt),k.removeEventListener("keydown",yt)}return{element:k,update:ve,destroy:jt}}}function Dx(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",s=(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 m=document.createElement("span");m.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",m.style.backgroundColor="var(--persona-primary, #171717)",m.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(m);let f=document.createElement("span");f.textContent=`Generating ${s.toLowerCase()}...`,u.appendChild(f)}else u.textContent=s;if(l.append(p,u),i.append(d,l),o==="complete"){let m=document.createElement("button");m.type="button",m.textContent="Download",m.title=`Download ${r}`,m.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-text, #1f2937)",m.style.backgroundColor="transparent",m.style.cursor="pointer",m.setAttribute("data-download-artifact",n),i.append(m)}return i}var Ox=(e,t)=>{var n,o,a;let r=(a=(o=(n=t==null?void 0:t.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:a.renderCard;if(r){let s=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:s,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Dx(e,t)});if(p)return p}return Dx(e,t)};var du=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)})}},ho=new du;ho.register("PersonaArtifactCard",Ox);function qC(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=y("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let n=y("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 _x(e,t){var ce,fe,He,rt;let r=(fe=(ce=e.features)==null?void 0:ce.artifacts)==null?void 0:fe.layout,o=((He=r==null?void 0:r.toolbarPreset)!=null?He:"default")==="document",a=(rt=r==null?void 0:r.panePadding)==null?void 0:rt.trim(),s=e.markdown?ra(e.markdown):null,i=ka(e.sanitize),d=Q=>{let de=s?s(Q):na(Q);return i?i(de):de},l=typeof document!="undefined"?y("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"),H==null||H.hide()};l&&l.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let u=y("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 m=y("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");m.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&m.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let C="rendered",M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?rr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):rr({icon:"eye",label:"Rendered view"}),A=o?rr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):rr({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),v=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,h=r==null?void 0:r.documentToolbarCopyMenuItems,E=!!(w&&h&&h.length>0),W=null,R,I=null,H=null;if(o&&(v||w)&&!E){if(R=v?Vs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):rr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let Q=Pe("chevron-down",14,"currentColor",2);Q&&R.appendChild(Q)}}else o&&E?(W=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),R=v?Vs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):rr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I=rr({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,I)):o?R=rr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):R=rr({icon:"copy",label:"Copy"});let G=o?rr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):rr({icon:"refresh-cw",label:"Refresh"}),ie=o?rr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):rr({icon:"x",label:"Close"}),ye=()=>{var V,Ce,Be;let Q=(V=Je.find(oe=>oe.id===X))!=null?V:Je[Je.length-1],de=(Ce=Q==null?void 0:Q.id)!=null?Ce:null,_e=(Q==null?void 0:Q.artifactType)==="markdown"&&(Be=Q.markdown)!=null?Be:"",Y=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:_e,jsonPayload:Y,id:de}},Oe=async()=>{var V;let{markdown:Q,jsonPayload:de}=ye(),_e=(V=Je.find(Ce=>Ce.id===X))!=null?V:Je[Je.length-1],Y=(_e==null?void 0:_e.artifactType)==="markdown"?Q:_e?de:"";try{await navigator.clipboard.writeText(Y)}catch{}};if(R.addEventListener("click",async()=>{let Q=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(Q&&E){let{markdown:de,jsonPayload:_e,id:Y}=ye();try{await Q({actionId:"primary",artifactId:Y,markdown:de,jsonPayload:_e})}catch{}return}await Oe()}),I&&(h!=null&&h.length)){let Q=()=>{var _e;return(_e=u.closest("[data-persona-root]"))!=null?_e:document.body},de=()=>{H=Ho({items:h.map(_e=>({id:_e.id,label:_e.label})),onSelect:async _e=>{let{markdown:Y,jsonPayload:V,id:Ce}=ye(),Be=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Be?await Be({actionId:_e,artifactId:Ce,markdown:Y,jsonPayload:V}):_e==="markdown"||_e==="md"?await navigator.clipboard.writeText(Y):_e==="json"||_e==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(Y||V)}catch{}},anchor:W!=null?W:I,position:"bottom-right",portal:Q()})};u.isConnected?de():requestAnimationFrame(de),I.addEventListener("click",_e=>{_e.stopPropagation(),H==null||H.toggle()})}G.addEventListener("click",async()=>{var Q;try{await((Q=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:Q.call(r))}catch{}K()}),ie.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let et=()=>{o&&(T.setAttribute("aria-pressed",C==="rendered"?"true":"false"),A.setAttribute("aria-pressed",C==="source"?"true":"false"))};T.addEventListener("click",()=>{C="rendered",et(),K()}),A.addEventListener("click",()=>{C="source",et(),K()});let be=y("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?(m.replaceChildren(),M.append(T,A),W?k.append(W,G,ie):k.append(R,G,ie),m.append(M,be,k),et()):(m.appendChild(f),m.appendChild(x)),a&&(m.style.paddingLeft=a,m.style.paddingRight=a);let xe=y("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"),Ie=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(xe.style.paddingLeft=a,xe.style.paddingRight=a,Ie.style.padding=a),u.appendChild(m),u.appendChild(xe),u.appendChild(Ie);let Je=[],X=null,Te=!1,K=()=>{var Y,V,Ce,Be;let Q=o&&Je.length<=1;xe.classList.toggle("persona-hidden",Q),xe.replaceChildren();for(let oe of Je){let Ee=y("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");Ee.type="button",Ee.textContent=oe.title||oe.id.slice(0,8),oe.id===X&&Ee.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ee.addEventListener("click",()=>t.onSelect(oe.id)),xe.appendChild(Ee)}Ie.replaceChildren();let de=X&&Je.find(oe=>oe.id===X)||Je[Je.length-1];if(!de)return;if(o){let oe=de.artifactType==="markdown"?"MD":(Y=de.component)!=null?Y:"Component",we=(de.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";be.textContent=`${we} \xB7 ${oe}`}else f.textContent="Artifacts";if(de.artifactType==="markdown"){if(o&&C==="source"){let Ee=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ee.textContent=(V=de.markdown)!=null?V:"",Ie.appendChild(Ee);return}let oe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");oe.innerHTML=d((Ce=de.markdown)!=null?Ce:""),Ie.appendChild(oe);return}let _e=de.component?ho.get(de.component):void 0;if(_e){let Ee={message:{id:de.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let we=_e((Be=de.props)!=null?Be:{},Ee);if(we){Ie.appendChild(we);return}}catch{}}Ie.appendChild(qC(de))},ge=()=>{var de;let Q=Je.length>0;if(u.classList.toggle("persona-hidden",!Q),l){let _e=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,V=((de=_e==null?void 0:_e.classList.contains("persona-artifact-narrow-host"))!=null?de:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&V&&Te?(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(Q){var de,_e,Y;Je=Q.artifacts,X=(Y=(_e=Q.selectedId)!=null?_e:(de=Q.artifacts[Q.artifacts.length-1])==null?void 0:de.id)!=null?Y:null,Je.length>0&&(Te=!0),K(),ge()},setMobileOpen(Q){Te=Q,!Q&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ge()}}}function En(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 Nx(e,t){var a,s,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"),!En(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.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 jC(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 Ul(e,t){var d,l,p,u,m,f,x,C,M,T;if(!En(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"),jC(e),Nx(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",(m=r==null?void 0:r.paneMaxWidth)!=null?m:"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=(f=r==null?void 0:r.paneBackground)==null?void 0:f.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let o=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let a=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(M=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:M.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):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"),Nx(e,t)}var $x=["panel","seamless"];function zl(e,t){var i,d,l,p,u,m;for(let f of $x)e.classList.remove(`persona-artifact-appearance-${f}`);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"),!En(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=$x.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(u=r==null?void 0:r.paneShadow)==null?void 0:u.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((m=r.unifiedSplitOuterRadius)==null?void 0:m.trim())||a;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Fx(e,t){var r,n,o;return!t||!En(e)?!1:((o=(n=(r=e.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function VC(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 GC(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 KC(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function JC(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}function Ux(e,t){var s;let n=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function zx(e,t,r,n,o,a){let s=VC(o,200),i=JC(t,r,n,200);i=Math.max(s,i);let d=GC(a);return d!==null&&(i=Math.min(i,d)),KC(e,s,i)}var qx={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"}},cu=(e,t,r,n)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(a=>{var x,C,M;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=qx[s])!=null?C:qx.init;a.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=y("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,E;let A=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${T.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,A.appendChild(k);let v=(h=T.type)!=null?h:"text",w;v==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=v),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}-${s}-${T.name}`,w.name=T.name,w.placeholder=(E=T.placeholder)!=null?E:"",T.required&&(w.required=!0),A.appendChild(w),p.appendChild(A)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("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=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(m),u.appendChild(f),p.appendChild(u),a.replaceChildren(d,p),p.addEventListener("submit",async T=>{var w,h;T.preventDefault();let A=(w=r.formEndpoint)!=null?w:"/form",k=new FormData(p),v={};k.forEach((E,W)=>{v[W]=E}),v.type=s,f.disabled=!0,m.textContent="Submitting\u2026";try{let E=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let W=await E.json();m.textContent=(h=W.message)!=null?h:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await n.sendMessage(String(W.nextPrompt))}catch(E){m.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var pu=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(a=>a.id));return[...r.filter(a=>!n.has(a.id)),...t].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Ys=new pu;var jx=()=>{let e=new Map,t=(o,a)=>(e.has(o)||e.set(o,new Set),e.get(o).add(a),()=>r(o,a)),r=(o,a)=>{var s;(s=e.get(o))==null||s.delete(a)};return{on:t,off:r,emit:(o,a)=>{var s;(s=e.get(o))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var XC=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},YC=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 a=t[o];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(r,o+1)}return null},Qs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=XC(e),r=YC(t);if(!r)return null;let n=JSON.parse(r);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},uu=e=>typeof e=="string"?e:e==null?"":String(e),ma={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:uu(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,n=uu(r.element);if(n&&((o=t.document)!=null&&o.querySelector)){let a=t.document.querySelector(n);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:uu(r.text)}}},Vx=e=>Array.isArray(e)?e.map(t=>String(t)):[],Zs=e=>{let t=new Set(Vx(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Vx(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),n();let d={action:i,message:a.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:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let m=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:m,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var QC=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}},ZC=e=>e.map(t=>({...t,streaming:!1})),ev=e=>e.map(t=>({...t,status:"complete"})),ql=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?QC(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let o={...r,messages:r.messages?ZC(r.messages):void 0,artifacts:r.artifacts?ev(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 Va=ld(Ui(),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 rv(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,Va.parse)(r,Va.STR|Va.OBJ),a=rv(o,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Gx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Vl(e,t){let{config:r,message:n,onPropsUpdate:o}=t,a=ho.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:n,config:r,updateProps:i=>{o&&o(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Kx(){let e=jl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Jx(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 Gl(e){let t=Jx(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 Kl(e){let t=Jx(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 nv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Jl(e){let{onSubmit:t,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=nv}=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,m=document.createElement("div");m.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,f.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=o,f.appendChild(C),m.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let h=1;h<=5;h++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${h} star${h>1?"s":""}: ${l[h-1]}`),E.title=l[h-1],E.dataset.rating=String(h),E.innerHTML=`
|
|
73
|
+
`,r.addEventListener("click",t);let n=s=>{var M,v,b,x,E,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=(v=a.title)!=null?v:"Chat Assistant";d.textContent=we,d.setAttribute("title",we)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let we=(b=a.subtitle)!=null?b:"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=(x=a.agentIconSize)!=null?x:"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=(E=a.agentIconText)!=null?E:"\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 m=r.querySelector("[data-role='launcher-image']");if(m){let we=(H=a.agentIconSize)!=null?H:"40px";m.style.height=we,m.style.width=we,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(m.src=a.iconUrl,m.style.display="block"):m.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let we=(W=a.callToActionIconSize)!=null?W:"32px";f.style.height=we,f.style.width=we,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 Te=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Te=(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 We=parseFloat(we)||24,Oe=Math.max(We-Te,8),K=Pe(a.callToActionIconName,Oe,"currentColor",2);K?f.appendChild(K):f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else f.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}let y=a.position&&Fn[a.position]?Fn[a.position]:Fn["bottom-right"],C="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",k="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?k:`${C} ${y}`,i||(r.style.zIndex=String((se=a.zIndex)!=null?se:qr));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=(ve=a.border)!=null?ve:T,r.style.boxShadow=(Ue=a.shadow)!=null?Ue: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",t),r.remove()};return e&&n(e),{element:r,update:n,destroy:o}};var Qw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Rl=(e,t={})=>{var C,k,T,S,M,v;let{showClose:r=!0,wrapperClassName:n=Qw,buttonSize:o,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(k=o!=null?o:a.closeButtonSize)!=null?k:"32px",d=h("div",n),l=h("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=(S=a.closeButtonShowTooltip)!=null?S:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let m=(M=a.closeButtonIconName)!=null?M:"x",f=(v=a.closeButtonIconText)!=null?v:"\xD7";l.style.color=a.closeButtonColor||en.actionIconColor;let y=Pe(m,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",x=a.closeButtonBorderColor||"transparent";l.style.border=`${b} solid ${x}`,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 b=null,x=()=>{if(b)return;let B=l.ownerDocument,H=B.body;if(!H)return;b=Yn(B,"div","persona-clear-chat-tooltip"),b.textContent=p;let W=Yn(B,"div");W.className="persona-clear-chat-tooltip-arrow",b.appendChild(W);let N=l.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Ro),b.style.left=`${N.left+N.width/2}px`,b.style.top=`${N.top-8}px`,b.style.transform="translate(-50%, -100%)",H.appendChild(b)},E=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};d.addEventListener("mouseenter",x),d.addEventListener("mouseleave",E),l.addEventListener("focus",x),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",x),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",x),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},Zw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wl=(e,t={})=>{var b,x,E,B,H,W,N,q,se,ve,Ue,je,we;let{wrapperClassName:r=Zw,buttonSize:n,iconSize:o="20px"}=t,a=(x=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?x:{},i=(E=n!=null?n:a.size)!=null?E:"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:"",m=(q=a.borderColor)!=null?q:"",f=(se=a.borderRadius)!=null?se:"",y=(ve=a.paddingX)!=null?ve:"",C=(Ue=a.paddingY)!=null?Ue:"",k=(je=a.tooltipText)!=null?je:"Clear chat",T=(we=a.showTooltip)!=null?we:!0,S=h("div",r),M=h("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",k),M.style.color=l||en.actionIconColor;let v=Pe(d,o,"currentColor",1);if(v&&(v.style.display="block",M.appendChild(v)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),u||m){let Te=u||"0px",We=m||"transparent";M.style.border=`${Te} solid ${We}`,M.classList.remove("persona-border-none")}if(f&&(M.style.borderRadius=f,M.classList.remove("persona-rounded-full")),y&&(M.style.paddingLeft=y,M.style.paddingRight=y),C&&(M.style.paddingTop=C,M.style.paddingBottom=C),S.appendChild(M),T&&k){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=k;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)};S.addEventListener("mouseenter",We),S.addEventListener("mouseleave",Oe),M.addEventListener("focus",We),M.addEventListener("blur",Oe),S._cleanupTooltip=()=>{Oe(),S.removeEventListener("mouseenter",We),S.removeEventListener("mouseleave",Oe),M.removeEventListener("focus",We),M.removeEventListener("blur",Oe)}}return{button:M,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=e=>{var b,x,E,B,H,W,N,q,se,ve,Ue,je,we,Te,We,Oe;let{config:t,showClose:r=!0}=e,n=h("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=t==null?void 0:t.launcher)!=null?b:{},s=(x=o.headerIconSize)!=null?x:"48px",a=(E=o.closeButtonPlacement)!=null?E:"inline",i=(B=o.headerIconHidden)!=null?B:!1,d=o.headerIconName,l=h("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=h("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=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=h("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 m=h("span","persona-text-xs");m.style.color=en.subtitleColor,m.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,m),i?n.append(p):n.append(l,p);let f=(Te=o.clearChat)!=null?Te:{},y=(We=f.enabled)!=null?We:!0,C=(Oe=f.placement)!=null?Oe:"inline",k=null,T=null;if(y){let He=Wl(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=He.button,T=He.wrapper,C==="top-right"&&(T.style.right="48px"),C==="inline"&&n.appendChild(T)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="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:v}=Rl(t,{showClose:r,wrapperClassName:S});return a!=="top-right"&&n.appendChild(v),{header:n,iconHolder:l,headerTitle:u,headerSubtitle:m,closeButton:M,closeButtonWrapper:v,clearChatButton:k,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=h("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 t){if(f.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}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 k=Pe(f.icon,16,"currentColor",1.5);k&&y.appendChild(k)}let C=document.createElement("span");C.textContent=f.label,y.appendChild(C),y.addEventListener("click",k=>{k.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 u(){a.classList.contains("persona-hidden")?l():p()}function m(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:m}}function ir(e){let{icon:t,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("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=h("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let m=Pe(t,s!=null?s:14,"currentColor",2);m&&p.appendChild(m)}let u=h("span");if(u.textContent=r,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[m,f]of Object.entries(d))p.setAttribute(m,f);return p}function Xa(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,s=h("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=h("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 f,y;let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=h("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=h("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=(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 C,k;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let m=Bo({items:n,onSelect:C=>{l.setAttribute("aria-expanded","false"),o(C)},anchor:l,position:s,portal:a});return a||l.appendChild(m.element),l.addEventListener("click",C=>{C.stopPropagation();let k=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"false":"true"),m.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{p.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),m.show()},close:()=>{l.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let C=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),m.toggle()},destroy:()=>{m.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 eC(e,t,r){var n,o,s;if(t!=null&&t.length)for(let a of t){let i=h("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=h("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 S,M,v,b,x,E,B,H,W;let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(S=t==null?void 0:t.launcher)!=null?S:{},i=h("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=(v=l.querySelector(".persona-combo-btn-label"))!=null?v:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("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),eC(l,o==null?void 0:o.trailingActions,(x=o==null?void 0:o.onAction)!=null?x: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=(E=N.borderRadius)!=null?E:"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",m=h("div",""),f=h("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=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=a.closeButtonColor||en.actionIconColor;let y=(W=a.closeButtonIconName)!=null?W:"x",C=Pe(y,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",n&&f.addEventListener("click",n),m.appendChild(f),i.appendChild(m);let k=h("div");k.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:k,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:m,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=h("div");p.style.display="none";let u=h("span"),m=h("span"),f=h("button");f.style.display="none";let y=h("div");return y.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:m,closeButton:f,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=h("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 b,x,E,B,H,W,N,q,se,ve,Ue,je;let t=(b=e==null?void 0:e.sendButton)!=null?b:{},r=(x=t.useIcon)!=null?x:!1,n=(E=t.iconText)!=null?E:"\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",m=t.backgroundColor,f=t.textColor,y=h("div","persona-send-button-wrapper"),C=h("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");C.type="submit",C.setAttribute("data-persona-composer-submit","");let k=null,T=null;if(r){C.style.width=u,C.style.height=u,C.style.minWidth=u,C.style.minHeight=u,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",f?C.style.color=f:C.style.color="var(--persona-button-primary-fg, #ffffff)";let we=parseFloat(u)||24,Te=(f==null?void 0:f.trim())||"currentColor";o?(k=Pe(o,we,Te,2),k?C.appendChild(k):C.textContent=n):C.textContent=n,T=Pe(s,we,Te,2),m?C.style.backgroundColor=m:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,f?C.style.color=f:C.classList.add("persona-text-white");t.borderWidth&&(C.style.borderWidth=t.borderWidth,C.style.borderStyle="solid"),t.borderColor&&(C.style.borderColor=t.borderColor),t.paddingX?(C.style.paddingLeft=t.paddingX,C.style.paddingRight=t.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),t.paddingY?(C.style.paddingTop=t.paddingY,C.style.paddingBottom=t.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let S=null;p&&a&&(S=h("div","persona-send-button-tooltip"),S.textContent=a,y.appendChild(S)),C.setAttribute("aria-label",a),y.appendChild(C);let M="send";return{button:C,wrapper:y,setMode:we=>{if(we===M)return;M=we;let Te=we==="stop"?i:a;if(C.setAttribute("aria-label",Te),S&&(S.textContent=Te),r){if(k&&T){let We=we==="stop"?T:k;C.replaceChildren(We)}}else C.textContent=we==="stop"?l:d}}},_l=e=>{var S,M,v,b,x,E,B,H,W,N,q,se;let t=(S=e==null?void 0:e.voiceRecognition)!=null?S:{};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=(b=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?b:"40px",i=h("div","persona-send-button-wrapper"),d=h("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=(x=t.iconName)!=null?x:"mic",p=(E=t.iconSize)!=null?E:a,u=parseFloat(p)||24,m=(H=t.backgroundColor)!=null?H:(B=e==null?void 0:e.sendButton)==null?void 0:B.backgroundColor,f=(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",f?d.style.color=f:d.style.color="var(--persona-text, #111827)";let C=Pe(l,u,f||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",m&&(d.style.backgroundColor=m),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 k=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((se=t.showTooltip)!=null?se:!1)&&k){let ve=h("div","persona-send-button-tooltip");ve.textContent=k,i.appendChild(ve)}return{button:d,wrapper:i}},Nl=e=>{var y,C,k,T,S,M,v,b;let t=(y=e==null?void 0:e.attachments)!=null?y:{};if(t.enabled!==!0)return null;let r=(k=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?k:"40px",n=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=h("input");o.type="file",o.accept=((T=t.allowedTypes)!=null?T:mo).join(","),o.multiple=((S=t.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=h("div","persona-send-button-wrapper"),a=h("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=(v=t.buttonIconName)!=null?v:"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",x=>{x.preventDefault(),o.click()}),s.appendChild(a);let m=(b=t.buttonTooltipText)!=null?b:"Attach file",f=h("div","persona-send-button-tooltip");return f.textContent=m,s.appendChild(f),{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=h("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=h("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=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Fs=e=>{var y,C,k,T,S,M;let{config:t}=e,r=h("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=h("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=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),m=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&m.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(m,f),o.append(u),o.addEventListener("click",v=>{v.target!==i.button&&v.target!==i.wrapper&&v.target!==(d==null?void 0:d.button)&&v.target!==(d==null?void 0:d.wrapper)&&v.target!==(l==null?void 0:l.button)&&v.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:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(S=l==null?void 0:l.input)!=null?S:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var yx=()=>{let e=h("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=h("span","persona-pill-peek__icon"),r=Pe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let n=h("span","persona-pill-peek__text"),o=h("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}},bx=e=>{var y,C,k,T,S,M;let{config:t}=e,r=h("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=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let m=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&m.append(d.wrapper),m.append(i.wrapper),p.addEventListener("click",v=>{v.target!==i.button&&v.target!==i.wrapper&&v.target!==(d==null?void 0:d.button)&&v.target!==(d==null?void 0:d.wrapper)&&v.target!==(l==null?void 0:l.button)&&v.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,m),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:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:o,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(S=l==null?void 0:l.input)!=null?S:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var wx=e=>{var p,u,m,f,y,C,k,T,S,M,v,b,x,E,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=(f=(m=e==null?void 0:e.launcher)==null?void 0:m.composerBar)!=null?f:{},q=h("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((k=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?k:qr);let se=h("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=h("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=(S=e==null?void 0:e.launcher)==null?void 0:S.zIndex)!=null?M:qr),{wrapper:q,panel:se,pillRoot:ve}}if(r){let N=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=h("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=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(b=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?b:"100%";return N.style.width=se,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let o=(x=e==null?void 0:e.launcher)!=null?x:{},s=o.position&&Fn[o.position]?Fn[o.position]:Fn["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((B=(E=e==null?void 0:e.launcher)==null?void 0:E.zIndex)!=null?B:qr);let i=h("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}},tC=(e,t)=>{var v,b,x,E,B,H,W,N,q;let r=h("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=(x=(b=(v=e==null?void 0:e.launcher)==null?void 0:v.clearChat)==null?void 0:b.enabled)!=null?x:!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=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("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=h("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=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(B=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeTitle)!=null?B:"Hello \u{1F44B}";let m=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");m.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,m);let f=h("div","persona-flex persona-flex-col persona-gap-3"),y=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;y&&(f.style.maxWidth=y,f.style.marginLeft="auto",f.style.marginRight="auto",f.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,f);let k=h("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let T=bx({config:e}),{root:S,textNode:M}=yx();return r.append(d,o,l,k),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:f,composerOverlay:k,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:m,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("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:M}},Cx=(e,t=!0)=>{var k,T,S,M,v,b,x,E,B;if(Ho(e))return tC(e,t);let r=h("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=(k=e==null?void 0:e.layout)==null?void 0:k.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=h("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=h("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=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(M=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(b=(v=e==null?void 0:e.copy)==null?void 0:v.welcomeSubtitle)!=null?b:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),u=(x=e==null?void 0:e.layout)==null?void 0:x.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let f=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 C=h("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",y||(f.footer.style.display="none"),r.append(f.footer),r.append(C),{container:r,body:a,messagesWrapper:p,composerOverlay:C,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 rC=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}},nC=(e,t)=>{if(!e)return null;let r=rC(e);if(r===null)return null;let n=t==null?void 0:t[e],o=n!==void 0?n:r;return o||null},oC=(e,t)=>{let r=h("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},sC=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,Ax=320,aC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),iC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),lC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),dC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),cC=(e,t,r)=>{if(e.length===0)return null;try{let n=h("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=h("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=`${Ax}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}),sC(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}},pC=e=>{if(e.length===0)return null;try{let t=h("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=h("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}},uC=e=>{if(e.length===0)return null;try{let t=h("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=h("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=`${Ax}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}},fC=e=>{if(e.length===0)return null;try{let t=h("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=h("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()},mC=(e,t)=>{let r=h("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=h("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},vx=(e,t)=>{let r=h("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},gC=(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 f,y,C,k,T,S;let n=(f=t.showCopy)!=null?f:!0,o=(y=t.showUpvote)!=null?y:!0,s=(C=t.showDownvote)!=null?C:!0;if(!n&&!o&&!s){let M=h("div");return M.style.display="none",M.id=`actions-${e.id}`,M.setAttribute("data-actions-for",e.id),M}let a=(k=t.visibility)!=null?k:"hover",i=(T=t.align)!=null?T:"right",d=(S=t.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],u=h("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 m=(M,v,b)=>{let x=ir({icon:M,label:v,size:14,className:"persona-message-action-btn"});return x.setAttribute("data-action",b),x};return n&&u.appendChild(m("copy","Copy message","copy")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("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,m=(Ce=d==null?void 0:d.position)!=null?Ce:"left",f=(Z=l==null?void 0:l.position)!=null?Z:"below",y=gC(e.role,i),C=h("div",y.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=aC(e),T=(xe=(he=e.content)==null?void 0:he.trim())!=null?xe:"",M=k.length>0&&T===rl,v=El((G=(Ve=s==null?void 0:s.widgetConfig)==null?void 0:Ve.features)==null?void 0:G.streamAnimation),b=(ye=(Ie=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:Ie.streamAnimation)==null?void 0:ye.plugins,x=e.role==="assistant"&&v.type!=="none"?qa(v.type,b):null,E=e.role==="assistant"&&((pe=x==null?void 0:x.isAnimating)==null?void 0:pe.call(x,e))===!0,B=e.role==="assistant"&&x!==null&&(!!e.streaming||E);B&&(x!=null&&x.bubbleClass)&&C.classList.add(x.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),B&&x&&(x.containerClass&&H.classList.add(x.containerClass),H.style.setProperty("--persona-stream-step",`${v.speed}ms`),H.style.setProperty("--persona-stream-duration",`${v.duration}ms`));let W=B?Ll((le=e.content)!=null?le:"",v.buffer,x,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",N=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;B&&(x==null?void 0:x.wrap)==="char"?q=ja(N,"char",e.id,{skipTags:x.skipTags}):B&&(x==null?void 0:x.wrap)==="word"&&(q=ja(N,"word",e.id,{skipTags:x.skipTags}));let se=null;if(M?(se=document.createElement("div"),se.innerHTML=q,se.style.display="none",H.appendChild(se)):H.innerHTML=q,B&&(x!=null&&x.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&&f==="inline"&&e.createdAt){let J=vx(e,l);J.classList.add("persona-ml-2","persona-inline"),H.appendChild(J)}if(k.length>0){let J=cC(k,!M&&!!T,()=>{M&&se&&(se.style.display="")});J?C.appendChild(J):M&&se&&(se.style.display="")}let ve=iC(e);if(ve.length>0){let J=pC(ve);J&&C.appendChild(J)}let Ue=lC(e);if(Ue.length>0){let J=uC(Ue);J&&C.appendChild(J)}let je=dC(e);if(je.length>0){let J=fC(je);J&&C.appendChild(J)}if(C.appendChild(H),u&&f==="below"&&e.createdAt){let J=vx(e,l);J.classList.add("persona-mt-1"),C.appendChild(J)}let we=e.role==="assistant"?nC(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=v.placeholder==="skeleton",ne=Ke&&v.buffer==="line"&&J;if(J)ne&&C.appendChild(Va());else if(Ke)C.appendChild(Va());else{let Y=eu("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Y&&C.appendChild(Y)}}if(we&&e.stopReason&&!e.streaming&&(T||(H.style.display="none"),C.appendChild(oC(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);C.appendChild(J)}if(!p||e.role==="system")return C;let We=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Oe=mC(d,e.role);return m==="right"||m==="left"&&e.role==="user"?We.append(C,Oe):We.append(Oe,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),We},Sx=(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,hC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),xC=(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
|
+
`):""},Tx=(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=h("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=xC(e,(we=o.previewMaxLines)!=null?we:3),l=h("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=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),m="Thinking...",f=(Te=t==null?void 0:t.reasoning)!=null?Te:{},y=String((We=r.startedAt)!=null?We:Date.now()),C=()=>{let he=h("span","");return he.setAttribute("data-tool-elapsed",y),he.textContent=Ki(r),he},k=(Oe=f.renderCollapsedSummary)==null?void 0:Oe.call(f,{message:e,reasoning:r,defaultSummary:m,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ki(r),createElapsedElement:C});typeof k=="string"&&k.trim()?(u.textContent=k,p.appendChild(u)):k instanceof HTMLElement?p.appendChild(k):(u.textContent=m,p.appendChild(u));let T=h("span","persona-text-xs persona-text-persona-primary");T.textContent=$h(r),p.appendChild(T);let S=(K=o.loadingAnimation)!=null?K:"none",M=f.activeTextTemplate,v=f.completeTextTemplate,b=i?M:v,x=k instanceof HTMLElement,E=(he,xe,Ve)=>{let G=Ve;for(let ee of xe){let Ie=h("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=h("span",ee.styles.map(pe=>`persona-tool-text-${pe}`).join(" "));return u.appendChild(ye),ye})():u;if(ee.isDuration&&i)Ie.appendChild(C());else{let ye=ee.isDuration?Ki(r):ee.text;xe?G=E(Ie,ye,G):Ie.appendChild(document.createTextNode(ye))}}};if(!x&&b)if(T.style.display="none",u.style.display="",i&&S!=="none"){let he=(He=f.loadingAnimationDuration)!=null?He:2e3;u.setAttribute("data-preserve-animation","true"),S==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),B(b,!1)):(u.classList.add(`persona-tool-loading-${S}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),S==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),B(b,!0))}else B(b,!1);else if(!x&&i&&S!=="none"){u.style.display="";let he=(j=f.loadingAnimationDuration)!=null?j:2e3;if(u.setAttribute("data-preserve-animation","true"),S==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${S}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),S==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let xe=u.textContent||m;u.textContent="",E(u,xe,0)}r.status==="complete"&&(u.style.display="none")}else x||(r.status==="complete"?u.style.display="none":u.style.display="");let H=null;if(s){H=h("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=h("div","persona-flex persona-items-center persona-ml-auto");Ve.append(H),l.append(p,Ve)}else l.append(p);let W=h("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:{}});hC(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=h("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=h("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,yC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),bC=(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
|
+
`):""},wC=(e,t)=>{var p,u,m,f,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=bC(e,(m=n==null?void 0:n.previewMaxLines)!=null?m:3),a=r?Fh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(f=t==null?void 0:t.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=$d(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=$d(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Mx=(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",m=Pe(n?"chevron-up":"chevron-down",16,u,2);m?l.appendChild(m):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=h("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}=wC(e,t),u=h("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 m=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let y=String((Ue=r.startedAt)!=null?Ue:Date.now()),C=()=>{let K=h("span","");return K.setAttribute("data-tool-elapsed",y),K.textContent=Ha(r),K},k=(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:C});typeof k=="string"&&k.trim()?(f.textContent=k,m.appendChild(f)):k instanceof HTMLElement?m.appendChild(k):(f.textContent=d,m.appendChild(f));let T=(Te=s.loadingAnimation)!=null?Te:"none",S=n.activeTextTemplate,M=n.completeTextTemplate,v=p?S:M,b=k instanceof HTMLElement,x=(K,He,j)=>{let Ce=j;for(let Z of He){let he=h("span","persona-tool-char");he.style.setProperty("--char-index",String(Ce)),he.textContent=Z===" "?"\xA0":Z,K.appendChild(he),Ce++}return Ce},E=(K,He)=>{var he;f.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=h("span",xe.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(G),G})():f;if(xe.isDuration&&p)Ve.appendChild(C());else{let G=xe.isDuration?Ha(r):xe.text;He?Z=x(Ve,G,Z):Ve.appendChild(document.createTextNode(G))}}};if(!b)if(p&&T!=="none"){let K=(We=n.loadingAnimationDuration)!=null?We:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),v&&E(v,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${K}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)),v)E(v,!0);else{let He=f.textContent||d;f.textContent="",x(f,He,0)}}else v&&E(v,!1);let B=null;if(a){B=h("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=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");j.append(B),u.append(m,j)}else u.append(m);let H=h("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:{}});yC(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=h("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=h("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=h("div","persona-space-y-1"),He=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(He.style.color=n.labelTextColor),He.textContent="Arguments";let j=h("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=h("div","persona-space-y-1"),He=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(He.style.color=n.labelTextColor),He.textContent="Activity";let j=h("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=h("div","persona-space-y-1"),He=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(He.style.color=n.labelTextColor),He.textContent="Result";let j=h("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=h("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",CC="Other",vC="Other\u2026",Ex="Type your own answer here",Lx="Send",AC="Next",SC="Back",TC="Submit all",MC="Skip",kC=3,au="data-ask-current-index",iu="data-ask-question-count",Px="data-ask-answers",lu="data-ask-grouped",Ix="data-ask-layout",EC=e=>e.layout==="pills"?"pills":"rows",LC=e=>e.getAttribute(Ix)==="pills"?"pills":"rows",kx=!1,Rx=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&&!kx&&(kx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ou}.`)),t.slice(0,ou)},PC=e=>{var t;return(t=Ya(e)[0])!=null?t:null},IC=(e,t)=>{var r;return(r=Ya(e)[t])!=null?r:null},Wx=(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))},Hx=(e,t,r)=>{if(e!=="rows")return null;let n=h("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let o=h("span","persona-ask-row-check");n.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},RC=(e,t,r,n)=>{let s=h("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=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Hx(r,n,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},WC=e=>{let r=h("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},HC=(e,t,r,n)=>{var p,u,m;let s=h("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(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!r){for(let f=0;f<kC;f++)s.appendChild(WC(n));return s}if(d.forEach((f,y)=>{s.appendChild(RC(f,y,n,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=n==="rows"?CC:vC;if(n==="rows"){let y=h("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 C=h("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(p=t.freeTextPlaceholder)!=null?p:Ex,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),C.appendChild(k),y.appendChild(C);let T=Hx(n,a,d.length);T&&y.appendChild(T),s.appendChild(y)}else{let y=h("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=(m=t.freeTextLabel)!=null?m:f,s.appendChild(y)}}return s},Bx=(e,t)=>{var s,a;let n=h("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:Ex,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Lx,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},BC=e=>{var n;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=h("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=e.submitLabel)!=null?n:Lx,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},DC=(e,t,r)=>{var l,p,u,m;let n=h("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=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:SC,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,n.appendChild(o);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:MC,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=h("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:TC:(m=r.nextLabel)!=null?m:AC,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(Px);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Dx=(e,t)=>{e.setAttribute(Px,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},OC=(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",_C=(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},NC=(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},Ox=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=LC(e),{payload:s,complete:a}=xo(t),i=Oo(e),d=En(e),l=Vs(e),p=i?IC(s,d):PC(s),u=!!(p!=null&&p.multiSelect),m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let y=e.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 C=e.querySelector('[data-ask-pill-list="true"]');if(C){let S=HC(p,n,a,o);C.replaceWith(S)}if(o!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(Bx(n,o))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!k?e.appendChild(BC(n)):(!u||i)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let S=DC(d,l,n);T?T.replaceWith(S):e.appendChild(S)}else T&&T.remove();Ox(e),_x(e)},$C=(e,t,r)=>{let n=Ul(t),o=EC(n),s=e.toolCall.id,a=Ya(r),i=Math.max(1,a.length),d=i>1,l=_C(e,a),p=d?NC(e,i):0,u=h("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(Ix,o),Dx(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`),Wx(u,n);let m=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",m.appendChild(f);let y=h("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",m.appendChild(y),u.appendChild(m);let k=h("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 k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),o!=="rows"&&u.appendChild(Bx(n,o)),du(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},FC=(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)},Nx=(e,t)=>{let r=h("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);Wx(r,n);let o=h("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}="${Rx(o)}"]`);if(a){FC(a,e,t);return}let{payload:i}=xo(e),d=$C(e,t,i);r.appendChild(d)},_o=(e,t)=>{if(!e)return;let r=t?`[${js}="${Rx(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,Dx(e,r),Ox(e),_x(e)},ql=(e,t,r,n)=>{let o=Vs(e),s=Math.max(0,Math.min(o-1,n));OC(e,s),du(e,t,r)};var pu=(e,t)=>{var C,k,T,S,M,v,b,x,E,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=h("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=(C=n==null?void 0:n.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=n==null?void 0:n.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!r)return s;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("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=h("div","persona-flex-1 persona-min-w-0"),m=h("div","persona-flex persona-items-center persona-gap-2"),f=h("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",m.appendChild(f),!o){let N=h("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"),m.appendChild(N)}u.appendChild(m);let y=h("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=h("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=h("div","persona-flex persona-gap-2 persona-mt-2");N.setAttribute("data-approval-buttons","true");let q=h("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=(v=n==null?void 0:n.approveButtonTextColor)!=null?v:"#ffffff",q.setAttribute("data-approval-action","approve");let se=Pe("shield-check",14,(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",2);se&&(se.style.marginRight="4px",q.appendChild(se));let ve=document.createTextNode((x=n==null?void 0:n.approveLabel)!=null?x:"Approve");q.appendChild(ve);let Ue=h("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=(E=n==null?void 0:n.denyButtonColor)!=null?E:"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 $x=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(f=>f.role==="user"))return;let p=document.createDocumentFragment(),u=o?o.isStreaming():!1,m=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=h("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=u,i!=null&&i.fontFamily&&(y.style.fontFamily=m(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),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 UC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),zC=new Set(["step_start","execution_start"]),qC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),jC=new Set(["step_complete","agent_turn_complete"]),VC=new Set(["flow_complete","agent_complete"]),Fx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),zx=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 zx(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 GC(e,t){return typeof t.type=="string"?t.type:e}function KC(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 JC(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 Ux(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 XC(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 YC(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ei=class{constructor(t=YC){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(!zx(r)){Fx.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=GC(t,r),o=this.now();if(UC.has(n)){this.startRun(o);return}if(zC.has(n)){this.run||this.startRun(o);return}if(qC.has(n)){if(!JC(n,r))return;let a=KC(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(jC.has(n)){if(!this.run)return;let a=this.run,i=Ux(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(VC.has(n)){if(!this.run)return;let a=this.run,i=Ux(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(Fx.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=XC(r);return s!=null?s:n-t.startedAt}};function Ks(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var QC={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)"}},ZC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],tv=100;function rv(e,t){let r={...QC,...t};if(r[e])return r[e];for(let n of Object.keys(r))if(n.endsWith("_")&&e.startsWith(n))return r[n];return ZC}function nv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ov(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 sv(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 av(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 iv(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 lv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function dv(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 cv(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=h("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=h("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 m;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Ks(l,(m=n.classNames)==null?void 0:m.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var q,se;let f=h("div",""),y=h("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 C=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=Pe(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&C.appendChild(k);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(q=n.timestampFormat)!=null?q:"relative";T.textContent=S==="relative"?nv(e.timestamp,r):ov(e.timestamp);let M=null;n.showSequenceNumbers!==!1&&(M=h("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 v=rv(e.type,n.badgeColors),b=h("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=v.bg,b.style.color=v.text,b.style.borderColor=v.text+"50",b.textContent=e.type;let x=(se=n.descriptionFields)!=null?se:ev,E=sv(e.payload,x),B=null;E&&(B=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=E);let H=h("div","persona-flex-1 persona-min-w-0"),W=h("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 av(iv(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(C),y.appendChild(T),M&&y.appendChild(M),y.appendChild(b),B&&y.appendChild(B),y.appendChild(H),y.appendChild(W),f.appendChild(y),d&&f.appendChild(cv(e,a,i)),f}}function qx(e){var y,C,k,T,S;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=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",p=(k=i==null?void 0:i.label)!=null?k:"",u=(S=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?S:{},m=s.find(M=>M.renderEventStreamView);if(m!=null&&m.renderEventStreamView&&o){let M=m.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=u.classNames,v=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ks(v,M==null?void 0:M.panel);let b=[],x="",E="",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=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ae=h("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(Ae,M==null?void 0:M.headerBar);let Wt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Wt.textContent="Events",Ce=h("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=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let cr=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");cr.textContent="Throughput",G=h("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=h("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=h("div","persona-flex-1");Z=h("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=h("option","");Et.value="",Et.textContent="All events",Z.appendChild(Et),he=h("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=h("span","persona-text-xs");Ht.textContent="Copy All",he.appendChild(Ht),Ae.appendChild(Wt),Ae.appendChild(Ce),ee&&Ae.appendChild(ee),Ae.appendChild(sr),Ae.appendChild(Z),Ae.appendChild(he);let Tt=h("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=h("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=h("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=h("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(Ae),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:Ae=>{x=Ae,ue(),te()},onSearchChange:Ae=>{E=Ae,ue(),te()}});pe=fe!=null?fe:ye()}else pe=ye();let Ye=h("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=lv(fe);let Ae=dv(fe);Ie&&(Ie.textContent=Ae,Ae||(Ie.style.display="none")),Ae?ee.setAttribute("aria-label",Ae):ee.removeAttribute("aria-label")}let be=h("div","persona-flex-1 persona-min-h-0 persona-relative"),J=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let Ke=h("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=h("span","");Y.textContent=p,Ke.appendChild(Y);let Q=h("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),v.setAttribute("tabindex","0"),v.appendChild(pe),v.appendChild(Ye),v.appendChild(be);function Be(){let fe=t.getAll(),Ae={};for(let Ht of fe)Ae[Ht.type]=(Ae[Ht.type]||0)+1;let Wt=Object.keys(Ae).sort(),sr=Wt.length!==H.length||!Wt.every((Ht,Tt)=>Ht===H[Tt]),Et=!sr&&Wt.some(Ht=>Ae[Ht]!==W[Ht]),gr=fe.length!==Object.values(W).reduce((Ht,Tt)=>Ht+Tt,0);if(!sr&&!Et&&!gr||(H=Wt,W=Ae,!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=h("option","");Tt.value=Ht,Tt.textContent=`${Ht} (${Ae[Ht]||0})`,Z.appendChild(Tt)}_t&&Wt.includes(_t)?Z.value=_t:_t&&(Z.value="",x="")}else for(let Ht=1;Ht<Z.options.length;Ht++){let Tt=Z.options[Ht];Tt.textContent=`${Tt.value} (${Ae[Tt.value]||0})`}}function ke(){let fe=t.getAll();if(x&&(fe=fe.filter(Ae=>Ae.type===x)),E){let Ae=E.toLowerCase();fe=fe.filter(Wt=>Wt.type.toLowerCase().includes(Ae)||Wt.payload.toLowerCase().includes(Ae))}return fe}function ge(){return x!==""||E!==""}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 Ae=J.scrollTop,Wt=q.isFollowing();we=!0,q.pause(),te(),J.scrollTop=Ae,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",b=ke();let Ae=b.length,Wt=t.getSize()>0;Ce&&(Ce.textContent=String(t.getSize())),Ae===0&&Wt&&ge()?(Q.textContent=E?`No events matching '${E}'`:"No events matching filter",Q.style.display="",J.style.display="none"):(Q.style.display="none",J.style.display=""),he&&(he.title=ge()?`Copy Filtered (${Ae})`:"Copy All"),d&&!q.isFollowing()&&Ae>N&&(se+=Ae-N,Y.textContent=p?`${p}${se>0?` (${se})`:""}`:"",Ke.style.display=""),N=Ae;let sr=t.getAll(),Et=sr.length>0?sr[0].timestamp:0,gr=new Set(b.map(Tt=>Tt.id));for(let Tt of We)gr.has(Tt)||We.delete(Tt);let _t=x!==K||E!==He,Ht=Oe.size===0&&b.length>0;if(_t||Ht||b.length===0){J.innerHTML="",Oe.clear();let Tt=document.createDocumentFragment();for(let Lt=0;Lt<b.length;Lt++){let ar=fu(b[Lt],Lt,Et,u,We,_e,s,o);Oe.set(b[Lt].id,ar),Tt.appendChild(ar)}J.appendChild(Tt),K=x,He=E,j=null}else{if(j!==null){let Lt=Oe.get(j);if(Lt&&Lt.parentNode===J){let ar=b.findIndex(mt=>mt.id===j);if(ar>=0){let mt=fu(b[ar],ar,Et,u,We,_e,s,o);J.insertBefore(mt,Lt),Lt.remove(),Oe.set(j,mt)}}j=null}let Tt=new Set(b.map(Lt=>Lt.id));for(let[Lt,ar]of Oe)Tt.has(Lt)||(ar.remove(),Oe.delete(Lt));for(let Lt=0;Lt<b.length;Lt++){let ar=b[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>=tv){je!==null&&(cancelAnimationFrame(je),je=null),te();return}Ue||(Ue=!0,je=requestAnimationFrame(()=>{je=null,te()}))}let tt=(fe,Ae)=>{if(!he)return;he.innerHTML="";let Wt=Pe(fe,"12px","currentColor",1.5);Wt&&he.appendChild(Wt);let sr=h("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=h("span","persona-text-xs");gr.textContent="Copy All",he.appendChild(gr),he.disabled=!1},Ae)},Xe=async()=>{if(he){he.disabled=!0;try{let fe;ge()?fe=b:r?(fe=await r(),fe.length===0&&(fe=t.getAll())):fe=t.getAll();let Ae=fe.map(Wt=>{try{return JSON.parse(Wt.payload)}catch{return Wt.payload}});await navigator.clipboard.writeText(JSON.stringify(Ae,null,2)),tt("check",1500)}catch{tt("x",1500)}}},Je=()=>{Z&&(x=Z.value,ue(),te())},pt=()=>{!xe||!Ve||(Ve.style.display=xe.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{E=xe.value,ue(),te()},150))},ht=()=>{!xe||!Ve||(xe.value="",E="",Ve.style.display="none",B&&clearTimeout(B),ue(),te())},zt=()=>{if(we)return;let fe=J.scrollTop,{action:Ae,nextLastScrollTop:Wt}=Ml({following:q.isFollowing(),currentScrollTop:fe,lastScrollTop:Te,nearBottom:I(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Te=Wt,Ae==="resume"?(q.resume(),se=0,Ke.style.display="none"):Ae==="pause"&&(q.pause(),d&&(Y.textContent=p,Ke.style.display=""))},or=fe=>{let Ae=kl({following:q.isFollowing(),deltaY:fe.deltaY,nearBottom:I(),resumeWhenNearBottom:!0});Ae==="pause"?(q.pause(),d&&(Y.textContent=p,Ke.style.display="")):Ae==="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 Ae=fe.target;if(!Ae||Ae.closest("button"))return;let Wt=Ae.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(),v.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),v.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),v.removeEventListener("keydown",ct)}return{element:v,update:qe,destroy:Jt}}}function jx(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 m=document.createElement("span");m.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",m.style.backgroundColor="var(--persona-primary, #171717)",m.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(m);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let m=document.createElement("button");m.type="button",m.textContent="Download",m.title=`Download ${r}`,m.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-text, #1f2937)",m.style.backgroundColor="transparent",m.style.cursor="pointer",m.setAttribute("data-download-artifact",n),i.append(m)}return i}var Vx=(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:()=>jx(e,t)});if(p)return p}return jx(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",Vx);function pv(e){var o;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=h("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("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 Gx(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"?h("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=h("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 m=h("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");m.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&m.classList.add("persona-artifact-toolbar-document");let f=h("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let y=h("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 C="rendered",k=h("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"}),S=o?ir({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):ir({icon:"code-2",label:"Source"}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),v=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,b=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,x=r==null?void 0:r.documentToolbarCopyMenuItems,E=!!(b&&x&&x.length>0),B=null,H,W=null,N=null;if(o&&(v||b)&&!E){if(H=v?Ja({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ir({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),b){let G=Pe("chevron-down",14,"currentColor",2);G&&H.appendChild(G)}}else o&&E?(B=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=v?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&&E){let{markdown:ee,jsonPayload:Ie,id:ye}=ve();try{await G({actionId:"primary",artifactId:ye,markdown:ee,jsonPayload:Ie})}catch{}return}await Ue()}),W&&(x!=null&&x.length)){let G=()=>{var Ie;return(Ie=u.closest("[data-persona-root]"))!=null?Ie:document.body},ee=()=>{N=Bo({items:x.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",C==="rendered"?"true":"false"),S.setAttribute("aria-pressed",C==="source"?"true":"false"))};T.addEventListener("click",()=>{C="rendered",je(),j()}),S.addEventListener("click",()=>{C="source",je(),j()});let we=h("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?(m.replaceChildren(),k.append(T,S),B?M.append(B,q,se):M.append(H,q,se),m.append(k,we,M),je()):(m.appendChild(f),m.appendChild(y)),s&&(m.style.paddingLeft=s,m.style.paddingRight=s);let Te=h("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=h("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(m),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=h("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 f.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&C==="source"){let be=h("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=h("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(pv(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 Kx(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 uv(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,m,f,y,C,k,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"),uv(e),Kx(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",(m=r==null?void 0:r.paneMaxWidth)!=null?m:"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=(f=r==null?void 0:r.paneBackground)==null?void 0:f.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=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(k=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:k.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"),Kx(e,t)}var Jx=["panel","seamless"];function Gl(e,t){var i,d,l,p,u,m;for(let f of Jx)e.classList.remove(`persona-artifact-appearance-${f}`);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=Jx.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 f=((m=r.unifiedSplitOuterRadius)==null?void 0:m.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Xx(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 fv(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 mv(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 gv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function hv(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}function Yx(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 Qx(e,t,r,n,o,s){let a=fv(o,200),i=hv(t,r,n,200);i=Math.max(a,i);let d=mv(s);return d!==null&&(i=Math.min(i,d)),gv(e,a,i)}var Zx={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,C,k;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(C=Zx[a])!=null?C:Zx.init;s.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=h("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 x,E;let S=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${a}-${T.name}`;let M=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=T.label,S.appendChild(M);let v=(x=T.type)!=null?x:"text",b;v==="textarea"?(b=document.createElement("textarea"),b.rows=3):(b=document.createElement("input"),b.type=v),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=`${t.id}-${a}-${T.name}`,b.name=T.name,b.placeholder=(E=T.placeholder)!=null?E:"",T.required&&(b.required=!0),S.appendChild(b),p.appendChild(S)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=h("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=(k=i.submitLabel)!=null?k:"Submit",u.appendChild(m),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var b,x;T.preventDefault();let S=(b=r.formEndpoint)!=null?b:"/form",M=new FormData(p),v={};M.forEach((E,B)=>{v[B]=E}),v.type=a,f.disabled=!0,m.textContent="Submitting\u2026";try{let E=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let B=await E.json();m.textContent=(x=B.message)!=null?x:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await n.sendMessage(String(B.nextPrompt))}catch(E){m.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.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 ey=()=>{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 xv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yv=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=xv(e),r=yv(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)}}},ty=e=>Array.isArray(e)?e.map(t=>String(t)):[],ni=e=>{let t=new Set(ty(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ty(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 m=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:m,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var bv=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}},wv=e=>e.map(t=>({...t,streaming:!1})),Cv=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?bv(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let o={...r,messages:r.messages?wv(r.messages):void 0,artifacts:r.artifacts?Cv(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 vv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Av(e,t){if(!vv(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=Av(o,r);s&&(e=s)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function ry(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 ny(){let e=Jl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function oy(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=oy(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=oy(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 Sv=["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=Sv}=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,m=document.createElement("div");m.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 C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=o,f.appendChild(C),m.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let x=1;x<=5;x++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${l[x-1]}`),E.title=l[x-1],E.dataset.rating=String(x),E.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
|
-
`,E.addEventListener("click",()=>{u=h,T.forEach((W,R)=>{let I=R<h;W.classList.toggle("selected",I),W.setAttribute("aria-checked",R===h-1?"true":"false")})}),T.push(E),M.appendChild(E)}m.appendChild(M);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=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),h.appendChild(A),m.appendChild(h)}let k=document.createElement("div");k.className="persona-feedback-actions";let v=document.createElement("button");v.type="button",v.className="persona-feedback-btn persona-feedback-btn-skip",v.textContent=i,v.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=s,w.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.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=s,console.error("[CSAT Feedback] Failed to submit:",h)}}),k.appendChild(v),k.appendChild(w),m.appendChild(k),p.appendChild(m),p}function Xl(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:a="What could we do better? (optional)...",submitText:s="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 m=null,f=document.createElement("div");f.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,x.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=o,x.appendChild(M),f.appendChild(x);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 k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let v=document.createElement("span");v.className="persona-feedback-label-high",v.textContent=p,A.appendChild(k),A.appendChild(v);let w=document.createElement("div");w.className="persona-feedback-numbers";let h=[];for(let H=0;H<=10;H++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${H} out of 10`),G.textContent=String(H),G.dataset.rating=String(H),H<=6?G.classList.add("persona-feedback-detractor"):H<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{m=H,h.forEach((ie,ye)=>{ie.classList.toggle("selected",ye===H),ie.setAttribute("aria-checked",ye===H?"true":"false")})}),h.push(G),w.appendChild(G)}T.appendChild(A),T.appendChild(w),f.appendChild(T);let E=null;if(d){let H=document.createElement("div");H.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=a,E.rows=3,E.setAttribute("aria-label","Additional comments"),H.appendChild(E),f.appendChild(H)}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(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=s,I.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let H=(E==null?void 0:E.value.trim())||void 0;await t(m,H),u.remove()}catch(H){I.disabled=!1,I.textContent=s,console.error("[NPS Feedback] Failed to submit:",H)}}),W.appendChild(R),W.appendChild(I),f.appendChild(W),u.appendChild(f),u}var Ga="persona-chat-history",ov=30*1e3,av={"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 sv(e){var n,o,a;if(!e)return[];let t=[],r=Array.from((n=e.items)!=null?n:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=av[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 s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function Yl(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,a,s,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:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function lv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var fu=e=>!e||typeof e!="object"?{}:{...e},Xx=e=>e.map(t=>({...t,streaming:!1})),Yx=(e,t,r)=>{let n=e!=null&&e.markdown?ra(e.markdown):null,o=ka(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."),a=>{var l,p,u;let s=(l=a.text)!=null?l:"",i=(p=a.message.rawContent)!=null?p:null;if(t){let m=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});m!==null&&(s=m.text,m.persist||(a.message.__skipPersist=!0),m.resubmit&&!a.streaming&&r&&r())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...a,text:s,raw:(u=i!=null?i:a.text)!=null?u:""}):n?d=n(s):d=na(s),o?o(d):d}};function Qx(e){var i,d,l,p;let t=y("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)",a=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,s=Pe(r,n,o,a);if(s&&t.appendChild(s),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Ql=(e,t,r)=>{var _u,Nu,$u,Fu,Uu,zu,qu,ju,Vu,Gu,Ku,Ju,Xu,Yu,Qu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,wf,Cf,vf,Af,Sf,Tf,Mf,kf,Ef,Lf,Pf,If,Rf;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=hl(t),o=Ys.getForInstance(n.plugins);n.components&&ho.registerAll(n.components);let a=jx(),i=n.persistState===!1?null:(_u=n.storageAdapter)!=null?_u:ql(),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:b,open:S}=g;return S&&(p=!0),b}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 b=g!=null?g:{messages:[],metadata:{}};return u(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=u(g);b.metadata&&(d=fu(b.metadata)),(Nu=b.messages)!=null&&Nu.length&&(n={...n,initialMessages:b.messages}),($u=b.artifacts)!=null&&$u.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Fu=b.selectedArtifactId)!=null?Fu: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:{}});(Uu=c.messages)!=null&&Uu.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let m=()=>d,f=c=>{var b;d=(b=c({...d}))!=null?b:{},xa()},x=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Qs],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ma.message,ma.messageAndClick],M=Zs({parsers:x,handlers:C,getSessionMetadata:m,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let T=(qu=(zu=n.launcher)==null?void 0:zu.enabled)!=null?qu:!0,A=(Vu=(ju=n.launcher)==null?void 0:ju.autoExpand)!=null?Vu:!1,k=(Gu=n.autoFocusInput)!=null?Gu:!1,v=A,w=T,h=(Ju=(Ku=n.layout)==null?void 0:Ku.header)==null?void 0:Ju.layout,E=!1,W=()=>Wo(n),R=()=>T||W(),I=W()?!1:T?A:!0,H=!1,G=null,ie=()=>{H=!0,G&&clearTimeout(G),G=setTimeout(()=>{H&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),H=!1)},1e4)},ye=Yx(n,M,ie),Oe=(Yu=(Xu=n.features)==null?void 0:Xu.showReasoning)!=null?Yu:!0,et=(Zu=(Qu=n.features)==null?void 0:Qu.showToolCalls)!=null?Zu:!0,be=(tf=(ef=n.features)==null?void 0:ef.showEventStreamToggle)!=null?tf:!1,xe=(nf=(rf=n.features)==null?void 0:rf.scrollToBottom)!=null?nf:{},Je=`${(af=typeof n.persistState=="object"?(of=n.persistState)==null?void 0:of.keyPrefix:void 0)!=null?af:"persona-"}event-stream`,X=be?new Xs(Je):null,Te=(df=(lf=(sf=n.features)==null?void 0:sf.eventStream)==null?void 0:lf.maxEvents)!=null?df:2e3,K=be?new Js(Te,X):null,ge=null,ce=!1,fe=null,He=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 rt={onCopy:c=>{var g,b;a.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.id,"copy").catch(S=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(b=(g=n.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;a.emit("message:feedback",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.messageId,c.type).catch(S=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(b=(g=n.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},Q=(cf=n.statusIndicator)!=null?cf:{},de=c=>{var g,b,S,D;return c==="idle"?(g=Q.idleText)!=null?g:_r.idle:c==="connecting"?(b=Q.connectingText)!=null?b:_r.connecting:c==="connected"?(S=Q.connectedText)!=null?S:_r.connected:c==="error"?(D=Q.errorText)!=null?D:_r.error:_r[c]};function _e(c,g,b,S){if(S==="idle"&&b.idleLink){c.textContent="";let D=document.createElement("a");D.href=b.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:Y,panel:V,pillRoot:Ce}=mx(n),Be=gx(n,R()),{container:oe,body:Ee,messagesWrapper:we,suggestions:Dt,textarea:U,sendButton:ae,sendButtonWrapper:ze,composerForm:he,statusText:Re,introTitle:ve,introSubtitle:ue,closeButton:Z,iconHolder:O,headerTitle:me,headerSubtitle:qe,header:$e,footer:Xe,actionsRow:mt,leftActions:ct,rightActions:yt}=Be,jt=Be.setSendButtonMode,N=Be.micButton,Me=Be.micButtonWrapper,ke=Be.attachmentButton,gt=Be.attachmentButtonWrapper,tt=Be.attachmentInput,Ut=Be.attachmentPreviewsContainer;oe.classList.add("persona-relative"),Ee.classList.add("persona-relative");let dr=12,Ot=()=>{var c;return(c=xe.label)!=null?c:""},It=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},lt=()=>xe.enabled!==!1,ht=y("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");ht.type="button",ht.style.display="none",ht.setAttribute("data-persona-scroll-to-bottom","true");let ar=y("span","persona-flex persona-items-center"),yn=y("span","");ht.append(ar,yn),oe.appendChild(ht);let Hr=()=>{let g=Xe.style.display==="none"?0:Xe.offsetHeight;ht.style.bottom=`${g+dr}px`};Hr();let Ln=()=>{let c=!!Ot();ht.setAttribute("aria-label",Ot()||"Jump to latest"),ht.title=Ot(),ht.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),ar.innerHTML="";let g=Pe(It(),"14px","currentColor",2);g?(ar.appendChild(g),ar.style.display=""):ar.style.display="none",yn.textContent=Ot(),yn.style.display=c?"":"none"};Ln();let Rt=null,bn=null,hr=o.find(c=>c.renderHeader);if(hr!=null&&hr.renderHeader){let c=hr.renderHeader({config:n,defaultRenderer:()=>{let g=fo({config:n,showClose:R()});return pa(oe,g,n),g.header},onClose:()=>Kt(!1,"user")});if(c){let g=oe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),$e=c)}}let Mr=()=>{var g,b,S,D;if(!K)return;if(ce=!0,!ge&&K&&(ge=Bx({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Zr(),config:n,plugins:o})),ge&&(Ee.style.display="none",(g=Xe.parentNode)==null||g.insertBefore(ge.element,Xe),ge.update()),Tt){Tt.style.boxShadow=`inset 0 0 0 1.5px ${Qr.actionIconColor}`;let F=(D=(S=(b=n.features)==null?void 0:b.eventStream)==null?void 0:S.classNames)==null?void 0:D.toggleButtonActive;F&&F.split(/\s+/).forEach(z=>z&&Tt.classList.add(z))}let c=()=>{if(!ce)return;let F=Date.now();F-He>=200&&(ge==null||ge.update(),He=F),fe=requestAnimationFrame(c)};He=0,fe=requestAnimationFrame(c),ro(),a.emit("eventStream:opened",{timestamp:Date.now()})},Zr=()=>{var c,g,b;if(ce){if(ce=!1,ge&&ge.element.remove(),Ee.style.display="",Tt){Tt.style.boxShadow="";let S=(b=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;S&&S.split(/\s+/).forEach(D=>D&&Tt.classList.remove(D))}fe!==null&&(cancelAnimationFrame(fe),fe=null),ro(),a.emit("eventStream:closed",{timestamp:Date.now()})}},Tt=null;if(be){let c=(uf=(pf=n.features)==null?void 0:pf.eventStream)==null?void 0:uf.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:"");Tt=y("button",g),Tt.style.width="28px",Tt.style.height="28px",Tt.style.color=Qr.actionIconColor,Tt.type="button",Tt.setAttribute("aria-label","Event Stream"),Tt.title="Event Stream";let b=Pe("activity","18px","currentColor",1.5);b&&Tt.appendChild(b);let S=Be.clearChatButtonWrapper,D=Be.closeButtonWrapper,F=S||D;F&&F.parentNode===$e?$e.insertBefore(Tt,F):$e.appendChild(Tt),Tt.addEventListener("click",()=>{ce?Zr():Mr()})}let Pn=c=>{var S,D,F;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let z=c.querySelector("[data-persona-composer-form]");z!=null&&z.parentNode?z.parentNode.insertBefore(b,z):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let z=y("input");z.type="file",z.accept=((S=g.allowedTypes)!=null?S:uo).join(","),z.multiple=((D=g.maxFiles)!=null?D:4)>1,z.style.display="none",z.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(z)}},an=o.find(c=>c.renderComposer);if(an!=null&&an.renderComposer){let c=n.composer,g=an.renderComposer({config:n,defaultRenderer:()=>_a({config:n}).footer,onSubmit:b=>{var z;if(!q||q.isStreaming())return;let S=b.trim(),D=(z=Rt==null?void 0:Rt.hasAttachments())!=null?z:!1;if(!S&&!D)return;os();let F;D&&(F=[],F.push(...Rt.getContentParts()),S&&F.push(Rs(S))),q.sendMessage(S,{contentParts:F}),D&&Rt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{tt==null||tt.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((ff=n.voiceRecognition)==null?void 0:ff.enabled)===!0?()=>{bn==null||bn()}:void 0});g&&(Xe.replaceWith(g),Xe=g)}let kr=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&(he=g),b&&(U=b),S&&(ae=S),D&&(N=D,Me=D.parentElement),F&&(Re=F);let z=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");z&&(Dt=z);let J=c.querySelector(".persona-attachment-button");J&&(ke=J,gt=J.parentElement),tt=c.querySelector('input[type="file"]'),Ut=c.querySelector(".persona-attachment-previews");let $=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");$&&(mt=$)};Pn(Xe),kr(Xe);let Er=(yf=(mf=n.layout)==null?void 0:mf.contentMaxWidth)!=null?yf:W()?(xf=(hf=(gf=n.launcher)==null?void 0:gf.composerBar)==null?void 0:hf.contentMaxWidth)!=null?xf:"720px":void 0;if(Er&&(we.style.maxWidth=Er,we.style.marginLeft="auto",we.style.marginRight="auto",we.style.width="100%"),Er&&he&&!W()&&(he.style.maxWidth=Er,he.style.marginLeft="auto",he.style.marginRight="auto"),Er&&Dt&&!W()&&(Dt.style.maxWidth=Er,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Er&&Ut&&!W()&&(Ut.style.maxWidth=Er,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(bf=n.attachments)!=null&&bf.enabled&&tt&&Ut){Rt=da.fromConfig(n.attachments),Rt.setPreviewsContainer(Ut),tt.addEventListener("change",b=>{let S=b.target;Rt==null||Rt.handleFileSelect(S.files),S.value=""});let c=n.attachments.dropOverlay,g=Qx(c);oe.appendChild(g)}(()=>{var S,D;let c=(D=(S=n.layout)==null?void 0:S.slots)!=null?D:{},g=F=>{switch(F){case"body-top":return oe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return we;case"footer-top":return Dt;case"composer":return he;case"footer-bottom":return Re;default:return null}},b=(F,z)=>{var J;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")$e.insertBefore(z,$e.firstChild);else if(F==="header-right")$e.appendChild(z);else{let $=$e.querySelector(".persona-flex-col");$?(J=$.parentNode)==null||J.insertBefore(z,$.nextSibling):$e.appendChild(z)}break;case"body-top":{let $=Ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");$?$.replaceWith(z):Ee.insertBefore(z,Ee.firstChild);break}case"body-bottom":Ee.appendChild(z);break;case"footer-top":Dt.replaceWith(z);break;case"footer-bottom":Re.replaceWith(z);break;default:break}};for(let[F,z]of Object.entries(c))if(z)try{let J=z({config:n,defaultContent:()=>g(F)});J&&b(F,J)}catch(J){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,J)}})();let In=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let S=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!S)return;let D=S.getAttribute("data-message-id");if(!D)return;let F=b.getAttribute("data-bubble-type");F==="reasoning"?($a.has(D)?$a.delete(D):$a.add(D),bx(D,S)):F==="tool"&&(Fa.has(D)?Fa.delete(D):Fa.add(D),wx(D,S,n)),cn.delete(D)};we.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),In(c))}),we.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),In(c))});let wn=new Map;we.addEventListener("click",c=>{var z;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let S=b.closest("[data-actions-for]");if(!S)return;let D=S.getAttribute("data-actions-for");if(!D)return;let F=b.getAttribute("data-action");if(F==="copy"){let $=q.getMessages().find(De=>De.id===D);if($&&rt.onCopy){let De=$.content||"";navigator.clipboard.writeText(De).then(()=>{b.classList.add("persona-message-action-success");let Ae=Pe("check",14,"currentColor",2);Ae&&(b.innerHTML="",b.appendChild(Ae)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let le=Pe("copy",14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le))},2e3)}).catch(Ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ae)}),rt.onCopy($)}}else if(F==="upvote"||F==="downvote"){let $=((z=wn.get(D))!=null?z:null)===F,De=F==="upvote"?"thumbs-up":"thumbs-down";if($){wn.delete(D),b.classList.remove("persona-message-action-active");let Ae=Pe(De,14,"currentColor",2);Ae&&(b.innerHTML="",b.appendChild(Ae))}else{let Ae=F==="upvote"?"downvote":"upvote",le=S.querySelector(`[data-action="${Ae}"]`);if(le){le.classList.remove("persona-message-action-active");let it=Pe(Ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);it&&(le.innerHTML="",le.appendChild(it))}wn.set(D,F),b.classList.add("persona-message-action-active");let Le=Pe(De,14,"currentColor",2);Le&&(Le.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Le)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Ye=q.getMessages().find(xt=>xt.id===D);Ye&&rt.onFeedback&&rt.onFeedback({type:F,messageId:Ye.id,message:Ye})}}}),we.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let S=b.closest(".persona-approval-bubble");if(!S)return;let D=S.getAttribute("data-message-id");if(!D)return;let F=b.getAttribute("data-approval-action");if(!F)return;let z=F==="approve"?"approved":"denied",$=q.getMessages().find(Ae=>Ae.id===D);if(!($!=null&&$.approval))return;let De=S.querySelector("[data-approval-buttons]");De&&De.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),$.approval.toolType==="webmcp"?q.resolveWebMcpApproval(D,z):q.resolveApproval($.approval,z)});let Et=null,Fe=null,P={artifacts:[],selectedId:null},ee=!1,pe={current:null};we.addEventListener("click",c=>{var le,Le,Ne,Ye,xt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let S=b.getAttribute("data-download-artifact");if(!S||((Ne=(Le=(le=n.features)==null?void 0:le.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:Ne.call(Le,{type:"download",artifactId:S}))===!0)return;let F=q.getArtifactById(S),z=F==null?void 0:F.markdown,J=(F==null?void 0:F.title)||"artifact";if(!z){let it=b.closest("[data-open-artifact]"),Ct=it==null?void 0:it.closest("[data-message-id]"),vt=Ct==null?void 0:Ct.getAttribute("data-message-id");if(vt){let Ve=q.getMessages().find(nt=>nt.id===vt);if(Ve!=null&&Ve.rawContent)try{let nt=JSON.parse(Ve.rawContent);z=(Ye=nt==null?void 0:nt.props)==null?void 0:Ye.markdown,J=((xt=nt==null?void 0:nt.props)==null?void 0:xt.title)||J}catch{}}}if(!z)return;let $=new Blob([z],{type:"text/markdown"}),De=URL.createObjectURL($),Ae=document.createElement("a");Ae.href=De,Ae.download=`${J}.md`,Ae.click(),URL.revokeObjectURL(De)}),we.addEventListener("click",c=>{var F,z,J;let b=c.target.closest("[data-open-artifact]");if(!b)return;let S=b.getAttribute("data-open-artifact");!S||((J=(z=(F=n.features)==null?void 0:F.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:J.call(z,{type:"open",artifactId:S}))===!0||(c.preventDefault(),c.stopPropagation(),ee=!1,q.selectArtifact(S),sn())}),we.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Wt=Be.composerOverlay,Jt=(c,g,b)=>{var J,$,De,Ae;let S=g.trim();if(!S||!pe.current)return;let D=(J=c.getAttribute("data-tool-call-id"))!=null?J:"",F=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:S,answers:b.structured,values:($=b.values)!=null?$:b.source==="multi"?S.split(", "):[S],isFreeText:F,source:b.source},bubbles:!0,composed:!0})),Oo(Wt,D);let z=pe.current.getMessages().find(le=>{var Le;return((Le=le.toolCall)==null?void 0:Le.id)===D});(De=z==null?void 0:z.agentMetadata)!=null&&De.awaitingLocalTool?pe.current.resolveAskUserQuestion(z,(Ae=b.structured)!=null?Ae:S):pe.current.sendMessage(S)},Nt=c=>{var D;let g=pe.current;if(!g)return;let b=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",S=g.getMessages().find(F=>{var z;return((z=F.toolCall)==null?void 0:z.id)===b});S&&g.persistAskUserQuestionProgress(S,{answers:$l(c,S),currentIndex:kn(c)})},cr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),wr=c=>{var D,F,z;if(((F=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=kn(c),b=za(c);if(g>=b-1)return;let S=(z=pe.current)==null?void 0:z.getMessages().find(J=>{var $;return(($=J.toolCall)==null?void 0:$.id)===c.getAttribute("data-tool-call-id")});S&&(Fl(c,S,n,g+1),Nt(c))};Wt.addEventListener("click",c=>{var F,z,J,$,De,Ae,le,Le,Ne,Ye,xt,it,Ct,vt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let S=b.closest("[data-persona-ask-sheet-for]");if(!S)return;let D=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let Ge=(F=S.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ge},bubbles:!0,composed:!0})),Oo(Wt,Ge);let Ve=(z=pe.current)==null?void 0:z.getMessages().find(nt=>{var B;return((B=nt.toolCall)==null?void 0:B.id)===Ge});(J=Ve==null?void 0:Ve.agentMetadata)!=null&&J.awaitingLocalTool&&(($=pe.current)==null||$.markAskUserQuestionResolved(Ve),(De=pe.current)==null||De.resolveAskUserQuestion(Ve,"(dismissed)"));return}if(D==="pick"){let Ge=b.getAttribute("data-option-label");if(!Ge)return;let Ve=S.getAttribute("data-multi-select")==="true",nt=Do(S);if(nt&&Ve){let B=fa(S)[kn(S)],Ue=new Set(Array.isArray(B)?B:[]);Ue.has(Ge)?Ue.delete(Ge):Ue.add(Ge),_o(S,Array.from(Ue)),Nt(S);return}if(nt){_o(S,Ge),Nt(S),wr(S);return}if(Ve){let B=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",B?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!B);let Ue=S.querySelector('[data-ask-user-action="submit-multi"]');Ue&&(Ue.disabled=su(S).length===0);return}Jt(S,Ge,{source:"pick",values:[Ge]});return}if(D==="submit-multi"){let Ge=su(S);if(Ge.length===0)return;Jt(S,Ge.join(", "),{source:"multi",values:Ge});return}if(D==="open-free-text"){let Ge=S.querySelector('[data-ask-free-text-row="true"]');if(Ge){Ge.classList.remove("persona-hidden");let Ve=Ge.querySelector('[data-ask-free-text-input="true"]');Ve==null||Ve.focus()}return}if(D==="focus-free-text"){let Ge=S.querySelector('[data-ask-free-text-input="true"]');Ge==null||Ge.focus();return}if(D==="submit-free-text"){let Ge=S.querySelector('[data-ask-free-text-input="true"]'),Ve=(Ae=Ge==null?void 0:Ge.value)!=null?Ae:"";if(!Ve.trim())return;if(Do(S)){_o(S,Ve.trim()),Nt(S),wr(S);return}Jt(S,Ve,{source:"free-text"});return}if(D==="next"||D==="back"){if(!pe.current)return;let Ge=(le=S.getAttribute("data-tool-call-id"))!=null?le:"",Ve=pe.current.getMessages().find(at=>{var We;return((We=at.toolCall)==null?void 0:We.id)===Ge});if(!Ve)return;let nt=S.querySelector('[data-ask-free-text-input="true"]'),B=(Ne=(Le=nt==null?void 0:nt.value)==null?void 0:Le.trim())!=null?Ne:"";if(B){let at=fa(S)[kn(S)];(typeof at!="string"||at!==B)&&_o(S,B)}let Ue=D==="next"?1:-1,Ke=kn(S)+Ue;Fl(S,Ve,n,Ke),Nt(S);return}if(D==="submit-all"){if(!pe.current)return;let Ge=(Ye=S.getAttribute("data-tool-call-id"))!=null?Ye:"",Ve=pe.current.getMessages().find(at=>{var We;return((We=at.toolCall)==null?void 0:We.id)===Ge});if(!Ve)return;let nt=S.querySelector('[data-ask-free-text-input="true"]'),B=(it=(xt=nt==null?void 0:nt.value)==null?void 0:xt.trim())!=null?it:"";B&&_o(S,B);let Ue=$l(S,Ve);pe.current.persistAskUserQuestionProgress(Ve,{answers:Ue,currentIndex:kn(S)});let Ke=cr(Ue);Jt(S,Ke||"(submitted)",{source:"submit-all",structured:Ue});return}if(D==="skip"){if(!pe.current)return;let Ge=(Ct=S.getAttribute("data-tool-call-id"))!=null?Ct:"",Ve=pe.current.getMessages().find(We=>{var qt;return((qt=We.toolCall)==null?void 0:qt.id)===Ge});if(!Ve)return;let nt=Do(S),B=kn(S),Ue=za(S),Ke=B>=Ue-1;if(!nt){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ge},bubbles:!0,composed:!0})),Oo(Wt,Ge),(vt=Ve.agentMetadata)!=null&&vt.awaitingLocalTool&&(pe.current.markAskUserQuestionResolved(Ve),pe.current.resolveAskUserQuestion(Ve,"(dismissed)"));return}_o(S,"");let at=S.querySelector('[data-ask-free-text-input="true"]');if(at&&(at.value=""),Ke){let We=$l(S,Ve),qt=cr(We);Jt(S,qt||"(skipped)",{source:"submit-all",structured:We});return}Fl(S,Ve,n,B+1),Nt(S);return}}),Wt.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let b=c.target;if(!((F=b.matches)!=null&&F.call(b,'[data-ask-free-text-input="true"]')))return;let S=b.closest("[data-persona-ask-sheet-for]");if(!S)return;c.preventDefault();let D=b.value;if(D.trim()){if(Do(S)){_o(S,D.trim()),Nt(S),wr(S);return}Jt(S,D,{source:"free-text"})}});let $r=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 b=Wt.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let S=Number(c.key),F=b.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",$r);let Lr=null,pt=null,Tr=null,Fr=null,yo=()=>{};function Zn(){Fr==null||Fr(),Fr=null}let bo=()=>{var z;if(!Lr||!pt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){pt.style.removeProperty("position"),pt.style.removeProperty("left"),pt.style.removeProperty("top"),pt.style.removeProperty("bottom"),pt.style.removeProperty("width"),pt.style.removeProperty("z-index");return}let S=Lr.firstElementChild;if(!S||S===pt)return;let D=10;pt.style.position="absolute",pt.style.top="0",pt.style.bottom="0",pt.style.width=`${D}px`,pt.style.zIndex="5";let F=S.offsetWidth-D/2;pt.style.left=`${Math.max(0,F)}px`},Un=()=>{},sn=()=>{var b,S,D,F,z;if(!Et||!En(n))return;Ul(e,n),zl(e,n),Un();let c=(F=(D=(S=(b=n.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:D.narrowHostMaxWidth)!=null?F:520,g=V.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),Et.update(P),ee?(Et.setMobileOpen(!1),Et.element.classList.add("persona-hidden"),(z=Et.backdrop)==null||z.classList.add("persona-hidden")):P.artifacts.length>0&&(Et.element.classList.remove("persona-hidden"),Et.setMobileOpen(!0)),yo()};if(En(n)){V.style.position="relative";let c=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(oe),Et=_x(n,{onSelect:b=>{var S;return(S=pe.current)==null?void 0:S.selectArtifact(b)},onDismiss:()=>{ee=!0,sn()}}),Et.element.classList.add("persona-hidden"),Lr=g,g.appendChild(c),g.appendChild(Et.element),Et.backdrop&&V.appendChild(Et.backdrop),V.appendChild(g),yo=()=>{var S,D,F,z;if(!Lr||!Et)return;if(!(((F=(D=(S=n.features)==null?void 0:S.artifacts)==null?void 0:D.layout)==null?void 0:F.resizable)===!0)){Tr==null||Tr(),Tr=null,Zn(),pt&&(pt.remove(),pt=null),Et.element.style.removeProperty("width"),Et.element.style.removeProperty("maxWidth");return}if(!pt){let J=y("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 $=e.ownerDocument,De=(z=$.defaultView)!=null?z:window,Ae=le=>{var Ct,vt;if(!Et||le.button!==0||e.classList.contains("persona-artifact-narrow-host")||De.innerWidth<=640)return;le.preventDefault(),Zn();let Le=le.clientX,Ne=Et.element.getBoundingClientRect().width,Ye=(vt=(Ct=n.features)==null?void 0:Ct.artifacts)==null?void 0:vt.layout,xt=Ge=>{let Ve=Lr.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-appearance-seamless"),B=nt?0:Ux(Lr,De),Ue=nt?0:J.getBoundingClientRect().width||6,Ke=Ne-(Ge.clientX-Le),at=zx(Ke,Ve,B,Ue,Ye==null?void 0:Ye.resizableMinWidth,Ye==null?void 0:Ye.resizableMaxWidth);Et.element.style.width=`${at}px`,Et.element.style.maxWidth="none",bo()},it=()=>{$.removeEventListener("pointermove",xt),$.removeEventListener("pointerup",it),$.removeEventListener("pointercancel",it),Fr=null;try{J.releasePointerCapture(le.pointerId)}catch{}};Fr=it,$.addEventListener("pointermove",xt),$.addEventListener("pointerup",it),$.addEventListener("pointercancel",it);try{J.setPointerCapture(le.pointerId)}catch{}};J.addEventListener("pointerdown",Ae),pt=J,Lr.insertBefore(J,Et.element),Tr=()=>{J.removeEventListener("pointerdown",Ae)}}if(pt){let J=P.artifacts.length>0&&!ee;pt.classList.toggle("persona-hidden",!J),bo()}},Un=()=>{var De,Ae,le,Le,Ne,Ye,xt,it,Ct,vt,Ge,Ve,nt,B;if(!T||!Et||((Ae=(De=n.launcher)==null?void 0:De.sidebarMode)!=null?Ae:!1)||br(n)&&Mn(n).reveal==="emerge")return;let S=(le=e.ownerDocument.defaultView)!=null?le:window,D=(Ne=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?Ne:!0,F=(xt=(Ye=n.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?xt:640;if(D&&S.innerWidth<=F||!Fx(n,T))return;let z=(vt=(Ct=(it=n.launcher)==null?void 0:it.width)!=null?Ct:n.launcherWidth)!=null?vt:xn,J=(B=(nt=(Ve=(Ge=n.features)==null?void 0:Ge.artifacts)==null?void 0:Ve.layout)==null?void 0:nt.expandedPanelWidth)!=null?B:"min(720px, calc(100vw - 24px))";P.artifacts.length>0&&!ee?(V.style.width=J,V.style.maxWidth=J):(V.style.width=z,V.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Fe=new ResizeObserver(()=>{sn()}),Fe.observe(V))}else V.appendChild(oe),W()&&Ce&&(Be.peekBanner&&Ce.appendChild(Be.peekBanner),Ce.appendChild(Xe));e.appendChild(Y),Ce&&e.appendChild(Ce);let Rn=()=>{var at,We,qt,wt,mr,Pr,Gt,qr,Ir,ut,At,jr,Dr,jo,Vo,Go,Aa,Sa,sr,Ko,Lo,Ht,tn,ao,Vr,rn,Xt,nr;if(W()){V.style.width="100%",V.style.maxWidth="100%";let Yt=(We=(at=n.launcher)==null?void 0:at.composerBar)!=null?We:{},ir=Y.dataset.state==="expanded",nn=(qt=Yt.expandedSize)!=null?qt:"anchored";if(!(ir&&nn!=="fullscreen")){oe.style.background="",oe.style.border="",oe.style.borderRadius="",oe.style.overflow="",oe.style.boxShadow="";return}let yr=(mr=(wt=n.theme)==null?void 0:wt.components)==null?void 0:mr.panel,jn=Da(n),so=(Jo,vi)=>{var us;return Jo==null||Jo===""?vi:(us=Ha(jn,Jo))!=null?us:Jo},bi="1px solid var(--persona-border)",wi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ci="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";oe.style.background="var(--persona-surface, #ffffff)",oe.style.border=so(yr==null?void 0:yr.border,bi),oe.style.borderRadius=so(yr==null?void 0:yr.borderRadius,Ci),oe.style.boxShadow=so(yr==null?void 0:yr.shadow,wi),oe.style.overflow="hidden";return}let c=br(n),g=(Gt=(Pr=n.launcher)==null?void 0:Pr.sidebarMode)!=null?Gt:!1,b=c||g||((Ir=(qr=n.launcher)==null?void 0:qr.fullHeight)!=null?Ir:!1),S=((ut=n.launcher)==null?void 0:ut.enabled)===!1,D=(jr=(At=n.theme)==null?void 0:At.components)==null?void 0:jr.panel,F=Da(n),z=(Yt,ir)=>{var nn;return Yt==null||Yt===""?ir:(nn=Ha(F,Yt))!=null?nn:Yt},J=(Dr=e.ownerDocument.defaultView)!=null?Dr:window,$=(Vo=(jo=n.launcher)==null?void 0:jo.mobileFullscreen)!=null?Vo:!0,De=(Aa=(Go=n.launcher)==null?void 0:Go.mobileBreakpoint)!=null?Aa:640,Ae=J.innerWidth<=De,le=$&&Ae&&T,Le=(sr=(Sa=n.launcher)==null?void 0:Sa.position)!=null?sr:"bottom-left",Ne=Le==="bottom-left"||Le==="top-left",Ye=(Lo=(Ko=n.launcher)==null?void 0:Ko.zIndex)!=null?Lo:Nr,xt=g||le?"none":"1px solid var(--persona-border)",it=le?"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&&!le&&(it="none",xt="none");let Ct=g||le?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=z(D==null?void 0:D.border,xt),Ge=z(D==null?void 0:D.shadow,it),Ve=z(D==null?void 0:D.borderRadius,Ct),nt=Ee.scrollTop;e.style.cssText="",Y.style.cssText="",V.style.cssText="",oe.style.cssText="",Ee.style.cssText="",Xe.style.cssText="";let B=()=>{var ir;if(nt<=0)return;((ir=Ee.ownerDocument.defaultView)!=null?ir:window).requestAnimationFrame(()=>{if(Ee.scrollTop===nt)return;let nn=Ee.scrollHeight-Ee.clientHeight;nn<=0||(Ee.scrollTop=Math.min(nt,nn))})};if(le){Y.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"),Y.style.cssText=`
|
|
80
|
+
`,E.addEventListener("click",()=>{u=x,T.forEach((B,H)=>{let W=H<x;B.classList.toggle("selected",W),B.setAttribute("aria-checked",H===x-1?"true":"false")})}),T.push(E),k.appendChild(E)}m.appendChild(k);let S=null;if(d){let x=document.createElement("div");x.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"),x.appendChild(S),m.appendChild(x)}let M=document.createElement("div");M.className="persona-feedback-actions";let v=document.createElement("button");v.type="button",v.className="persona-feedback-btn persona-feedback-btn-skip",v.textContent=i,v.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(u===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}b.disabled=!0,b.textContent="Submitting...";try{let x=(S==null?void 0:S.value.trim())||void 0;await t(u,x),p.remove()}catch(x){b.disabled=!1,b.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),M.appendChild(v),M.appendChild(b),m.appendChild(M),p.appendChild(m),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 m=null,f=document.createElement("div");f.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,y.appendChild(C);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=o,y.appendChild(k),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 M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let v=document.createElement("span");v.className="persona-feedback-label-high",v.textContent=p,S.appendChild(M),S.appendChild(v);let b=document.createElement("div");b.className="persona-feedback-numbers";let x=[];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",()=>{m=N,x.forEach((se,ve)=>{se.classList.toggle("selected",ve===N),se.setAttribute("aria-checked",ve===N?"true":"false")})}),x.push(q),b.appendChild(q)}T.appendChild(S),T.appendChild(b),f.appendChild(T);let E=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),N.appendChild(E),f.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(m===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let N=(E==null?void 0:E.value.trim())||void 0;await t(m,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),f.appendChild(B),u.appendChild(f),u}var Xs="persona-chat-history",Tv=30*1e3,Mv={"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 kv(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=Mv[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 Ev(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 Lv(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},sy=e=>e.map(t=>({...t,streaming:!1})),ay=(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 m=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.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 iy(e){var i,d,l,p;let t=h("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=h("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,Af,Sf,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=ey(),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:w,open:A}=g;return A&&(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 u(w)});else{let g=c!=null?c:{messages:[],metadata:{}},w=u(g);w.metadata&&(d=yu(w.metadata)),(ju=w.messages)!=null&&ju.length&&(n={...n,initialMessages:w.messages}),(Vu=w.artifacts)!=null&&Vu.length&&(n={...n,initialArtifacts:w.artifacts,initialSelectedArtifactId:(Gu=w.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 m=()=>d,f=c=>{var w;d=(w=c({...d}))!=null?w:{},bs()},y=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ri],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[hs.message,hs.messageAndClick],k=ni({parsers:y,handlers:C,getSessionMetadata:m,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let T=(Xu=(Ju=n.launcher)==null?void 0:Ju.enabled)!=null?Xu:!0,S=(Qu=(Yu=n.launcher)==null?void 0:Yu.autoExpand)!=null?Qu:!1,M=(Zu=n.autoFocusInput)!=null?Zu:!1,v=S,b=T,x=(tf=(ef=n.layout)==null?void 0:ef.header)==null?void 0:tf.layout,E=!1,B=()=>Ho(n),H=()=>T||B(),W=B()?!1:T?S:!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=ay(n,k,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,w;s.emit("message:copy",c),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(c.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(w=(g=n.messageActions)==null?void 0:g.onCopy)==null||w.call(g,c)},onFeedback:c=>{var g,w;s.emit("message:feedback",c),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(c.messageId,c.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(w=(g=n.messageActions)==null?void 0:g.onFeedback)==null||w.call(g,c)}},ee=(hf=n.statusIndicator)!=null?hf:{},Ie=c=>{var g,w,A,_;return c==="idle"?(g=ee.idleText)!=null?g:zr.idle:c==="connecting"?(w=ee.connectingText)!=null?w:zr.connecting:c==="connected"?(A=ee.connectedText)!=null?A:zr.connected:c==="error"?(_=ee.errorText)!=null?_:zr.error:zr[c]};function ye(c,g,w,A){if(A==="idle"&&w.idleLink){c.textContent="";let _=document.createElement("a");_.href=w.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}=wx(n),Me=Cx(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,Ae=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=h("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=h("span","persona-flex persona-items-center"),Tt=h("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,w,A,_;if(!j)return;if(he=!0,!Z&&j&&(Z=qx({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=(_=(A=(w=n.features)==null?void 0:w.eventStream)==null?void 0:A.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,w;if(he){if(he=!1,Z&&Z.element.remove(),J.style.display="",xt){xt.style.boxShadow="";let A=(w=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:w.toggleButtonActive;A&&A.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=h("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=Pe("activity","18px","currentColor",1.5);w&&xt.appendChild(w);let A=Me.clearChatButtonWrapper,_=Me.closeButtonWrapper,F=A||_;F&&F.parentNode===Xe?Xe.insertBefore(xt,F):Xe.appendChild(xt),xt.addEventListener("click",()=>{he?_r():Lr()})}let an=c=>{var A,_,F;let g=n.attachments;if(!(g!=null&&g.enabled))return;let w=c.querySelector(".persona-attachment-previews");if(!w){w=h("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=h("input");U.type="file",U.accept=((A=g.allowedTypes)!=null?A: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:w=>{var U;if(!R||R.isStreaming())return;let A=w.trim(),_=(U=mt==null?void 0:mt.hasAttachments())!=null?U:!1;if(!A&&!_)return;ia();let F;_&&(F=[],F.push(...mt.getContentParts()),A&&F.push(Ba(A))),R.sendMessage(A,{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:w=>{n.composer={...n.composer,selectedModelId:w},n.agent&&(n.agent={...n.agent,model:w})},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]"),w=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),_=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&(ke=g),w&&(Y=w),A&&(Q=A),_&&(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"]'),Ae=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=(Sf=(wf=n.layout)==null?void 0:wf.contentMaxWidth)!=null?Sf:B()?(Af=(vf=(Cf=n.launcher)==null?void 0:Cf.composerBar)==null?void 0:vf.contentMaxWidth)!=null?Af:"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&&Ae&&!B()&&(Ae.style.maxWidth=Rr,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),(Tf=n.attachments)!=null&&Tf.enabled&&fe&&Ae){mt=cs.fromConfig(n.attachments),mt.setPreviewsContainer(Ae),fe.addEventListener("change",w=>{let A=w.target;mt==null||mt.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=iy(c);be.appendChild(g)}(()=>{var A,_;let c=(_=(A=n.layout)==null?void 0:A.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}},w=(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&&w(F,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,V)}})();let Pn=c=>{let w=c.target.closest('button[data-expand-header="true"]');if(!w)return;let A=w.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let _=A.getAttribute("data-message-id");if(!_)return;let F=w.getAttribute("data-bubble-type");F==="reasoning"?(zs.has(_)?zs.delete(_):zs.add(_),Tx(_,A)):F==="tool"&&(qs.has(_)?qs.delete(_):qs.add(_),Mx(_,A,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 w=c.target.closest(".persona-message-action-btn[data-action]");if(!w)return;c.preventDefault(),c.stopPropagation();let A=w.closest("[data-actions-for]");if(!A)return;let _=A.getAttribute("data-actions-for");if(!_)return;let F=w.getAttribute("data-action");if(F==="copy"){let $=R.getMessages().find(De=>De.id===_);if($&&G.onCopy){let De=$.content||"";navigator.clipboard.writeText(De).then(()=>{w.classList.add("persona-message-action-success");let Se=Pe("check",14,"currentColor",2);Se&&(w.innerHTML="",w.appendChild(Se)),setTimeout(()=>{w.classList.remove("persona-message-action-success");let ce=Pe("copy",14,"currentColor",2);ce&&(w.innerHTML="",w.appendChild(ce))},2e3)}).catch(Se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Se)}),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(_),w.classList.remove("persona-message-action-active");let Se=Pe(De,14,"currentColor",2);Se&&(w.innerHTML="",w.appendChild(Se))}else{let Se=F==="upvote"?"downvote":"upvote",ce=A.querySelector(`[data-action="${Se}"]`);if(ce){ce.classList.remove("persona-message-action-active");let dt=Pe(Se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(ce.innerHTML="",ce.appendChild(dt))}In.set(_,F),w.classList.add("persona-message-action-active");let Le=Pe(De,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 Qe=R.getMessages().find(gt=>gt.id===_);Qe&&G.onFeedback&&G.onFeedback({type:F,messageId:Qe.id,message:Qe})}}}),Ke.addEventListener("click",c=>{let w=c.target.closest("button[data-approval-action]");if(!w)return;c.preventDefault(),c.stopPropagation();let A=w.closest(".persona-approval-bubble");if(!A)return;let _=A.getAttribute("data-message-id");if(!_)return;let F=w.getAttribute("data-approval-action");if(!F)return;let U=F==="approve"?"approved":"denied",$=R.getMessages().find(Se=>Se.id===_);if(!($!=null&&$.approval))return;let De=A.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 w=c.target.closest("[data-download-artifact]");if(!w)return;c.preventDefault(),c.stopPropagation();let A=w.getAttribute("data-download-artifact");if(!A||((Ne=(Le=(ce=n.features)==null?void 0:ce.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:Ne.call(Le,{type:"download",artifactId:A}))===!0)return;let F=R.getArtifactById(A),U=F==null?void 0:F.markdown,V=(F==null?void 0:F.title)||"artifact";if(!U){let dt=w.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($),Se=document.createElement("a");Se.href=De,Se.download=`${V}.md`,Se.click(),URL.revokeObjectURL(De)}),Ke.addEventListener("click",c=>{var F,U,V;let w=c.target.closest("[data-open-artifact]");if(!w)return;let A=w.getAttribute("data-open-artifact");!A||((V=(U=(F=n.features)==null?void 0:F.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:V.call(U,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),Ee=!1,R.selectArtifact(A),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,w)=>{var V,$,De,Se;let A=g.trim();if(!A||!rt.current)return;let _=(V=c.getAttribute("data-tool-call-id"))!=null?V:"",F=w.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:_,answer:A,answers:w.structured,values:($=w.values)!=null?$:w.source==="multi"?A.split(", "):[A],isFreeText:F,source:w.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,(Se=w.structured)!=null?Se:A):rt.current.sendMessage(A)},er=c=>{var _;let g=rt.current;if(!g)return;let w=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",A=g.getMessages().find(F=>{var U;return((U=F.toolCall)==null?void 0:U.id)===w});A&&g.persistAskUserQuestionProgress(A,{answers:zl(c,A),currentIndex:En(c)})},Pr=c=>Object.entries(c).map(([g,w])=>`${g}: ${Array.isArray(w)?w.join(", "):w}`).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),w=Vs(c);if(g>=w-1)return;let A=(U=rt.current)==null?void 0:U.getMessages().find(V=>{var $;return(($=V.toolCall)==null?void 0:$.id)===c.getAttribute("data-tool-call-id")});A&&(ql(c,A,n,g+1),er(c))};Xt.addEventListener("click",c=>{var F,U,V,$,De,Se,ce,Le,Ne,Qe,gt,dt,Ct,vt;let w=c.target.closest("[data-ask-user-action]");if(!w)return;let A=w.closest("[data-persona-ask-sheet-for]");if(!A)return;let _=w.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),_==="dismiss"){let ze=(F=A.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=w.getAttribute("data-option-label");if(!ze)return;let Fe=A.getAttribute("data-multi-select")==="true",nt=Oo(A);if(nt&&Fe){let D=ms(A)[En(A)],$e=new Set(Array.isArray(D)?D:[]);$e.has(ze)?$e.delete(ze):$e.add(ze),No(A,Array.from($e)),er(A);return}if(nt){No(A,ze),er(A),Nr(A);return}if(Fe){let D=w.getAttribute("aria-pressed")==="true";w.setAttribute("aria-pressed",D?"false":"true"),w.classList.toggle("persona-ask-pill-selected",!D);let $e=A.querySelector('[data-ask-user-action="submit-multi"]');$e&&($e.disabled=cu(A).length===0);return}$t(A,ze,{source:"pick",values:[ze]});return}if(_==="submit-multi"){let ze=cu(A);if(ze.length===0)return;$t(A,ze.join(", "),{source:"multi",values:ze});return}if(_==="open-free-text"){let ze=A.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=A.querySelector('[data-ask-free-text-input="true"]');ze==null||ze.focus();return}if(_==="submit-free-text"){let ze=A.querySelector('[data-ask-free-text-input="true"]'),Fe=(Se=ze==null?void 0:ze.value)!=null?Se:"";if(!Fe.trim())return;if(Oo(A)){No(A,Fe.trim()),er(A),Nr(A);return}$t(A,Fe,{source:"free-text"});return}if(_==="next"||_==="back"){if(!rt.current)return;let ze=(ce=A.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=A.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(A)[En(A)];(typeof at!="string"||at!==D)&&No(A,D)}let $e=_==="next"?1:-1,Ge=En(A)+$e;ql(A,Fe,n,Ge),er(A);return}if(_==="submit-all"){if(!rt.current)return;let ze=(Qe=A.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=A.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(A,D);let $e=zl(A,Fe);rt.current.persistAskUserQuestionProgress(Fe,{answers:$e,currentIndex:En(A)});let Ge=Pr($e);$t(A,Ge||"(submitted)",{source:"submit-all",structured:$e});return}if(_==="skip"){if(!rt.current)return;let ze=(Ct=A.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(A),D=En(A),$e=Vs(A),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(A,"");let at=A.querySelector('[data-ask-free-text-input="true"]');if(at&&(at.value=""),Ge){let Re=zl(A,Fe),jt=Pr(Re);$t(A,jt||"(skipped)",{source:"submit-all",structured:Re});return}ql(A,Fe,n,D+1),er(A);return}}),Xt.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let w=c.target;if(!((F=w.matches)!=null&&F.call(w,'[data-ask-free-text-input="true"]')))return;let A=w.closest("[data-persona-ask-sheet-for]");if(!A)return;c.preventDefault();let _=w.value;if(_.trim()){if(Oo(A)){No(A,_.trim()),er(A),Nr(A);return}$t(A,_,{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=Xt.querySelector("[data-persona-ask-sheet-for]");if(!w||w.getAttribute("data-ask-layout")!=="rows"||w.getAttribute("data-multi-select")==="true")return;let A=Number(c.key),F=w.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[A-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"),w=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||w){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 A=Vt.firstElementChild;if(!A||A===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=A.offsetWidth-_/2;Ft.style.left=`${Math.max(0,F)}px`},zn=()=>{},ln=()=>{var w,A,_,F,U;if(!me||!Ln(n))return;Vl(e,n),Gl(e,n),zn();let c=(F=(_=(A=(w=n.features)==null?void 0:w.artifacts)==null?void 0:A.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=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(be),me=Gx(n,{onSelect:w=>{var A;return(A=rt.current)==null?void 0:A.selectArtifact(w)},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 A,_,F,U;if(!Vt||!me)return;if(!(((F=(_=(A=n.features)==null?void 0:A.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=h("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,Se=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:Yx(Vt,De),$e=nt?0:V.getBoundingClientRect().width||6,Ge=Ne-(ze.clientX-Le),at=Qx(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",Se),Ft=V,Vt.insertBefore(V,me.element),Ir=()=>{V.removeEventListener("pointerdown",Se)}}if(Ft){let V=oe.artifacts.length>0&&!Ee;Ft.classList.toggle("persona-hidden",!V),Co()}},zn=()=>{var De,Se,ce,Le,Ne,Qe,gt,dt,Ct,vt,ze,Fe,nt,D;if(!T||!me||((Se=(De=n.launcher)==null?void 0:De.sidebarMode)!=null?Se:!1)||Tr(n)&&kn(n).reveal==="emerge")return;let A=(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(_&&A.innerWidth<=F||!Xx(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,At,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 Sr=(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)",Ai="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Si="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";be.style.background="var(--persona-surface, #ffffff)",be.style.border=lo(Sr==null?void 0:Sr.border,vi),be.style.borderRadius=lo(Sr==null?void 0:Sr.borderRadius,Si),be.style.boxShadow=lo(Sr==null?void 0:Sr.shadow,Ai),be.style.overflow="hidden";return}let c=Tr(n),g=(Gt=(Hr=n.launcher)==null?void 0:Hr.sidebarMode)!=null?Gt:!1,w=c||g||((Br=(Vr=n.launcher)==null?void 0:Vr.fullHeight)!=null?Br:!1),A=((ft=n.launcher)==null?void 0:ft.enabled)===!1,_=(Gr=(At=n.theme)==null?void 0:At.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,Se=V.innerWidth<=De,ce=$&&Se&&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=`
|
|
81
81
|
position: fixed !important;
|
|
82
82
|
inset: 0 !important;
|
|
83
83
|
width: 100% !important;
|
|
@@ -87,9 +87,9 @@ _Details: ${r.message}_`:n}var Wa=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: ${
|
|
90
|
+
z-index: ${Qe} !important;
|
|
91
91
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
92
|
-
`,
|
|
92
|
+
`,le.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 Wa=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
|
-
`,
|
|
105
|
+
`,be.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 Wa=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
|
-
`,
|
|
116
|
+
`,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0",E=!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)A&&w?(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)"),w&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(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%",A&&(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&&!A&&!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=`
|
|
117
117
|
position: fixed !important;
|
|
118
118
|
top: 0 !important;
|
|
119
119
|
bottom: 0 !important;
|
|
120
|
-
width: ${
|
|
120
|
+
width: ${Qt} !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: ${
|
|
127
|
+
z-index: ${Qe} !important;
|
|
128
128
|
${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
129
|
-
`,
|
|
129
|
+
`,le.style.cssText=`
|
|
130
130
|
position: relative !important;
|
|
131
131
|
display: flex !important;
|
|
132
132
|
flex-direction: column !important;
|
|
@@ -137,9 +137,9 @@ _Details: ${r.message}_`:n}var Wa=class e{constructor(t={},r){this.config=t;this
|
|
|
137
137
|
min-height: 0 !important;
|
|
138
138
|
margin: 0 !important;
|
|
139
139
|
padding: 0 !important;
|
|
140
|
-
box-shadow: ${
|
|
141
|
-
border-radius: ${
|
|
142
|
-
`,
|
|
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=`
|
|
143
143
|
display: flex !important;
|
|
144
144
|
flex-direction: column !important;
|
|
145
145
|
flex: 1 1 0% !important;
|
|
@@ -148,29 +148,29 @@ _Details: ${r.message}_`:n}var Wa=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: ${
|
|
151
|
+
border-radius: ${Fe} !important;
|
|
152
152
|
border: ${vt} !important;
|
|
153
|
-
`,
|
|
153
|
+
`,Je.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 Yt="max-height: -moz-available !important; max-height: stretch !important;",ir=g?"":"padding-top: 1.25em !important;",nn=g?"":`z-index: ${(nr=(Xt=n.launcher)==null?void 0:Xt.zIndex)!=null?nr:Nr} !important;`;Y.style.cssText+=Yt+ir+nn}B()};Rn(),Po(e,n),Ul(e,n),zl(e,n);let Lt=[];Lt.push(()=>{document.removeEventListener("keydown",$r)});let pr=null,ur=null;Lt.push(()=>{pr==null||pr(),pr=null,ur==null||ur(),ur=null}),Fe&&Lt.push(()=>{Fe==null||Fe.disconnect(),Fe=null}),Lt.push(()=>{Tr==null||Tr(),Tr=null,Zn(),pt&&(pt.remove(),pt=null),Et==null||Et.element.style.removeProperty("width"),Et==null||Et.element.style.removeProperty("maxWidth")}),be&&Lt.push(()=>{fe!==null&&(cancelAnimationFrame(fe),fe=null),ge==null||ge.destroy(),ge=null,K==null||K.destroy(),K=null,X=null});let ln=null,wo=()=>{ln&&(ln(),ln=null),n.colorScheme==="auto"&&(ln=bl(()=>{Po(e,n)}))};wo(),Lt.push(()=>{ln&&(ln(),ln=null)});let Cn=(wf=n.features)==null?void 0:wf.streamAnimation;if(Cn!=null&&Cn.type&&Cn.type!=="none"){let c=Fs(Cn.type,Cn.plugins);c&&(Up(c,e),Lt.push(()=>px(e)))}let Wn=Hx(Dt),dn=null,q,Se=!1,cn=ax(),Hn=new Map,zn=new Map,Ja=0,Bn=vl(),Dn=0,On=null,eo=!1,$o=!1,ri=4,Xa=24,ni=80,ha=new Map,kt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ya=(vf=(Cf=n.voiceRecognition)==null?void 0:Cf.autoResume)!=null?vf:!1,vn=c=>{a.emit("voice:state",{active:kt.active,source:c,timestamp:Date.now()})},en=()=>{f(c=>({...c,voiceState:{active:kt.active,timestamp:Date.now(),manuallyDeactivated:kt.manuallyDeactivated}}))},oi=()=>{var S,D;if(((S=n.voiceRecognition)==null?void 0:S.enabled)===!1)return;let c=fu(d.voiceState),g=!!c.active,b=Number((D=c.timestamp)!=null?D:0);kt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<ov&&setTimeout(()=>{var F,z;kt.active||(kt.manuallyDeactivated=!1,((z=(F=n.voiceRecognition)==null?void 0:F.provider)==null?void 0:z.type)==="runtype"?q.toggleVoice().then(()=>{kt.active=q.isVoiceActive(),vn("restore"),q.isVoiceActive()&&j()}):qo("restore"))},1e3)},ai=()=>q?Xx(q.getMessages()).filter(c=>!c.__skipPersist):[];function xa(c){if(!(i!=null&&i.save))return;let b={messages:c?Xx(c):q?ai():[],metadata:d,artifacts:P.artifacts,selectedArtifactId:P.selectedId};try{let S=i.save(b);S instanceof Promise&&S.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let to=null,si=()=>Y.querySelector("#persona-scroll-container")||Ee,Fo=()=>{to!==null&&(cancelAnimationFrame(to),to=null),eo=!1},Qa=()=>{On!==null&&(cancelAnimationFrame(On),On=null),$o=!1,Fo()},ro=()=>{if(!lt()||ce){ht.parentNode&&ht.remove(),ht.style.display="none";return}ht.parentNode!==oe&&oe.appendChild(ht),Hr();let c=Os(Ee)>0;ht.style.display=Bn.isFollowing()||!c?"none":""},Za=()=>{Bn.pause()&&(Qa(),ro())},Co=()=>{Bn.resume(),ro()},vo=(c=!1)=>{Bn.isFollowing()&&(!c&&!Se||(On!==null&&(cancelAnimationFrame(On),On=null),$o=!0,On=requestAnimationFrame(()=>{On=null,$o=!1,Bn.isFollowing()&&ii(si(),c?220:140)})))},ii=(c,g=500)=>{let b=c.scrollTop,S=Os(c),D=S-b;if(Math.abs(D)<1){Dn=c.scrollTop;return}if(Math.abs(D)>=ni){Fo(),eo=!0,c.scrollTop=S,Dn=c.scrollTop,eo=!1;return}Fo();let F=performance.now();eo=!0;let z=$=>1-Math.pow(1-$,3),J=$=>{if(!Bn.isFollowing()){Fo();return}let De=Os(c);De!==S&&(S=De,D=S-b);let Ae=$-F,le=Math.min(Ae/g,1),Le=z(le),Ne=b+D*Le;c.scrollTop=Ne,Dn=c.scrollTop,le<1?to=requestAnimationFrame(J):(c.scrollTop=S,Dn=c.scrollTop,to=null,eo=!1)};to=requestAnimationFrame(J)},li=c=>{let g=new Map;c.forEach(b=>{let S=ha.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!S&&b.role==="assistant"&&a.emit("assistant:message",b),b.role==="assistant"&&(S!=null&&S.streaming)&&b.streaming===!1&&a.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(S?b.approval.status!=="pending"&&a.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):a.emit("approval:requested",{approval:b.approval,message:b}))}),ha.clear(),g.forEach((b,S)=>{ha.set(S,b)})},Uo=(c,g,b)=>{var it,Ct,vt,Ge,Ve,nt;let S=document.createElement("div"),F=(()=>{var Ue;let B=o.find(Ke=>Ke.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Ue=n.loadingIndicator)!=null&&Ue.render)return n.loadingIndicator.render})(),z=(B,Ue)=>Ue==null?!1:typeof Ue=="string"?(B.textContent=Ue,!0):(B.appendChild(Ue),!0),J=new Set,$=new Set,De=o.some(B=>B.renderAskUserQuestion),Ae=[],le=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(B=>{var qr,Ir,ut,At,jr,Dr,jo,Vo,Go,Aa,Sa,sr,Ko,Lo;J.add(B.id);let Ue=De&&mo(B),Ke=!Ue&&B.role==="assistant"&&!B.variant&&Le&&Gl(B);if(!Ke&&zn.has(B.id)){let Ht=c.querySelector(`#wrapper-${B.id}`);Ht==null||Ht.removeAttribute("data-preserve-runtime"),zn.delete(B.id)}let at=mo(B)?`:${(qr=B.agentMetadata)!=null&&qr.askUserQuestionAnswered?"a":"u"}:${(Ir=B.agentMetadata)!=null&&Ir.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",We=ox(B,Ja)+at,qt=Ue||Ke?null:sx(cn,B.id,We);if(qt){S.appendChild(qt.cloneNode(!0)),mo(B)&&((ut=B.toolCall)!=null&&ut.id)&&((At=B.agentMetadata)==null?void 0:At.awaitingLocalTool)===!0&&!((jr=B.agentMetadata)!=null&&jr.askUserQuestionAnswered)&&($.add(B.toolCall.id),qa(B,n,Be.composerOverlay));return}let wt=null,mr=o.find(Ht=>!!(B.variant==="reasoning"&&Ht.renderReasoning||B.variant==="tool"&&Ht.renderToolCall||B.variant==="approval"&&Ht.renderApproval||!B.variant&&Ht.renderMessage)),Pr=(Dr=n.layout)==null?void 0:Dr.messages;if(mo(B)&&((jo=B.agentMetadata)==null?void 0:jo.askUserQuestionAnswered)===!0){Hn.delete(B.id);let Ht=c.querySelector(`#wrapper-${B.id}`);Ht==null||Ht.removeAttribute("data-preserve-runtime");return}if(mo(B)&&((Go=(Vo=n.features)==null?void 0:Vo.askUserQuestion)==null?void 0:Go.enabled)!==!1){let Ht=o.find(tn=>typeof tn.renderAskUserQuestion=="function");if(Ht&&pe.current){let tn=Hn.get(B.id),ao=tn!==We,Vr=null;if(ao){let{payload:nr,complete:Yt}=go(B),ir=B.id,nn=()=>{var un;return(un=pe.current)==null?void 0:un.getMessages().find(yr=>yr.id===ir)};Vr=Ht.renderAskUserQuestion({message:B,payload:nr,complete:Yt,resolve:un=>{var jn;let yr=nn();yr&&((jn=pe.current)==null||jn.resolveAskUserQuestion(yr,un))},dismiss:()=>{var yr,jn,so;let un=nn();(yr=un==null?void 0:un.agentMetadata)!=null&&yr.awaitingLocalTool&&((jn=pe.current)==null||jn.markAskUserQuestionResolved(un),(so=pe.current)==null||so.resolveAskUserQuestion(un,"(dismissed)"))},config:n})}let rn=tn!=null;if(ao&&Vr===null&&!rn){((Aa=B.agentMetadata)==null?void 0:Aa.awaitingLocalTool)===!0&&!((Sa=B.agentMetadata)!=null&&Sa.askUserQuestionAnswered)&&($.add(B.toolCall.id),qa(B,n,Be.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${B.id}`,Xt.setAttribute("data-wrapper-id",B.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),S.appendChild(Xt),Ae.push({messageId:B.id,fingerprint:We,bubble:Vr});return}else{((sr=B.agentMetadata)==null?void 0:sr.awaitingLocalTool)===!0&&!((Ko=B.agentMetadata)!=null&&Ko.askUserQuestionAnswered)&&($.add(B.toolCall.id),qa(B,n,Be.composerOverlay));return}}else if(mr)if(B.variant==="reasoning"&&B.reasoning&&mr.renderReasoning){if(!Oe)return;wt=mr.renderReasoning({message:B,defaultRenderer:()=>Qp(B,n),config:n})}else if(B.variant==="tool"&&B.toolCall&&mr.renderToolCall){if(!et)return;wt=mr.renderToolCall({message:B,defaultRenderer:()=>Zp(B,n),config:n})}else if(B.variant==="approval"&&B.approval&&mr.renderApproval){if(n.approval===!1)return;wt=mr.renderApproval({message:B,defaultRenderer:()=>iu(B,n),config:n})}else mr.renderMessage&&(wt=mr.renderMessage({message:B,defaultRenderer:()=>{let Ht=Na(B,b,Pr,n.messageActions,rt,{loadingIndicatorRenderer:F,widgetConfig:n});return B.role!=="user"&&cu(Ht,B,n,q),Ht},config:n}));if(!wt&&Ke){let Ht=Kl(B);if(Ht){let tn=zn.get(B.id),ao=tn!==We,Vr=n.wrapComponentDirectiveInBubble!==!1,rn=null;if(ao){let Xt=Vl(Ht,{config:n,message:B,transform:b});if(Xt)if(Vr){let nr=document.createElement("div");if(nr.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(" "),nr.id=`bubble-${B.id}`,nr.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Yt=document.createElement("div");Yt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Yt.innerHTML=b({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),nr.appendChild(Yt)}nr.appendChild(Xt),rn=nr}else{let nr=document.createElement("div");if(nr.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",nr.id=`bubble-${B.id}`,nr.setAttribute("data-message-id",B.id),nr.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Yt=document.createElement("div");Yt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Yt.innerHTML=b({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),nr.appendChild(Yt)}nr.appendChild(Xt),rn=nr}}if(rn||tn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${B.id}`,Xt.setAttribute("data-wrapper-id",B.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),Vr||Xt.classList.add("persona-w-full"),S.appendChild(Xt),le.push({messageId:B.id,fingerprint:We,bubble:rn});return}}}if(!wt)if(B.variant==="reasoning"&&B.reasoning){if(!Oe)return;wt=Qp(B,n)}else if(B.variant==="tool"&&B.toolCall){if(!et)return;wt=Zp(B,n)}else if(B.variant==="approval"&&B.approval){if(n.approval===!1)return;wt=iu(B,n)}else{let Ht=(Lo=n.layout)==null?void 0:Lo.messages;Ht!=null&&Ht.renderUserMessage&&B.role==="user"?wt=Ht.renderUserMessage({message:B,config:n,streaming:!!B.streaming}):Ht!=null&&Ht.renderAssistantMessage&&B.role==="assistant"?wt=Ht.renderAssistantMessage({message:B,config:n,streaming:!!B.streaming}):wt=Na(B,b,Ht,n.messageActions,rt,{loadingIndicatorRenderer:F,widgetConfig:n}),B.role!=="user"&&wt&&cu(wt,B,n,q)}let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-${B.id}`,Gt.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Gt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Gt.classList.add("persona-w-full"),Gt.appendChild(wt),ix(cn,B.id,We,Gt),S.appendChild(Gt)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ue=>{let Ke=Ue.getAttribute("data-persona-ask-sheet-for");Ke&&!$.has(Ke)&&Oo(Be.composerOverlay,Ke)}),(Ct=(it=n.features)==null?void 0:it.toolCallDisplay)!=null&&Ct.grouped){let B=[],Ue=[];g.forEach(Ke=>{if(Ke.variant==="tool"&&Ke.toolCall&&et){Ue.push(Ke);return}Ue.length>1&&B.push(Ue),Ue=[]}),Ue.length>1&&B.push(Ue),B.forEach((Ke,at)=>{var Ir,ut;let We=Ke.map(At=>Array.from(S.children).find(jr=>jr instanceof HTMLElement&&jr.getAttribute("data-wrapper-id")===At.id)).filter(At=>!!At);if(We.length<2)return;let qt=document.createElement("div");qt.className="persona-flex",qt.id=`wrapper-tool-group-${at}-${Ke[0].id}`,qt.setAttribute("data-wrapper-id",`tool-group-${at}-${Ke[0].id}`);let wt=document.createElement("div");wt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",wt.setAttribute("data-persona-tool-group","true");let mr=document.createElement("div");mr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Pr=`Called ${Ke.length} tools`,Gt=(ut=(Ir=n.toolCall)==null?void 0:Ir.renderGroupedSummary)==null?void 0:ut.call(Ir,{messages:Ke,toolCalls:Ke.map(At=>At.toolCall).filter(At=>!!At),defaultSummary:Pr,config:n});z(mr,Gt)||(mr.textContent=Pr);let qr=document.createElement("div");qr.className="persona-tool-group-stack persona-flex persona-flex-col",wt.append(mr,qr),qt.appendChild(wt),We[0].before(qt),We.forEach((At,jr)=>{let Dr=document.createElement("div");Dr.className="persona-tool-group-item persona-relative",Dr.setAttribute("data-persona-tool-group-item","true"),jr<We.length-1&&Dr.setAttribute("data-persona-tool-group-connector","true"),Dr.appendChild(At),qr.appendChild(Dr)})})}lx(cn,J);let Ne=g.some(B=>B.role==="assistant"&&B.streaming),Ye=g[g.length-1],xt=(Ye==null?void 0:Ye.role)==="assistant"&&!Ye.streaming&&Ye.variant!=="approval";if(Se&&g.some(B=>B.role==="user")&&!Ne&&!xt){let B={config:n,streaming:!0,location:"standalone",defaultRenderer:ua},Ue=o.find(at=>at.renderLoadingIndicator),Ke=null;if(Ue!=null&&Ue.renderLoadingIndicator&&(Ke=Ue.renderLoadingIndicator(B)),Ke===null&&((vt=n.loadingIndicator)!=null&&vt.render)&&(Ke=n.loadingIndicator.render(B)),Ke===null&&(Ke=ua()),Ke){let at=document.createElement("div"),We=((Ge=n.loadingIndicator)==null?void 0:Ge.showBubble)!==!1;at.className=We?["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(Ke);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-typing-indicator",qt.setAttribute("data-wrapper-id","typing-indicator"),qt.appendChild(at),S.appendChild(qt)}}if(!Se&&g.length>0){let B=g[g.length-1],Ue={config:n,lastMessage:B,messageCount:g.length},Ke=o.find(We=>We.renderIdleIndicator),at=null;if(Ke!=null&&Ke.renderIdleIndicator&&(at=Ke.renderIdleIndicator(Ue)),at===null&&((Ve=n.loadingIndicator)!=null&&Ve.renderIdle)&&(at=n.loadingIndicator.renderIdle(Ue)),at){let We=document.createElement("div"),qt=((nt=n.loadingIndicator)==null?void 0:nt.showBubble)!==!1;We.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(" "),We.setAttribute("data-idle-indicator","true"),We.appendChild(at);let wt=document.createElement("div");wt.className="persona-flex",wt.id="wrapper-idle-indicator",wt.setAttribute("data-wrapper-id","idle-indicator"),wt.appendChild(We),S.appendChild(wt)}}if(wl(c,S),Ae.length>0)for(let{messageId:B,fingerprint:Ue,bubble:Ke}of Ae){let at=c.querySelector(`#wrapper-${B}`);at&&Ke!==null&&(at.replaceChildren(Ke),at.setAttribute("data-bubble-fp",Ue),Hn.set(B,Ue))}if(Hn.size>0)for(let B of Hn.keys())J.has(B)||Hn.delete(B);if(le.length>0)for(let{messageId:B,fingerprint:Ue,bubble:Ke}of le){let at=c.querySelector(`#wrapper-${B}`);at&&Ke!==null&&(at.replaceChildren(Ke),at.setAttribute("data-bubble-fp",Ue),zn.set(B,Ue))}if(zn.size>0)for(let B of zn.keys())J.has(B)||zn.delete(B)},Ao=null,di=()=>{var b;if(Ao)return;let c=S=>{let D=S.composedPath();D.includes(Y)||Ce&&D.includes(Ce)||Kt(!1,"user")};Ao=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},es=()=>{var g;if(!Ao)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Ao,!0),Ao=null};Lt.push(()=>es());let So=null,ci=()=>{var b;if(So)return;let c=S=>{S.key==="Escape"&&(S.isComposing||Kt(!1,"user"))};So=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},ts=()=>{var g;if(!So)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",So,!0),So=null};Lt.push(()=>ts());let To=!1,rs=new Set,pi=()=>{var g,b,S,D;let c=(S=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:S.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},no=()=>{var Ct,vt,Ge,Ve;if(!W())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(I){c.classList.remove("persona-pill-peek--visible");return}let b=(Ct=q==null?void 0:q.getMessages())!=null?Ct:[],S;for(let nt=b.length-1;nt>=0;nt--){let B=b[nt];if(B.role==="assistant"&&B.content){S=B;break}}if(!S){c.classList.remove("persona-pill-peek--visible");return}let D=S.content,F=!!S.streaming,z=pi(),J=Tl(z),$=J.type!=="none"?Fs(J.type,z==null?void 0:z.plugins):null,De=((vt=$==null?void 0:$.isAnimating)==null?void 0:vt.call($,S))===!0,Ae=$!==null&&(F||De);Ae&&$&&!rs.has($.name)&&(Up($,e),rs.add($.name));let le=Ae&&($!=null&&$.containerClass)?$.containerClass:null,Le=(Ge=g.dataset.personaPeekStreamClass)!=null?Ge:null;Le&&Le!==le&&(g.classList.remove(Le),delete g.dataset.personaPeekStreamClass),le&&Le!==le&&(g.classList.add(le),g.dataset.personaPeekStreamClass=le),Ae?(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 Ne=Ae?Ml(D,J.buffer,$,S,F):D;if(Ae&&J.placeholder==="skeleton"&&F&&(!Ne||!Ne.trim())){let nt=document.createElement("div"),B=zs();B.classList.add("persona-pill-peek__skeleton"),nt.appendChild(B),wl(g,nt)}else{let nt=Math.max(0,Ne.length-100),B=Ne.length>100?Ne.slice(-100):Ne,Ue=na(B);if(!Ae||!$){let Ke=Ne.length>100?`\u2026${B}`:B;g.textContent!==Ke&&(g.textContent=Ke)}else{let Ke=Ue;($.wrap==="char"||$.wrap==="word")&&(Ke=Us(Ue,$.wrap,`peek-${S.id}`,{skipTags:$.skipTags,startIndex:nt}));let at=document.createElement("div");if(at.innerHTML=Ke,$.useCaret&&B.length>0){let We=kl(),qt=at.querySelectorAll(".persona-stream-char, .persona-stream-word"),wt=qt[qt.length-1];wt!=null&&wt.parentNode?wt.parentNode.insertBefore(We,wt.nextSibling):at.appendChild(We)}wl(g,at),(Ve=$.onAfterRender)==null||Ve.call($,{container:g,bubble:c,messageId:S.id,message:S,speed:J.speed,duration:J.duration})}}let it=Se||To;c.classList.toggle("persona-pill-peek--visible",it)};if(W()){let c=Be.peekBanner;if(c){let S=D=>{D.preventDefault(),D.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",S),Lt.push(()=>{c.removeEventListener("pointerdown",S)})}let g=()=>{To||(To=!0,no())},b=()=>{To&&(To=!1,no())};V.addEventListener("pointerenter",g),V.addEventListener("pointerleave",b),Lt.push(()=>{V.removeEventListener("pointerenter",g),V.removeEventListener("pointerleave",b)}),Ce&&(Ce.addEventListener("pointerenter",g),Ce.addEventListener("pointerleave",b),Lt.push(()=>{Ce.removeEventListener("pointerenter",g),Ce.removeEventListener("pointerleave",b)}))}let ui=c=>{var Le,Ne,Ye,xt,it,Ct,vt,Ge;let g=(Ne=(Le=n.launcher)==null?void 0:Le.composerBar)!=null?Ne:{},b=(Ye=g.expandedSize)!=null?Ye:"anchored",S=(xt=g.bottomOffset)!=null?xt:"16px",D=g.collapsedMaxWidth,F=(it=g.expandedMaxWidth)!=null?it:"880px",z=(Ct=g.expandedTopOffset)!=null?Ct:"5vh",J=(vt=g.modalMaxWidth)!=null?vt:"880px",$=(Ge=g.modalMaxHeight)!=null?Ge:"min(90vh, 800px)",De="calc(100vw - 32px)",Ae="var(--persona-pill-area-height, 80px)",le=Y.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",Ce){let Ve=Ce.style;Ve.bottom=S,Ve.width=D!=null?D:""}if(c&&b!=="fullscreen"){if(b==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=J,le.maxWidth=De,le.maxHeight=$,le.height=$;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${S} + ${Ae})`,le.top=z,le.width=F,le.maxWidth=De}},Mo=()=>{var $,De,Ae,le,Le,Ne,Ye,xt;if(!R())return;if(W()){let Ct=(Ae=((De=($=n.launcher)==null?void 0:$.composerBar)!=null?De:{}).expandedSize)!=null?Ae:"anchored",vt=I?"expanded":"collapsed";Y.dataset.state=vt,Y.dataset.expandedSize=Ct,Ce&&(Ce.dataset.state=vt,Ce.dataset.expandedSize=Ct),Y.style.removeProperty("display"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ui(I),oe.style.display=I?"flex":"none",Rn(),I?(di(),ci()):(es(),ts()),no();return}let c=br(n),g=(le=e.ownerDocument.defaultView)!=null?le:window,b=(Ne=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ne:640,S=(xt=(Ye=n.launcher)==null?void 0:Ye.mobileFullscreen)!=null?xt:!0,D=g.innerWidth<=b,F=S&&D&&T,z=Mn(n).reveal;I?(Y.style.removeProperty("display"),Y.style.display=c?"flex":"",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0"),V.classList.add("persona-scale-100","persona-opacity-100"),je?je.element.style.display="none":st&&(st.style.display="none")):(c?c&&(z==="overlay"||z==="push")&&!F?(Y.style.removeProperty("display"),Y.style.display="flex",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.setProperty("display","none","important"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.display="",Y.classList.add("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100"),V.classList.add("persona-scale-95","persona-opacity-0")),je?je.element.style.display=c?"none":"":st&&(st.style.display=c?"none":""))},Kt=(c,g="user")=>{var F,z;if(!R()||I===c)return;let b=I;I=c,Mo();let S=(()=>{var Ye,xt,it,Ct,vt,Ge,Ve,nt,B,Ue;let J=(xt=(Ye=n.launcher)==null?void 0:Ye.sidebarMode)!=null?xt:!1,$=(it=e.ownerDocument.defaultView)!=null?it:window,De=(vt=(Ct=n.launcher)==null?void 0:Ct.mobileFullscreen)!=null?vt:!0,Ae=(Ve=(Ge=n.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?Ve:640,le=$.innerWidth<=Ae,Le=br(n)&&De&&le,Ne=W()&&((Ue=(B=(nt=n.launcher)==null?void 0:nt.composerBar)==null?void 0:B.expandedSize)!=null?Ue:"fullscreen")==="fullscreen";return J||De&&le&&T||Le||Ne})();if(I&&S){if(!pr){let J=e.getRootNode(),$=J instanceof ShadowRoot?J.host:e.closest(".persona-host");$&&(pr=zp($,(z=(F=n.launcher)==null?void 0:F.zIndex)!=null?z:Nr))}ur||(ur=qp(e.ownerDocument))}else I||(pr==null||pr(),pr=null,ur==null||ur(),ur=null);I&&(Vt(),vo(!0));let D={open:I,source:g,timestamp:Date.now()};I&&!b?a.emit("widget:opened",D):!I&&b&&a.emit("widget:closed",D),a.emit("widget:state",{open:I,launcherEnabled:T,voiceActive:kt.active,streaming:q.isStreaming()})},ya=c=>{jt(c?"stop":"send"),N&&(N.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=()=>{kt.active||U&&U.focus()};a.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>ba(),200)});let ns=()=>{var b,S,D,F,z,J,$,De,Ae,le,Le;ve.textContent=(S=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?S:"Hello \u{1F44B}",ue.textContent=(F=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",U.placeholder=(J=(z=n.copy)==null?void 0:z.inputPlaceholder)!=null?J:"How can I help...";let c=Ee.querySelector("[data-persona-intro-card]");if(c){let Ne=(($=n.copy)==null?void 0:$.showWelcomeCard)!==!1;c.style.display=Ne?"":"none",Ne?(Ee.classList.remove("persona-gap-3"),Ee.classList.add("persona-gap-6")):(Ee.classList.remove("persona-gap-6"),Ee.classList.add("persona-gap-3"))}!((Ae=(De=n.sendButton)==null?void 0:De.useIcon)!=null&&Ae)&&!(q!=null&&q.isStreaming())&&(ae.textContent=(Le=(le=n.copy)==null?void 0:le.sendButtonLabel)!=null?Le:"Send"),U.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',U.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 qn=null,fi=()=>{qn==null&&(qn=setInterval(()=>{let c=we.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(qn),qn=null;return}let g=Date.now();c.forEach(b=>{let S=Number(b.getAttribute("data-tool-elapsed"));S&&(b.textContent=qi(g-S))})},100))};if(q=new Wa(n,{onMessagesChanged(c){Uo(we,c,ye),fi(),q&&(c.some(D=>D.role==="user")?Wn.render([],q,U,c):Wn.render(n.suggestionChips,q,U,c,n.suggestionChipsConfig)),vo(!Se),li(c);let g=[...c].reverse().find(S=>S.role==="user"),b=kt.lastUserMessageId;g&&g.id!==b&&(kt.lastUserMessageId=g.id,a.emit("user:message",g)),kt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),xa(c),no()},onStatusChanged(c){var S;let g=(S=n.statusIndicator)!=null?S:{};_e(Re,(D=>{var F,z,J,$;return D==="idle"?(F=g.idleText)!=null?F:_r.idle:D==="connecting"?(z=g.connectingText)!=null?z:_r.connecting:D==="connected"?(J=g.connectedText)!=null?J:_r.connected:D==="error"?($=g.errorText)!=null?$:_r.error:_r[D]})(c),g,c)},onStreamingChanged(c){Se=c,ya(c),q&&Uo(we,q.getMessages(),ye),c||vo(!0),no()},onVoiceStatusChanged(c){var g,b;if(((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":te(),_();break;case"speaking":te(),se();break;default:c==="idle"&&q.isBargeInActive()?(te(),j(),N==null||N.setAttribute("aria-label","End voice session")):(kt.active=!1,te(),vn("system"),en());break}},onArtifactsState(c){P=c,sn(),xa()}}),pe.current=q,((Sf=(Af=n.voiceRecognition)==null?void 0:Af.provider)==null?void 0:Sf.type)==="runtype")try{q.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&q.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,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,b,S;c&&(c.metadata&&(d=fu(c.metadata),M.syncFromMetadata()),(g=c.messages)!=null&&g.length&&q.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&q.hydrateArtifacts(c.artifacts,(S=c.selectedArtifactId)!=null?S:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let os=()=>{var g,b,S;!W()||I||!((S=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||S)||Kt(!0,"auto")},as=c=>{var D;if(c.preventDefault(),q.isStreaming()){q.cancel();return}let g=U.value.trim(),b=(D=Rt==null?void 0:Rt.hasAttachments())!=null?D:!1;if(!g&&!b)return;os();let S;b&&(S=[],S.push(...Rt.getContentParts()),g&&S.push(Rs(g))),U.value="",U.style.height="auto",zo(),q.sendMessage(g,{contentParts:S}),b&&Rt.clearAttachments()},mi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},wa={...Cl},Ca=!1,zo=()=>{wa={...Cl}},gi=()=>q.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),hi=c=>{if(!U)return;Ca=!0,U.value=c,U.dispatchEvent(new Event("input",{bubbles:!0})),Ca=!1;let g=U.value.length;U.setSelectionRange(g,g)},ss=()=>{Ca||zo()},is=c=>{if(U){if(mi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=U.selectionStart===0&&U.selectionEnd===0,b=nx({direction:c.key==="ArrowUp"?"up":"down",history:gi(),currentValue:U.value,atStart:g,state:wa});if(wa=b.state,b.handled){c.preventDefault(),b.value!==void 0&&hi(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(q.isStreaming()){c.preventDefault();return}zo(),c.preventDefault(),ae.click()}}},ls=c=>{c.key!=="Escape"||c.isComposing||q.isStreaming()&&c.composedPath().includes(oe)&&(q.cancel(),zo(),c.preventDefault(),c.stopImmediatePropagation())},ds=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!Rt)return;let g=sv(c.clipboardData);g.length!==0&&(c.preventDefault(),await Rt.handleFiles(g))},Ur=null,pn=!1,oo=null,bt=null,cs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qo=(c="user")=>{var F,z,J,$,De,Ae,le;if(pn||q.isStreaming())return;let g=cs();if(!g)return;Ur=new g;let S=(z=((F=n.voiceRecognition)!=null?F:{}).pauseDuration)!=null?z:2e3;Ur.continuous=!0,Ur.interimResults=!0,Ur.lang="en-US";let D=U.value;Ur.onresult=Le=>{let Ne="",Ye="";for(let it=0;it<Le.results.length;it++){let Ct=Le.results[it],vt=Ct[0].transcript;Ct.isFinal?Ne+=vt+" ":Ye=vt}let xt=D+Ne+Ye;U.value=xt,oo&&clearTimeout(oo),(Ne||Ye)&&(oo=window.setTimeout(()=>{let it=U.value.trim();it&&Ur&&pn&&(_n(),U.value="",U.style.height="auto",q.sendMessage(it,{viaVoice:!0}))},S))},Ur.onerror=Le=>{Le.error!=="no-speech"&&_n()},Ur.onend=()=>{if(pn){let Le=U.value.trim();Le&&Le!==D.trim()&&(U.value="",U.style.height="auto",q.sendMessage(Le,{viaVoice:!0})),_n()}};try{if(Ur.start(),pn=!0,kt.active=!0,c!=="system"&&(kt.manuallyDeactivated=!1),vn(c),en(),N){let Le=(J=n.voiceRecognition)!=null?J:{};bt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:($=Le.iconName)!=null?$:"mic",iconSize:parseFloat((le=(Ae=Le.iconSize)!=null?Ae:(De=n.sendButton)==null?void 0:De.size)!=null?le:"40")||24};let Ne=Le.recordingBackgroundColor,Ye=Le.recordingIconColor,xt=Le.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Ye!=null?Ye:"var(--persona-voice-recording-indicator, #ffffff)",Ye){let it=N.querySelector("svg");it&&it.setAttribute("stroke",Ye)}xt&&(N.style.borderColor=xt),N.setAttribute("aria-label","Stop voice recognition")}}catch{_n("system")}},_n=(c="user")=>{if(pn){if(pn=!1,oo&&(clearTimeout(oo),oo=null),Ur){try{Ur.stop()}catch{}Ur=null}if(kt.active=!1,vn(c),en(),N){if(N.classList.remove("persona-voice-recording"),bt){N.style.backgroundColor=bt.backgroundColor,N.style.color=bt.color,N.style.borderColor=bt.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",bt.color||"currentColor"),bt=null}N.setAttribute("aria-label","Start voice recognition")}}},xi=(c,g)=>{var Ct,vt,Ge,Ve,nt,B,Ue,Ke;let b=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(!(b||S))return null;let F=y("div","persona-send-button-wrapper"),z=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");z.type="button",z.setAttribute("aria-label","Start voice recognition");let J=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",$=(Ge=g==null?void 0:g.size)!=null?Ge:"40px",De=(Ve=c==null?void 0:c.iconSize)!=null?Ve:$,Ae=parseFloat(De)||24,le=(nt=c==null?void 0:c.backgroundColor)!=null?nt:g==null?void 0:g.backgroundColor,Le=(B=c==null?void 0:c.iconColor)!=null?B:g==null?void 0:g.textColor;z.style.width=De,z.style.height=De,z.style.minWidth=De,z.style.minHeight=De,z.style.fontSize="18px",z.style.lineHeight="1",Le?z.style.color=Le:z.style.color="var(--persona-text, #111827)";let Ye=Pe(J,Ae,Le||"currentColor",1.5);Ye?z.appendChild(Ye):z.textContent="\u{1F3A4}",le?z.style.backgroundColor=le:z.style.backgroundColor="",c!=null&&c.borderWidth&&(z.style.borderWidth=c.borderWidth,z.style.borderStyle="solid"),c!=null&&c.borderColor&&(z.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(z.style.paddingLeft=c.paddingX,z.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(z.style.paddingTop=c.paddingY,z.style.paddingBottom=c.paddingY),F.appendChild(z);let xt=(Ue=c==null?void 0:c.tooltipText)!=null?Ue:"Start voice recognition";if(((Ke=c==null?void 0:c.showTooltip)!=null?Ke:!1)&&xt){let at=y("div","persona-send-button-tooltip");at.textContent=xt,F.appendChild(at)}return{micButton:z,micButtonWrapper:F}},ko=()=>{var g,b,S,D,F;if(!N||bt)return;let c=(g=n.voiceRecognition)!=null?g:{};bt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((F=(D=c.iconSize)!=null?D:(S=n.sendButton)==null?void 0:S.size)!=null?F:"40")||24}},ot=(c,g)=>{var F,z,J,$,De;if(!N)return;let b=N.querySelector("svg");b&&b.remove();let S=(De=bt==null?void 0:bt.iconSize)!=null?De:parseFloat(($=(J=(F=n.voiceRecognition)==null?void 0:F.iconSize)!=null?J:(z=n.sendButton)==null?void 0:z.size)!=null?$:"40")||24,D=Pe(c,S,g,1.5);D&&N.appendChild(D)},L=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},j=()=>{var D;if(!N)return;ko();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,S=c.recordingBorderColor;if(L(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let F=N.querySelector("svg");F&&F.setAttribute("stroke",b)}S&&(N.style.borderColor=S),N.setAttribute("aria-label","Stop voice recognition")},_=()=>{var J,$,De,Ae,le,Le,Ne,Ye;if(!N)return;ko();let c=(J=n.voiceRecognition)!=null?J:{},g=q.getVoiceInterruptionMode(),b=($=c.processingIconName)!=null?$:"loader",S=(Ae=(De=c.processingIconColor)!=null?De:bt==null?void 0:bt.color)!=null?Ae:"",D=(Le=(le=c.processingBackgroundColor)!=null?le:bt==null?void 0:bt.backgroundColor)!=null?Le:"",F=(Ye=(Ne=c.processingBorderColor)!=null?Ne:bt==null?void 0:bt.borderColor)!=null?Ye:"";L(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=D,N.style.borderColor=F;let z=S||"currentColor";N.style.color=z,ot(b,z),N.setAttribute("aria-label","Processing voice input"),g==="none"&&(N.style.cursor="default")},se=()=>{var De,Ae,le,Le,Ne,Ye,xt,it,Ct,vt,Ge,Ve;if(!N)return;ko();let c=(De=n.voiceRecognition)!=null?De:{},g=q.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",S=(Ae=c.speakingIconName)!=null?Ae:b,D=(Ye=c.speakingIconColor)!=null?Ye:g==="barge-in"?(Le=(le=c.recordingIconColor)!=null?le:bt==null?void 0:bt.color)!=null?Le:"":(Ne=bt==null?void 0:bt.color)!=null?Ne:"",F=(Ct=c.speakingBackgroundColor)!=null?Ct:g==="barge-in"?(xt=c.recordingBackgroundColor)!=null?xt:"var(--persona-voice-recording-bg, #ef4444)":(it=bt==null?void 0:bt.backgroundColor)!=null?it:"",z=(Ve=c.speakingBorderColor)!=null?Ve:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(Ge=bt==null?void 0:bt.borderColor)!=null?Ge:"";L(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=F,N.style.borderColor=z;let J=D||"currentColor";N.style.color=J,ot(S,J);let $=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",$),g==="none"&&(N.style.cursor="default"),g==="barge-in"&&N.classList.add("persona-voice-recording")},te=()=>{var c,g,b;N&&(L(),bt&&(N.style.backgroundColor=(c=bt.backgroundColor)!=null?c:"",N.style.color=(g=bt.color)!=null?g:"",N.style.borderColor=(b=bt.borderColor)!=null?b:"",ot(bt.iconName,bt.color||"currentColor"),bt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},re=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=q.getVoiceStatus(),S=q.getVoiceInterruptionMode();if(S==="none"&&(b==="processing"||b==="speaking"))return;if(S==="cancel"&&(b==="processing"||b==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{kt.active=!1,kt.manuallyDeactivated=!0,en(),vn("user"),te()});return}q.toggleVoice().then(()=>{kt.active=q.isVoiceActive(),kt.manuallyDeactivated=!q.isVoiceActive(),en(),vn("user"),q.isVoiceActive()?j():te()});return}if(pn){let b=U.value.trim();kt.manuallyDeactivated=!0,en(),_n("user"),b&&(U.value="",U.style.height="auto",q.sendMessage(b))}else kt.manuallyDeactivated=!1,en(),qo("user")};bn=re,N&&(N.addEventListener("click",re),Lt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),te()):_n("system"),N&&N.removeEventListener("click",re)}));let dt=a.on("assistant:complete",()=>{Ya&&(kt.active||kt.manuallyDeactivated||Ya==="assistant"&&!kt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!kt.active&&!kt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{kt.active=q.isVoiceActive(),vn("auto"),q.isVoiceActive()&&j()}):qo("auto"))},600))});Lt.push(dt);let Ze=a.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Lt.push(Ze);let ft=()=>{Kt(!I,"user")},je=null,st=null;if(T&&!W()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>js(n,ft).element,onToggle:ft});g&&(st=g)}st||(je=js(n,ft))}je?e.appendChild(je.element):st&&e.appendChild(st),Mo(),Wn.render(n.suggestionChips,q,U,void 0,n.suggestionChipsConfig),ns(),ya(q.isStreaming()),vo(!0),oi(),k&&(!T||W()?setTimeout(()=>ba(),0):I&&setTimeout(()=>ba(),200));let Vt=()=>{var $,De,Ae,le,Le,Ne,Ye,xt,it,Ct,vt,Ge,Ve,nt,B,Ue,Ke,at,We,qt,wt,mr;if(W()){Hr(),Mo();return}let c=br(n),g=(De=($=n.launcher)==null?void 0:$.sidebarMode)!=null?De:!1,b=c||g||((le=(Ae=n.launcher)==null?void 0:Ae.fullHeight)!=null?le:!1),S=(Le=e.ownerDocument.defaultView)!=null?Le:window,D=(Ye=(Ne=n.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ye:!0,F=(it=(xt=n.launcher)==null?void 0:xt.mobileBreakpoint)!=null?it:640,z=S.innerWidth<=F,J=D&&z&&T;try{if(J){Rn(),Po(e,n);return}if(E&&(E=!1,Rn(),Po(e,n)),!T&&!c){V.style.height="",V.style.width="";return}if(!g&&!c){let Pr=(vt=(Ct=n==null?void 0:n.launcher)==null?void 0:Ct.width)!=null?vt:n==null?void 0:n.launcherWidth,Gt=Pr!=null?Pr:xn;V.style.width=Gt,V.style.maxWidth=Gt}if(Un(),!b){let Pr=S.innerHeight,Gt=64,qr=(Ve=(Ge=n.launcher)==null?void 0:Ge.heightOffset)!=null?Ve:0,Ir=Math.max(200,Pr-Gt),ut=Math.min(640,Ir),At=Math.max(200,ut-qr);V.style.height=`${At}px`}}finally{if(Hr(),Mo(),I&&T){let Gt=((nt=e.ownerDocument.defaultView)!=null?nt:window).innerWidth<=((Ue=(B=n.launcher)==null?void 0:B.mobileBreakpoint)!=null?Ue:640),qr=(at=(Ke=n.launcher)==null?void 0:Ke.sidebarMode)!=null?at:!1,Ir=(qt=(We=n.launcher)==null?void 0:We.mobileFullscreen)!=null?qt:!0,ut=br(n)&&Ir&&Gt,At=qr||Ir&&Gt&&T||ut;if(At&&!ur){let jr=e.getRootNode(),Dr=jr instanceof ShadowRoot?jr.host:e.closest(".persona-host");Dr&&!pr&&(pr=zp(Dr,(mr=(wt=n.launcher)==null?void 0:wt.zIndex)!=null?mr:Nr)),ur=qp(e.ownerDocument)}else At||(pr==null||pr(),pr=null,ur==null||ur(),ur=null)}}};Vt();let Cr=(Tf=e.ownerDocument.defaultView)!=null?Tf:window;if(Cr.addEventListener("resize",Vt),Lt.push(()=>Cr.removeEventListener("resize",Vt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Hr()});c.observe(Xe),Lt.push(()=>c.disconnect())}Dn=Ee.scrollTop;let $t=Ee.scrollHeight,zt=()=>{let c=Ee.scrollTop,g=Ee.scrollHeight,b=g<$t;$t=g;let{action:S,nextLastScrollTop:D}=Al({following:Bn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:_s(Ee,Xa),userScrollThreshold:ri,isAutoScrolling:eo||$o||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=D,S==="resume"){Co();return}S==="pause"&&Za()};Ee.addEventListener("scroll",zt,{passive:!0}),Lt.push(()=>Ee.removeEventListener("scroll",zt));let vr=c=>{let g=Sl({following:Bn.isFollowing(),deltaY:c.deltaY,nearBottom:_s(Ee,Xa),resumeWhenNearBottom:!0});g==="pause"?Za():g==="resume"&&Co()};Ee.addEventListener("wheel",vr,{passive:!0}),Lt.push(()=>Ee.removeEventListener("wheel",vr)),ht.addEventListener("click",()=>{Ee.scrollTop=Ee.scrollHeight,Dn=Ee.scrollTop,Co(),vo(!0)}),Lt.push(()=>ht.remove()),Lt.push(()=>{Qa()});let Br=()=>{Z&&(dn&&(Z.removeEventListener("click",dn),dn=null),R()?(Z.style.display="",dn=()=>{Kt(!1,"user")},Z.addEventListener("click",dn)):Z.style.display="none")};Br(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{q.clearMessages(),cn.clear(),Co(),Oo(Be.composerOverlay);try{localStorage.removeItem(Ga),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},M.syncFromMetadata(),K==null||K.clear(),ge==null||ge.update()})})(),he&&he.addEventListener("submit",as),U==null||U.addEventListener("keydown",is),U==null||U.addEventListener("input",ss),U==null||U.addEventListener("paste",ds);let fr=(Mf=e.ownerDocument)!=null?Mf:document;fr.addEventListener("keydown",ls,!0);let An="persona-attachment-drop-active",ps=0,id=()=>{ps=0,oe.classList.remove(An)},va=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&Rt!==null},Ru=c=>{!Yl(c.dataTransfer)||!va()||(ps++,ps===1&&oe.classList.add(An))},Wu=c=>{!Yl(c.dataTransfer)||!va()||(ps--,ps<=0&&id())},Hu=c=>{!Yl(c.dataTransfer)||!va()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Bu=c=>{var b;if(!Yl(c.dataTransfer)||!va())return;c.preventDefault(),c.stopPropagation(),id();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&Rt.handleFiles(g)},Eo=!0;oe.addEventListener("dragenter",Ru,Eo),oe.addEventListener("dragleave",Wu,Eo),e.addEventListener("dragover",Hu,Eo),e.addEventListener("drop",Bu,Eo);let yi=e.ownerDocument,Du=c=>{va()&&c.preventDefault()},Ou=c=>{va()&&c.preventDefault()};yi.addEventListener("dragover",Du),yi.addEventListener("drop",Ou),Lt.push(()=>{he&&he.removeEventListener("submit",as),U==null||U.removeEventListener("keydown",is),U==null||U.removeEventListener("input",ss),U==null||U.removeEventListener("paste",ds),fr.removeEventListener("keydown",ls,!0)}),Lt.push(()=>{oe.removeEventListener("dragenter",Ru,Eo),oe.removeEventListener("dragleave",Wu,Eo),e.removeEventListener("dragover",Hu,Eo),e.removeEventListener("drop",Bu,Eo),yi.removeEventListener("dragover",Du),yi.removeEventListener("drop",Ou),id()}),Lt.push(()=>{q.cancel()}),je?Lt.push(()=>{je==null||je.destroy()}):st&&Lt.push(()=>{st==null||st.remove()});let xr={update(c){var yr,jn,so,bi,wi,Ci,Jo,vi,us,Wf,Hf,Bf,Df,Of,_f,Nf,$f,Ff,Uf,zf,qf,jf,Vf,Gf,Kf,Jf,Xf,Yf,Qf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,wm,Cm,vm,Am,Sm,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,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,wg,Cg,vg,Ag,Sg,Tg,Mg,kg,Eg;let g=n.toolCall,b=n.messageActions,S=(yr=n.layout)==null?void 0:yr.messages,D=n.colorScheme,F=n.loadingIndicator,z=n.iterationDisplay,J=(jn=n.features)==null?void 0:jn.showReasoning,$=(so=n.features)==null?void 0:so.showToolCalls,De=(bi=n.features)==null?void 0:bi.toolCallDisplay,Ae=(wi=n.features)==null?void 0:wi.reasoningDisplay;n={...n,...c},Rn(),Po(e,n),Ul(e,n),zl(e,n),sn(),n.colorScheme!==D&&wo();let le=Ys.getForInstance(n.plugins);o.length=0,o.push(...le),T=(Jo=(Ci=n.launcher)==null?void 0:Ci.enabled)!=null?Jo:!0,A=(us=(vi=n.launcher)==null?void 0:vi.autoExpand)!=null?us:!1,Oe=(Hf=(Wf=n.features)==null?void 0:Wf.showReasoning)!=null?Hf:!0,et=(Df=(Bf=n.features)==null?void 0:Bf.showToolCalls)!=null?Df:!0,xe=(_f=(Of=n.features)==null?void 0:Of.scrollToBottom)!=null?_f:{},Ln(),ro();let Le=be;if(be=($f=(Nf=n.features)==null?void 0:Nf.showEventStreamToggle)!=null?$f:!1,be&&!Le){if(K||(X=new Xs(Je),K=new Js(Te,X),X.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),q.setSSEEventCallback((ne,_t)=>{var Zt;(Zt=n.onSSEEvent)==null||Zt.call(n,ne,_t),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(_t)})})),!Tt&&$e){let ne=(Uf=(Ff=n.features)==null?void 0:Ff.eventStream)==null?void 0:Uf.classNames,_t="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:"");Tt=y("button",_t),Tt.style.width="28px",Tt.style.height="28px",Tt.style.color=Qr.actionIconColor,Tt.type="button",Tt.setAttribute("aria-label","Event Stream"),Tt.title="Event Stream";let Zt=Pe("activity","18px","currentColor",1.5);Zt&&Tt.appendChild(Zt);let St=Be.clearChatButtonWrapper,Ft=Be.closeButtonWrapper,Ar=St||Ft;Ar&&Ar.parentNode===$e?$e.insertBefore(Tt,Ar):$e.appendChild(Tt),Tt.addEventListener("click",()=>{ce?Zr():Mr()})}}else!be&&Le&&(Zr(),Tt&&(Tt.remove(),Tt=null),K==null||K.clear(),X==null||X.destroy(),K=null,X=null);if(((zf=n.launcher)==null?void 0:zf.enabled)===!1&&je&&(je.destroy(),je=null),((qf=n.launcher)==null?void 0:qf.enabled)===!1&&st&&(st.remove(),st=null),((jf=n.launcher)==null?void 0:jf.enabled)!==!1&&!je&&!st){let ne=o.find(_t=>_t.renderLauncher);if(ne!=null&&ne.renderLauncher){let _t=ne.renderLauncher({config:n,defaultRenderer:()=>js(n,ft).element,onToggle:ft});_t&&(st=_t,e.appendChild(st))}st||(je=js(n,ft),e.appendChild(je.element))}je&&je.update(n),me&&((Vf=n.launcher)==null?void 0:Vf.title)!==void 0&&(me.textContent=n.launcher.title),qe&&((Gf=n.launcher)==null?void 0:Gf.subtitle)!==void 0&&(qe.textContent=n.launcher.subtitle);let Ne=(Kf=n.layout)==null?void 0:Kf.header;if((Ne==null?void 0:Ne.layout)!==h&&$e){let ne=Ne?Oa(n,Ne,{showClose:R(),onClose:()=>Kt(!1,"user")}):fo({config:n,showClose:R(),onClose:()=>Kt(!1,"user")});$e.replaceWith(ne.header),$e=ne.header,O=ne.iconHolder,me=ne.headerTitle,qe=ne.headerSubtitle,Z=ne.closeButton,h=Ne==null?void 0:Ne.layout}else if(Ne&&(O&&(O.style.display=Ne.showIcon===!1?"none":""),me&&(me.style.display=Ne.showTitle===!1?"none":""),qe&&(qe.style.display=Ne.showSubtitle===!1?"none":""),Z&&(Z.style.display=Ne.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let ne=Ne.showClearChat;if(ne!==void 0){Be.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:_t}=Be;_t&&!_t.classList.contains("persona-absolute")&&(ne?_t.classList.remove("persona-ml-auto"):_t.classList.add("persona-ml-auto"))}}let xt=((Jf=n.layout)==null?void 0:Jf.showHeader)!==!1;$e&&($e.style.display=xt?"":"none");let it=((Xf=n.layout)==null?void 0:Xf.showFooter)!==!1;Xe&&(Xe.style.display=it?"":"none"),Hr(),ro(),T!==w?T?Kt(A,"auto"):(I=!0,Mo()):A!==v&&Kt(A,"auto"),v=A,w=T,Vt(),Br();let Ge=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ve=JSON.stringify(n.messageActions)!==JSON.stringify(b),nt=JSON.stringify((Yf=n.layout)==null?void 0:Yf.messages)!==JSON.stringify(S),B=((Qf=n.loadingIndicator)==null?void 0:Qf.render)!==(F==null?void 0:F.render)||((Zf=n.loadingIndicator)==null?void 0:Zf.renderIdle)!==(F==null?void 0:F.renderIdle)||((em=n.loadingIndicator)==null?void 0:em.showBubble)!==(F==null?void 0:F.showBubble),Ue=n.iterationDisplay!==z,Ke=((rm=(tm=n.features)==null?void 0:tm.showReasoning)!=null?rm:!0)!==(J!=null?J:!0)||((om=(nm=n.features)==null?void 0:nm.showToolCalls)!=null?om:!0)!==($!=null?$:!0)||JSON.stringify((am=n.features)==null?void 0:am.toolCallDisplay)!==JSON.stringify(De)||JSON.stringify((sm=n.features)==null?void 0:sm.reasoningDisplay)!==JSON.stringify(Ae);(Ge||Ve||nt||B||Ue||Ke)&&q&&(Ja++,Uo(we,q.getMessages(),ye));let We=(im=n.launcher)!=null?im:{},qt=(lm=We.headerIconHidden)!=null?lm:!1,wt=(cm=(dm=n.layout)==null?void 0:dm.header)==null?void 0:cm.showIcon,mr=qt||wt===!1,Pr=We.headerIconName,Gt=(pm=We.headerIconSize)!=null?pm:"48px";if(O){let ne=oe.querySelector(".persona-border-b-persona-divider"),_t=ne==null?void 0:ne.querySelector(".persona-flex-col");if(mr)O.style.display="none",ne&&_t&&!ne.contains(_t)&&ne.insertBefore(_t,ne.firstChild);else{if(O.style.display="",O.style.height=Gt,O.style.width=Gt,ne&&_t&&(ne.contains(O)?O.nextSibling!==_t&&(O.remove(),ne.insertBefore(O,_t)):ne.insertBefore(O,_t)),Pr){let St=parseFloat(Gt)||24,Ft=Pe(Pr,St*.6,"#ffffff",2);Ft?O.replaceChildren(Ft):O.textContent=(um=We.agentIconText)!=null?um:"\u{1F4AC}"}else if(We.iconUrl){let St=O.querySelector("img");if(St)St.src=We.iconUrl,St.style.height=Gt,St.style.width=Gt;else{let Ft=document.createElement("img");Ft.src=We.iconUrl,Ft.alt="",Ft.className="persona-rounded-xl persona-object-cover",Ft.style.height=Gt,Ft.style.width=Gt,O.replaceChildren(Ft)}}else{let St=O.querySelector("svg"),Ft=O.querySelector("img");(St||Ft)&&O.replaceChildren(),O.textContent=(fm=We.agentIconText)!=null?fm:"\u{1F4AC}"}let Zt=O.querySelector("img");Zt&&(Zt.style.height=Gt,Zt.style.width=Gt)}}let qr=(gm=(mm=n.layout)==null?void 0:mm.header)==null?void 0:gm.showTitle,Ir=(xm=(hm=n.layout)==null?void 0:hm.header)==null?void 0:xm.showSubtitle;if(me&&(me.style.display=qr===!1?"none":""),qe&&(qe.style.display=Ir===!1?"none":""),Z){((bm=(ym=n.layout)==null?void 0:ym.header)==null?void 0:bm.showCloseButton)===!1?Z.style.display="none":Z.style.display="";let _t=(wm=We.closeButtonSize)!=null?wm:"32px",Zt=(Cm=We.closeButtonPlacement)!=null?Cm:"inline";Z.style.height=_t,Z.style.width=_t;let{closeButtonWrapper:St}=Be,Ft=Zt==="top-right",Ar=St==null?void 0:St.classList.contains("persona-absolute");if(St&&Ft!==Ar)if(St.remove(),Ft)St.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",oe.style.position="relative",oe.appendChild(St);else{let Mt=(Am=(vm=We.clearChat)==null?void 0:vm.placement)!=null?Am:"inline",Sr=(Tm=(Sm=We.clearChat)==null?void 0:Sm.enabled)!=null?Tm:!0;St.className=Sr&&Mt==="inline"?"":"persona-ml-auto";let on=oe.querySelector(".persona-border-b-persona-divider");on&&on.appendChild(St)}if(Z.style.color=We.closeButtonColor||Qr.actionIconColor,We.closeButtonBackgroundColor?(Z.style.backgroundColor=We.closeButtonBackgroundColor,Z.classList.remove("hover:persona-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let Mt=We.closeButtonBorderWidth||"0px",Sr=We.closeButtonBorderColor||"transparent";Z.style.border=`${Mt} solid ${Sr}`,Z.classList.remove("persona-border-none")}else Z.style.border="",Z.classList.add("persona-border-none");We.closeButtonBorderRadius?(Z.style.borderRadius=We.closeButtonBorderRadius,Z.classList.remove("persona-rounded-full")):(Z.style.borderRadius="",Z.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(Z.style.paddingLeft=We.closeButtonPaddingX,Z.style.paddingRight=We.closeButtonPaddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),We.closeButtonPaddingY?(Z.style.paddingTop=We.closeButtonPaddingY,Z.style.paddingBottom=We.closeButtonPaddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let Or=(Mm=We.closeButtonIconName)!=null?Mm:"x",Nn=(km=We.closeButtonIconText)!=null?km:"\xD7";Z.innerHTML="";let Gr=Pe(Or,"28px","currentColor",1);Gr?Z.appendChild(Gr):Z.textContent=Nn;let gr=(Em=We.closeButtonTooltipText)!=null?Em:"Close chat",fn=(Lm=We.closeButtonShowTooltip)!=null?Lm:!0;if(Z.setAttribute("aria-label",gr),St&&(St._cleanupTooltip&&(St._cleanupTooltip(),delete St._cleanupTooltip),fn&&gr)){let Mt=null,Sr=()=>{if(Mt||!Z)return;let Xo=Z.ownerDocument,fs=Xo.body;if(!fs)return;Mt=Xn(Xo,"div","persona-clear-chat-tooltip"),Mt.textContent=gr;let ms=Xn(Xo,"div");ms.className="persona-clear-chat-tooltip-arrow",Mt.appendChild(ms);let Yo=Z.getBoundingClientRect();Mt.style.position="fixed",Mt.style.zIndex=String(Io),Mt.style.left=`${Yo.left+Yo.width/2}px`,Mt.style.top=`${Yo.top-8}px`,Mt.style.transform="translate(-50%, -100%)",fs.appendChild(Mt)},on=()=>{Mt&&Mt.parentNode&&(Mt.parentNode.removeChild(Mt),Mt=null)};St.addEventListener("mouseenter",Sr),St.addEventListener("mouseleave",on),Z.addEventListener("focus",Sr),Z.addEventListener("blur",on),St._cleanupTooltip=()=>{on(),St&&(St.removeEventListener("mouseenter",Sr),St.removeEventListener("mouseleave",on)),Z&&(Z.removeEventListener("focus",Sr),Z.removeEventListener("blur",on))}}}let{clearChatButton:ut,clearChatButtonWrapper:At}=Be;if(ut){let ne=(Pm=We.clearChat)!=null?Pm:{},_t=(Im=ne.enabled)!=null?Im:!0,Zt=(Wm=(Rm=n.layout)==null?void 0:Rm.header)==null?void 0:Wm.showClearChat,St=Zt!==void 0?Zt:_t,Ft=(Hm=ne.placement)!=null?Hm:"inline";if(At){At.style.display=St?"":"none";let{closeButtonWrapper:Ar}=Be;!W()&&Ar&&!Ar.classList.contains("persona-absolute")&&(St?Ar.classList.remove("persona-ml-auto"):Ar.classList.add("persona-ml-auto"));let Or=Ft==="top-right",Nn=At.classList.contains("persona-absolute");if(!W()&&Or!==Nn&&St){if(At.remove(),Or)At.className="persona-absolute persona-top-4 persona-z-50",At.style.right="48px",oe.style.position="relative",oe.appendChild(At);else{At.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",At.style.right="";let gr=oe.querySelector(".persona-border-b-persona-divider"),fn=Be.closeButtonWrapper;gr&&fn&&fn.parentElement===gr?gr.insertBefore(At,fn):gr&&gr.appendChild(At)}let Gr=Be.closeButtonWrapper;Gr&&!Gr.classList.contains("persona-absolute")&&(Or?Gr.classList.add("persona-ml-auto"):Gr.classList.remove("persona-ml-auto"))}}if(St){if(!W()){let Mt=(Bm=ne.size)!=null?Bm:"32px";ut.style.height=Mt,ut.style.width=Mt}let Ar=(Dm=ne.iconName)!=null?Dm:"refresh-cw",Or=(Om=ne.iconColor)!=null?Om:"";ut.style.color=Or||Qr.actionIconColor,ut.innerHTML="";let Nn=W()?"14px":"20px",Gr=Pe(Ar,Nn,"currentColor",2);if(Gr&&ut.appendChild(Gr),ne.backgroundColor?(ut.style.backgroundColor=ne.backgroundColor,ut.classList.remove("hover:persona-bg-gray-100")):(ut.style.backgroundColor="",ut.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let Mt=ne.borderWidth||"0px",Sr=ne.borderColor||"transparent";ut.style.border=`${Mt} solid ${Sr}`,ut.classList.remove("persona-border-none")}else ut.style.border="",ut.classList.add("persona-border-none");ne.borderRadius?(ut.style.borderRadius=ne.borderRadius,ut.classList.remove("persona-rounded-full")):(ut.style.borderRadius="",ut.classList.add("persona-rounded-full")),ne.paddingX?(ut.style.paddingLeft=ne.paddingX,ut.style.paddingRight=ne.paddingX):(ut.style.paddingLeft="",ut.style.paddingRight=""),ne.paddingY?(ut.style.paddingTop=ne.paddingY,ut.style.paddingBottom=ne.paddingY):(ut.style.paddingTop="",ut.style.paddingBottom="");let gr=(_m=ne.tooltipText)!=null?_m:"Clear chat",fn=(Nm=ne.showTooltip)!=null?Nm:!0;if(ut.setAttribute("aria-label",gr),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),fn&&gr)){let Mt=null,Sr=()=>{if(Mt||!ut)return;let Xo=ut.ownerDocument,fs=Xo.body;if(!fs)return;Mt=Xn(Xo,"div","persona-clear-chat-tooltip"),Mt.textContent=gr;let ms=Xn(Xo,"div");ms.className="persona-clear-chat-tooltip-arrow",Mt.appendChild(ms);let Yo=ut.getBoundingClientRect();Mt.style.position="fixed",Mt.style.zIndex=String(Io),Mt.style.left=`${Yo.left+Yo.width/2}px`,Mt.style.top=`${Yo.top-8}px`,Mt.style.transform="translate(-50%, -100%)",fs.appendChild(Mt)},on=()=>{Mt&&Mt.parentNode&&(Mt.parentNode.removeChild(Mt),Mt=null)};At.addEventListener("mouseenter",Sr),At.addEventListener("mouseleave",on),ut.addEventListener("focus",Sr),ut.addEventListener("blur",on),At._cleanupTooltip=()=>{on(),At&&(At.removeEventListener("mouseenter",Sr),At.removeEventListener("mouseleave",on)),ut&&(ut.removeEventListener("focus",Sr),ut.removeEventListener("blur",on))}}}}let jr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Qs],Dr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ma.message,ma.messageAndClick];M=Zs({parsers:jr,handlers:Dr,getSessionMetadata:m,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),ye=Yx(n,M,ie),q.updateConfig(n),Uo(we,q.getMessages(),ye),Wn.render(n.suggestionChips,q,U,void 0,n.suggestionChipsConfig),ns(),ya(q.isStreaming());let jo=(($m=n.voiceRecognition)==null?void 0:$m.enabled)===!0,Vo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Go=((Um=(Fm=n.voiceRecognition)==null?void 0:Fm.provider)==null?void 0:Um.type)==="runtype";if(jo&&(Vo||Go))if(!N||!Me){let ne=xi(n.voiceRecognition,n.sendButton);ne&&(N=ne.micButton,Me=ne.micButtonWrapper,yt.insertBefore(Me,ze),N.addEventListener("click",re),N.disabled=q.isStreaming())}else{let ne=(zm=n.voiceRecognition)!=null?zm:{},_t=(qm=n.sendButton)!=null?qm:{},Zt=(jm=ne.iconName)!=null?jm:"mic",St=(Vm=_t.size)!=null?Vm:"40px",Ft=(Gm=ne.iconSize)!=null?Gm:St,Ar=parseFloat(Ft)||24;N.style.width=Ft,N.style.height=Ft,N.style.minWidth=Ft,N.style.minHeight=Ft;let Or=(Jm=(Km=ne.iconColor)!=null?Km:_t.textColor)!=null?Jm:"currentColor";N.innerHTML="";let Nn=Pe(Zt,Ar,Or,2);Nn?N.appendChild(Nn):N.textContent="\u{1F3A4}";let Gr=(Xm=ne.backgroundColor)!=null?Xm:_t.backgroundColor;Gr?N.style.backgroundColor=Gr:N.style.backgroundColor="",Or?N.style.color=Or:N.style.color="var(--persona-text, #111827)",ne.borderWidth?(N.style.borderWidth=ne.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),ne.borderColor?N.style.borderColor=ne.borderColor:N.style.borderColor="",ne.paddingX?(N.style.paddingLeft=ne.paddingX,N.style.paddingRight=ne.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),ne.paddingY?(N.style.paddingTop=ne.paddingY,N.style.paddingBottom=ne.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let gr=Me==null?void 0:Me.querySelector(".persona-send-button-tooltip"),fn=(Ym=ne.tooltipText)!=null?Ym:"Start voice recognition";if(((Qm=ne.showTooltip)!=null?Qm:!1)&&fn)if(gr)gr.textContent=fn,gr.style.display="";else{let Sr=document.createElement("div");Sr.className="persona-send-button-tooltip",Sr.textContent=fn,Me==null||Me.insertBefore(Sr,N)}else gr&&(gr.style.display="none");Me.style.display="",N.disabled=q.isStreaming()}else N&&Me&&(Me.style.display="none",((eg=(Zm=n.voiceRecognition)==null?void 0:Zm.provider)==null?void 0:eg.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():pn&&_n());if(((tg=n.attachments)==null?void 0:tg.enabled)===!0)if(!gt||!ke){let ne=(rg=n.attachments)!=null?rg:{},Zt=(og=((ng=n.sendButton)!=null?ng:{}).size)!=null?og:"40px";Ut||(Ut=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",he.insertBefore(Ut,U)),tt||(tt=document.createElement("input"),tt.type="file",tt.accept=((ag=ne.allowedTypes)!=null?ag:uo).join(","),tt.multiple=((sg=ne.maxFiles)!=null?sg:4)>1,tt.style.display="none",tt.setAttribute("aria-label","Attach files"),he.insertBefore(tt,U)),gt=y("div","persona-send-button-wrapper"),ke=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ke.type="button",ke.setAttribute("aria-label",(ig=ne.buttonTooltipText)!=null?ig:"Attach file");let St=(lg=ne.buttonIconName)!=null?lg:"paperclip",Ft=Zt,Ar=parseFloat(Ft)||40,Or=Math.round(Ar*.6);ke.style.width=Ft,ke.style.height=Ft,ke.style.minWidth=Ft,ke.style.minHeight=Ft,ke.style.fontSize="18px",ke.style.lineHeight="1",ke.style.backgroundColor="transparent",ke.style.color="var(--persona-primary, #111827)",ke.style.border="none",ke.style.borderRadius="6px",ke.style.transition="background-color 0.15s ease",ke.addEventListener("mouseenter",()=>{ke.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ke.addEventListener("mouseleave",()=>{ke.style.backgroundColor="transparent"});let Nn=Pe(St,Or,"currentColor",1.5);Nn?ke.appendChild(Nn):ke.textContent="\u{1F4CE}",ke.addEventListener("click",fn=>{fn.preventDefault(),tt==null||tt.click()}),gt.appendChild(ke);let Gr=(dg=ne.buttonTooltipText)!=null?dg:"Attach file",gr=y("div","persona-send-button-tooltip");gr.textContent=Gr,gt.appendChild(gr),ct.append(gt),!Rt&&tt&&Ut&&(Rt=da.fromConfig(ne),Rt.setPreviewsContainer(Ut),tt.addEventListener("change",async()=>{Rt&&(tt!=null&&tt.files)&&(await Rt.handleFileSelect(tt.files),tt.value="")})),oe.querySelector(".persona-attachment-drop-overlay")||oe.appendChild(Qx(ne.dropOverlay))}else{gt.style.display="";let ne=(cg=n.attachments)!=null?cg:{};tt&&(tt.accept=((pg=ne.allowedTypes)!=null?pg:uo).join(","),tt.multiple=((ug=ne.maxFiles)!=null?ug:4)>1),Rt&&Rt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else gt&&(gt.style.display="none"),Rt&&Rt.clearAttachments(),(fg=oe.querySelector(".persona-attachment-drop-overlay"))==null||fg.remove();let sr=(mg=n.sendButton)!=null?mg:{},Ko=(gg=sr.useIcon)!=null?gg:!1,Lo=(hg=sr.iconText)!=null?hg:"\u2191",Ht=sr.iconName,tn=(xg=sr.tooltipText)!=null?xg:"Send message",ao=(yg=sr.showTooltip)!=null?yg:!1,Vr=(bg=sr.size)!=null?bg:"40px",rn=sr.backgroundColor,Xt=sr.textColor;if(Ko){if(ae.style.width=Vr,ae.style.height=Vr,ae.style.minWidth=Vr,ae.style.minHeight=Vr,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Xt?ae.style.color=Xt:ae.style.color="var(--persona-button-primary-fg, #ffffff)",Ht){let ne=parseFloat(Vr)||24,_t=(Xt==null?void 0:Xt.trim())||"currentColor",Zt=Pe(Ht,ne,_t,2);Zt?ae.appendChild(Zt):ae.textContent=Lo}else ae.textContent=Lo;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rn?(ae.style.backgroundColor=rn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(Cg=(wg=n.copy)==null?void 0:wg.sendButtonLabel)!=null?Cg:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.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",rn?(ae.style.backgroundColor=rn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Xt?ae.style.color=Xt:ae.classList.add("persona-text-white");sr.borderWidth?(ae.style.borderWidth=sr.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),sr.borderColor?ae.style.borderColor=sr.borderColor:ae.style.borderColor="",sr.paddingX?(ae.style.paddingLeft=sr.paddingX,ae.style.paddingRight=sr.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),sr.paddingY?(ae.style.paddingTop=sr.paddingY,ae.style.paddingBottom=sr.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let nr=ze==null?void 0:ze.querySelector(".persona-send-button-tooltip");if(ao&&tn)if(nr)nr.textContent=tn,nr.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=tn,ze==null||ze.insertBefore(ne,ae)}else nr&&(nr.style.display="none");let Yt=(Mg=(vg=n.layout)==null?void 0:vg.contentMaxWidth)!=null?Mg:W()?(Tg=(Sg=(Ag=n.launcher)==null?void 0:Ag.composerBar)==null?void 0:Sg.contentMaxWidth)!=null?Tg:"720px":void 0;Yt?(we.style.maxWidth=Yt,we.style.marginLeft="auto",we.style.marginRight="auto",we.style.width="100%",he&&(he.style.maxWidth=Yt,he.style.marginLeft="auto",he.style.marginRight="auto"),Dt&&(Dt.style.maxWidth=Yt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto")):(we.style.maxWidth="",we.style.marginLeft="",we.style.marginRight="",we.style.width="",he&&(he.style.maxWidth="",he.style.marginLeft="",he.style.marginRight=""),Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""));let ir=(kg=n.statusIndicator)!=null?kg:{},nn=(Eg=ir.visible)!=null?Eg:!0;if(Re.style.display=nn?"":"none",q){let ne=q.getStatus();_e(Re,(Zt=>{var St,Ft,Ar,Or;return Zt==="idle"?(St=ir.idleText)!=null?St:_r.idle:Zt==="connecting"?(Ft=ir.connectingText)!=null?Ft:_r.connecting:Zt==="connected"?(Ar=ir.connectedText)!=null?Ar:_r.connected:Zt==="error"?(Or=ir.errorText)!=null?Or:_r.error:_r[Zt]})(ne),ir,ne)}Re.classList.remove("persona-text-left","persona-text-center","persona-text-right");let un=ir.align==="left"?"persona-text-left":ir.align==="center"?"persona-text-center":"persona-text-right";Re.classList.add(un)},open(){R()&&Kt(!0,"api")},close(){R()&&Kt(!1,"api")},toggle(){R()&&Kt(!I,"api")},clearChat(){ee=!1,q.clearMessages(),cn.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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},M.syncFromMetadata(),K==null||K.clear(),ge==null||ge.update()},setMessage(c){return!U||q.isStreaming()?!1:(!I&&R()&&Kt(!0,"system"),U.value=c,U.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||U.value.trim();return g?(!I&&R()&&Kt(!0,"system"),U.value="",U.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return q.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(q.isVoiceActive()||(!I&&R()&&Kt(!0,"system"),kt.manuallyDeactivated=!1,en(),q.toggleVoice().then(()=>{kt.active=q.isVoiceActive(),vn("user"),q.isVoiceActive()&&j()})),!0):pn?!0:cs()?(!I&&R()&&Kt(!0,"system"),kt.manuallyDeactivated=!1,en(),qo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{kt.active=!1,kt.manuallyDeactivated=!0,en(),vn("user"),te()}),!0):!1:pn?(kt.manuallyDeactivated=!0,en(),_n("user"),!0):!1},injectMessage(c){return!I&&R()&&Kt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!I&&R()&&Kt(!0,"system");let g=q.injectAssistantMessage(c);return H&&(H=!1,G&&(clearTimeout(G),G=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!I&&R()&&Kt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!I&&R()&&Kt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!I&&R()&&Kt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!I&&R()&&Kt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!I&&R()&&Kt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){K&&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(){!be||!K||Mr()},hideEventStream(){ce&&Zr()},isEventStreamVisible(){return ce},showArtifacts(){En(n)&&(ee=!1,sn(),Et==null||Et.setMobileOpen(!0))},hideArtifacts(){En(n)&&(ee=!0,sn())},upsertArtifact(c){return En(n)?(ee=!1,q.upsertArtifact(c)):null},selectArtifact(c){En(n)&&q.selectArtifact(c)},clearArtifacts(){En(n)&&q.clearArtifacts()},getArtifacts(){var c;return(c=q==null?void 0:q.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=q==null?void 0:q.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!I&&!W()||!U?!1:(U.focus(),!0)},async resolveApproval(c,g){let S=q.getMessages().find(D=>{var F;return D.variant==="approval"&&((F=D.approval)==null?void 0:F.id)===c});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${c}`);if(S.approval.toolType==="webmcp"){q.resolveWebMcpApproval(S.id,g);return}return q.resolveApproval(S.approval,g)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return R()&&I},isVoiceActive(){return kt.active},getState(){return{open:R()&&I,launcherEnabled:T,voiceActive:kt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!I&&R()&&Kt(!0,"system");let g=we.querySelector(".persona-feedback-container");g&&g.remove();let b=Jl({onSubmit:async(S,D)=>{var F;q.isClientTokenMode()&&await q.submitCSATFeedback(S,D),(F=c==null?void 0:c.onSubmit)==null||F.call(c,S,D)},onDismiss:c==null?void 0:c.onDismiss,...c});we.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!I&&R()&&Kt(!0,"system");let g=we.querySelector(".persona-feedback-container");g&&g.remove();let b=Xl({onSubmit:async(S,D)=>{var F;q.isClientTokenMode()&&await q.submitNPSFeedback(S,D),(F=c==null?void 0:c.onSubmit)==null||F.call(c,S,D)},onDismiss:c==null?void 0:c.onDismiss,...c});we.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return q.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return q.submitNPSFeedback(c,g)},destroy(){qn!=null&&(clearInterval(qn),qn=null),Lt.forEach(c=>c()),Y.remove(),Ce==null||Ce.remove(),je==null||je.destroy(),st==null||st.remove(),dn&&Z.removeEventListener("click",dn)}};if((((kf=r==null?void 0:r.debugTools)!=null?kf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:xr,getMessages:xr.getMessages,getStatus:xr.getStatus,getMetadata:xr.getPersistentMetadata,updateMetadata:xr.updatePersistentMetadata,clearHistory:()=>xr.clearChat(),setVoiceActive:b=>b?xr.startVoiceRecognition():xr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Lt.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=J=>{let $=J.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&xr.focusInput()};if(window.addEventListener("persona:focusInput",g),Lt.push(()=>{window.removeEventListener("persona:focusInput",g)}),be){let J=De=>{let Ae=De.detail;(!(Ae!=null&&Ae.instanceId)||Ae.instanceId===c)&&xr.showEventStream()},$=De=>{let Ae=De.detail;(!(Ae!=null&&Ae.instanceId)||Ae.instanceId===c)&&xr.hideEventStream()};window.addEventListener("persona:showEventStream",J),window.addEventListener("persona:hideEventStream",$),Lt.push(()=>{window.removeEventListener("persona:showEventStream",J),window.removeEventListener("persona:hideEventStream",$)})}let b=J=>{let $=J.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&xr.showArtifacts()},S=J=>{let $=J.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&xr.hideArtifacts()},D=J=>{let $=J.detail;$!=null&&$.instanceId&&$.instanceId!==c||$!=null&&$.artifact&&xr.upsertArtifact($.artifact)},F=J=>{let $=J.detail;$!=null&&$.instanceId&&$.instanceId!==c||typeof($==null?void 0:$.id)=="string"&&xr.selectArtifact($.id)},z=J=>{let $=J.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&xr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",z),Lt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",z)})}let Sn=iv(n.persistState);if(Sn&&R()){let c=lv(Sn.storage),g=`${Sn.keyPrefix}widget-open`,b=`${Sn.keyPrefix}widget-voice`,S=`${Sn.keyPrefix}widget-voice-mode`;if(c){let D=((Ef=Sn.persist)==null?void 0:Ef.openState)&&c.getItem(g)==="true",F=((Lf=Sn.persist)==null?void 0:Lf.voiceState)&&c.getItem(b)==="true",z=((Pf=Sn.persist)==null?void 0:Pf.voiceState)&&c.getItem(S)==="true";if(D&&setTimeout(()=>{xr.open(),setTimeout(()=>{var J;if(F||z)xr.startVoiceRecognition();else if((J=Sn.persist)!=null&&J.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),(If=Sn.persist)!=null&&If.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(Rf=Sn.persist)!=null&&Rf.voiceState&&(a.on("voice:state",J=>{c.setItem(b,J.active?"true":"false")}),a.on("user:message",J=>{c.setItem(S,J.viaVoice?"true":"false")})),Sn.clearOnChatClear){let J=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(S)},$=()=>J();window.addEventListener("persona:clear-chat",$),Lt.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return p&&R()&&setTimeout(()=>{xr.open()},0),no(),xr};var dv=(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},Zx=(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"},xu=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=""},ey=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",xu(e)},mu=e=>{e.style.transition=""},gu=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=""},hu=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Zl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},cv=(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))},pv=(e,t,r,n,o,a)=>{let s=a?t:e;o==="left"?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)},ty=(e,t,r,n,o,a,s)=>{var x,C,M,T,A,k;let i=Mn(a),d=i.reveal==="push";cv(e,t,r,n,d),pv(e,t,r,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"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=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,u=(T=(M=a==null?void 0:a.launcher)==null?void 0:M.mobileBreakpoint)!=null?T:640,m=l!=null?l.innerWidth<=u:!1;if(p&&m&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),gu(t),mu(n),ey(n),hu(r),Zl(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((k=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?k:Nr),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"),ey(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",gu(t),mu(n),hu(r),Zl(o,n);let v=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",h=s?"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=v,n.style.transform=h,n.style.pointerEvents=s?"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",mu(n),xu(n),Zl(o,n);let v=dv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),h=i.animate?"transform 180ms ease":"none",E=i.side==="right"?s?`translateX(-${v}px)`:"translateX(0)":s?"translateX(0)":`translateX(-${v}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+v}px`,t.style.transition=h,t.style.transform=E,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=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",gu(t),xu(n),hu(r),Zl(o,n);let v=i.reveal==="emerge";v?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",h=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!s;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=v||E?"hidden":"visible",n.style.transition=h,v&&(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")}},uv=(e,t)=>{let r=e.ownerDocument.createElement("div");return Zx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){Zx(r,n)},destroy(){r.remove()}}},fv=(e,t)=>{var A,k,v,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 a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),d=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),u=(k=(A=t==null?void 0:t.launcher)==null?void 0:A.enabled)==null||k?(w=(v=t==null?void 0:t.launcher)==null?void 0:v.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(s,e),d.appendChild(e);let m=null,f=()=>{m==null||m.disconnect(),m=null},x=()=>{f(),Mn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(m=new ResizeObserver(()=>{ty(s,i,d,l,p,t,u)}),m.observe(s))},C=()=>{ty(s,i,d,l,p,t,u),x()},M=s.ownerDocument.defaultView,T=()=>{C()};return M==null||M.addEventListener("resize",T),Mn(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),C(),{mode:"docked",host:p,shell:s,syncWidgetState(h){let E=h.launcherEnabled?h.open:!0;u!==E&&(u=E,C())},updateConfig(h){var E,W;t=h,((W=(E=t==null?void 0:t.launcher)==null?void 0:E.enabled)!=null?W:!0)===!1&&(u=!0),C()},destroy(){M==null||M.removeEventListener("resize",T),f(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}},ei=(e,t)=>br(t)?fv(e,t):uv(e,t);var yu={},mv=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},gv=()=>{try{if(typeof yu!="undefined"&&yu.url)return new URL("../widget.css",yu.url).href}catch{}return null},ry=(e,t)=>{let r=gv(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let a=o.cloneNode(!0);e.insertBefore(a,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 a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},ny=e=>{var M;let t=mv(e.target),r=e.useShadowDom===!0,n=t.ownerDocument,o=e.config,a=ei(t,o),s,i=[],d=(T,A)=>{var h,E;let v=!((E=(h=A==null?void 0:A.launcher)==null?void 0:h.enabled)!=null?E:!0)||br(A),w=n.createElement("div");if(w.setAttribute("data-persona-root","true"),v&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0"),r){let W=T.attachShadow({mode:"open"});W.appendChild(w),ry(W,n)}else T.appendChild(w),ry(T,n);return t.id&&w.setAttribute("data-persona-instance",t.id),w},l=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},u=()=>{let T=d(a.host,o);s=Ql(T,o,{debugTools:e.debugTools}),p()},m=()=>{i.forEach(T=>T()),i=[],s.destroy()};u(),(M=e.onReady)==null||M.call(e);let f=T=>{m(),a.destroy(),a=ei(t,T),o=T,u()},x={update(T){var E,W,R,I,H,G;let A={...o,...T,launcher:{...(E=o==null?void 0:o.launcher)!=null?E:{},...(W=T==null?void 0:T.launcher)!=null?W:{},dock:{...(I=(R=o==null?void 0:o.launcher)==null?void 0:R.dock)!=null?I:{},...(G=(H=T==null?void 0:T.launcher)==null?void 0:H.dock)!=null?G:{}}}},k=br(o),v=br(A),w=Wo(o),h=Wo(A);if(k!==v||w!==h){f(A);return}o=A,a.updateConfig(o),s.update(T),l()},destroy(){m(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(T,A,k){if(A==="host")return a.host;if(A in T)return Reflect.get(T,A,k);let v=s[A];return typeof v=="function"?v.bind(s):v}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var ly=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),hv=new Set(["button","a","input","select","textarea","details","summary"]),xv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),bu=/\b(product|card|item|listing|result)\b/i,Cu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yv=3e3,bv=100;function dy(e){let t=typeof e.className=="string"?e.className:"";if(bu.test(t)||e.id&&bu.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];if(n.name.startsWith("data-")&&bu.test(n.value))return!0}return!1}function cy(e){var t;return Cu.test(((t=e.textContent)!=null?t:"").trim())}function py(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 wv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function oy(e){let t=e.match(Cu);return t?t[0]:null}function ay(e){var n,o,a;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 s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function Cv(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",Av="result-card";function sy(e){return!dy(e)||!cy(e)||!py(e)&&!wv(e)?0:5200}function iy(e){var n;return!dy(e)||cy(e)||!py(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 vu=[{id:vv,scoreElement(e){return sy(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||Cu.test(n)&&n.length<32)}return!0},formatSummary(e,t){var d,l,p;if(sy(e)===0)return null;let{title:r,href:n}=ay(e),o=(p=(l=oy(((d=e.textContent)!=null?d:"").trim()))!=null?l:oy(t.text))!=null?p:"",a=Cv(e);return[n&&r?`[${r}](${n})${o?` \u2014 ${o}`:""}`:r?`${r}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
158
|
-
`)}},{id:
|
|
159
|
-
`)}}];function
|
|
160
|
-
${
|
|
157
|
+
`}if(!A&&!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(()=>xx(e)))}let Wn=$x(ne),cn=null,R,pn=!1,Hn=px(),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,An=c=>{s.emit("voice:state",{active:Pt.active,source:c,timestamp:Date.now()})},tn=()=>{f(c=>({...c,voiceState:{active:Pt.active,timestamp:Date.now(),manuallyDeactivated:Pt.manuallyDeactivated}}))},li=()=>{var A,_;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=yu(d.voiceState),g=!!c.active,w=Number((_=c.timestamp)!=null?_:0);Pt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-w<Tv&&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(),An("restore"),R.isVoiceActive()&&O()}):jo("restore"))},1e3)},di=()=>R?sy(R.getMessages()).filter(c=>!c.__skipPersist):[];function bs(c){if(!(i!=null&&i.save))return;let w={messages:c?sy(c):R?di():[],metadata:d,artifacts:oe.artifacts,selectedArtifactId:oe.selectedId};try{let A=i.save(w);A instanceof Promise&&A.catch(_=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",_)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}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())},Ao=()=>{Bn.resume(),oo()},So=(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 w=c.scrollTop,A=$a(c),_=A-w;if(Math.abs(_)<1){Dn=c.scrollTop;return}if(Math.abs(_)>=ii){Uo(),ro=!0,c.scrollTop=A,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!==A&&(A=De,_=A-w);let Se=$-F,ce=Math.min(Se/g,1),Le=U(ce),Ne=w+_*Le;c.scrollTop=Ne,Dn=c.scrollTop,ce<1?no=requestAnimationFrame(V):(c.scrollTop=A,Dn=c.scrollTop,no=null,ro=!1)};no=requestAnimationFrame(V)},ui=c=>{let g=new Map;c.forEach(w=>{let A=ys.get(w.id);g.set(w.id,{streaming:w.streaming,role:w.role}),!A&&w.role==="assistant"&&s.emit("assistant:message",w),w.role==="assistant"&&(A!=null&&A.streaming)&&w.streaming===!1&&s.emit("assistant:complete",w),w.variant==="approval"&&w.approval&&(A?w.approval.status!=="pending"&&s.emit("approval:resolved",{approval:w.approval,decision:w.approval.status}):s.emit("approval:requested",{approval:w.approval,message:w}))}),ys.clear(),g.forEach((w,A)=>{ys.set(A,w)})},zo=(c,g,w)=>{var dt,Ct,vt,ze,Fe,nt;let A=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),Se=[],ce=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(D=>{var Vr,Br,ft,At,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=cx(D,Qs)+at,jt=$e||Ge?null:ux(Hn,D.id,Re);if(jt){A.appendChild(jt.cloneNode(!0)),ho(D)&&((ft=D.toolCall)!=null&&ft.id)&&((At=D.agentMetadata)==null?void 0:At.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(Sr=>Sr.id===ur)};Kr=Bt.renderAskUserQuestion({message:D,payload:lr,complete:Qt,resolve:fn=>{var Vn;let Sr=on();Sr&&((Vn=rt.current)==null||Vn.resolveAskUserQuestion(Sr,fn))},dismiss:()=>{var Sr,Vn,lo;let fn=on();(Sr=fn==null?void 0:fn.agentMetadata)!=null&&Sr.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"),A.appendChild(Yt),Se.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,w,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:w});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=w({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=w({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"),A.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,w,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),fx(Hn,D.id,Re,Gt),A.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(At=>Array.from(A.children).find(Gr=>Gr instanceof HTMLElement&&Gr.getAttribute("data-wrapper-id")===At.id)).filter(At=>!!At);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(At=>At.toolCall).filter(At=>!!At),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((At,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(At),Vr.appendChild(Fr)})})}mx(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),A.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),A.appendChild(bt)}}if(Al(c,A),Se.length>0)for(let{messageId:D,fingerprint:$e,bubble:Ge}of Se){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 w;if(To)return;let c=A=>{let _=A.composedPath();_.includes(pe)||Ye&&_.includes(Ye)||Kt(!1,"user")};To=c,((w=e.ownerDocument)!=null?w: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 w;if(Mo)return;let c=A=>{A.key==="Escape"&&(A.isComposing||Kt(!1,"user"))};Mo=c,((w=e.ownerDocument)!=null?w: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,w,A,_;let c=(A=(w=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:w.peek)==null?void 0:A.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 w=(Ct=R==null?void 0:R.getMessages())!=null?Ct:[],A;for(let nt=w.length-1;nt>=0;nt--){let D=w[nt];if(D.role==="assistant"&&D.content){A=D;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let _=A.content,F=!!A.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($,A))===!0,Se=$!==null&&(F||De);Se&&$&&!sa.has($.name)&&(Vp($,e),sa.add($.name));let ce=Se&&($!=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),Se?(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=Se?Ll(_,V.buffer,$,A,F):_;if(Se&&V.placeholder==="skeleton"&&F&&(!Ne||!Ne.trim())){let nt=document.createElement("div"),D=Va();D.classList.add("persona-pill-peek__skeleton"),nt.appendChild(D),Al(g,nt)}else{let nt=Math.max(0,Ne.length-100),D=Ne.length>100?Ne.slice(-100):Ne,$e=os(D);if(!Se||!$){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-${A.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)}Al(g,at),(Fe=$.onAfterRender)==null||Fe.call($,{container:g,bubble:c,messageId:A.id,message:A,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 A=_=>{_.preventDefault(),_.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",A),It.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{ko||(ko=!0,so())},w=()=>{ko&&(ko=!1,so())};le.addEventListener("pointerenter",g),le.addEventListener("pointerleave",w),It.push(()=>{le.removeEventListener("pointerenter",g),le.removeEventListener("pointerleave",w)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",w),It.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",w)}))}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:{},w=(Qe=g.expandedSize)!=null?Qe:"anchored",A=(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)",Se="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=A,Fe.width=_!=null?_:""}if(c&&w!=="fullscreen"){if(w==="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(${A} + ${Se})`,ce.top=U,ce.width=F,ce.maxWidth=De}},Eo=()=>{var $,De,Se,ce,Le,Ne,Qe,gt;if(!H())return;if(B()){let Ct=(Se=((De=($=n.launcher)==null?void 0:$.composerBar)!=null?De:{}).expandedSize)!=null?Se:"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,w=(Ne=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ne:640,A=(gt=(Qe=n.launcher)==null?void 0:Qe.mobileFullscreen)!=null?gt:!0,_=g.innerWidth<=w,F=A&&_&&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 w=W;W=c,Eo();let A=(()=>{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,Se=(Fe=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?Fe:640,ce=$.innerWidth<=Se,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&&A){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(),So(!0));let _={open:W,source:g,timestamp:Date.now()};W&&!w?s.emit("widget:opened",_):!W&&w&&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 w,A,_,F,U,V,$,De,Se,ce,Le;ue.textContent=(A=(w=n.copy)==null?void 0:w.welcomeTitle)!=null?A:"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"))}!((Se=(De=n.sendButton)==null?void 0:De.useIcon)!=null&&Se)&&!(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=>{f(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(w=>{let A=Number(w.getAttribute("data-tool-elapsed"));A&&(w.textContent=Gi(g-A))})},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)),So(!pn),ui(c);let g=[...c].reverse().find(A=>A.role==="user"),w=Pt.lastUserMessageId;g&&g.id!==w&&(Pt.lastUserMessageId=g.id,s.emit("user:message",g)),Pt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),bs(c),so()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};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||So(!0),so()},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":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(),An("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 w;(w=n.onSSEEvent)==null||w.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,w,A;c&&(c.metadata&&(d=yu(c.metadata),k.syncFromMetadata()),(g=c.messages)!=null&&g.length&&R.hydrateMessages(c.messages),(w=c.artifacts)!=null&&w.length&&R.hydrateArtifacts(c.artifacts,(A=c.selectedArtifactId)!=null?A:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ia=()=>{var g,w,A;!B()||W||!((A=(w=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:w.expandOnSubmit)==null||A)||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(),w=(_=mt==null?void 0:mt.hasAttachments())!=null?_:!1;if(!g&&!w)return;ia();let A;w&&(A=[],A.push(...mt.getContentParts()),g&&A.push(Ba(g))),Y.value="",Y.style.height="auto",qo(),R.sendMessage(g,{contentParts:A}),w&&mt.clearAttachments()},yi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},vs={...Sl},As=!1,qo=()=>{vs={...Sl}},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;As=!0,Y.value=c,Y.dispatchEvent(new Event("input",{bubbles:!0})),As=!1;let g=Y.value.length;Y.setSelectionRange(g,g)},da=()=>{As||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,w=dx({direction:c.key==="ArrowUp"?"up":"down",history:bi(),currentValue:Y.value,atStart:g,state:vs});if(vs=w.state,w.handled){c.preventDefault(),w.value!==void 0&&wi(w.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 w;if(((w=n.attachments)==null?void 0:w.enabled)!==!0||!mt)return;let g=kv(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,Se,ce;if(un||R.isStreaming())return;let g=fa();if(!g)return;jr=new g;let A=(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}))},A))},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),An(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=(Se=Le.iconSize)!=null?Se:(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,An(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")}}},Ss=(c,g)=>{var Ct,vt,ze,Fe,nt,D,$e,Ge;let w=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((Ct=c==null?void 0:c.provider)==null?void 0:Ct.type)==="runtype";if(!(w||A))return null;let F=h("div","persona-send-button-wrapper"),U=h("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:$,Se=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,Se,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)&>){let at=h("div","persona-send-button-tooltip");at.textContent=gt,F.appendChild(at)}return{micButton:U,micButtonWrapper:F}},ot=()=>{var g,w,A,_,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:(w=c.iconName)!=null?w:"mic",iconSize:parseFloat((F=(_=c.iconSize)!=null?_:(A=n.sendButton)==null?void 0:A.size)!=null?F:"40")||24}},L=(c,g)=>{var F,U,V,$,De;if(!X)return;let w=X.querySelector("svg");w&&w.remove();let A=(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,A,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,w=c.recordingIconColor,A=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=w!=null?w:"var(--persona-voice-recording-indicator, #ffffff)",w){let F=X.querySelector("svg");F&&F.setAttribute("stroke",w)}A&&(X.style.borderColor=A),X.setAttribute("aria-label","Stop voice recognition")},ie=()=>{var V,$,De,Se,ce,Le,Ne,Qe;if(!X)return;ot();let c=(V=n.voiceRecognition)!=null?V:{},g=R.getVoiceInterruptionMode(),w=($=c.processingIconName)!=null?$:"loader",A=(Se=(De=c.processingIconColor)!=null?De:yt==null?void 0:yt.color)!=null?Se:"",_=(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=A||"currentColor";X.style.color=U,L(w,U),X.setAttribute("aria-label","Processing voice input"),g==="none"&&(X.style.cursor="default")},de=()=>{var De,Se,ce,Le,Ne,Qe,gt,dt,Ct,vt,ze,Fe;if(!X)return;ot();let c=(De=n.voiceRecognition)!=null?De:{},g=R.getVoiceInterruptionMode(),w=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(Se=c.speakingIconName)!=null?Se:w,_=(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(A,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,w;X&&(z(),yt&&(X.style.backgroundColor=(c=yt.backgroundColor)!=null?c:"",X.style.color=(g=yt.color)!=null?g:"",X.style.borderColor=(w=yt.borderColor)!=null?w:"",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 w=R.getVoiceStatus(),A=R.getVoiceInterruptionMode();if(A==="none"&&(w==="processing"||w==="speaking"))return;if(A==="cancel"&&(w==="processing"||w==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{Pt.active=!1,Pt.manuallyDeactivated=!0,tn(),An("user"),re()});return}R.toggleVoice().then(()=>{Pt.active=R.isVoiceActive(),Pt.manuallyDeactivated=!R.isVoiceActive(),tn(),An("user"),R.isVoiceActive()?O():re()});return}if(un){let w=Y.value.trim();Pt.manuallyDeactivated=!0,tn(),_n("user"),w&&(Y.value="",Y.style.height="auto",R.sendMessage(w))}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(),An("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()),So(!0),li(),M&&(!T||B()?setTimeout(()=>Cs(),0):W&&setTimeout(()=>Cs(),200));let yr=()=>{var $,De,Se,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,w=c||g||((ce=(Se=n.launcher)==null?void 0:Se.fullHeight)!=null?ce:!1),A=(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=A.innerWidth<=F,V=_&&U&&T;try{if(V){Rn(),Io(e,n);return}if(E&&(E=!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(),!w){let Hr=A.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),At=Math.max(200,ft-Vr);le.style.height=`${At}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,At=Vr||Br&&Gt&&T||ft;if(At&&!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 At||(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,w=g<qt;qt=g;let{action:A,nextLastScrollTop:_}=Ml({following:Bn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:Fa(J,Zs),userScrollThreshold:ai,isAutoScrolling:ro||Fo||w,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=_,A==="resume"){Ao();return}A==="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"&&Ao()};J.addEventListener("wheel",$r,{passive:!0}),It.push(()=>J.removeEventListener("wheel",$r)),_t.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,Dn=J.scrollTop,Ao(),So(!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(),Ao(),_o(Me.composerOverlay);try{localStorage.removeItem(Xs),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(w){console.error("[AgentWidget] Failed to clear default localStorage:",w)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Xs)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(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)}d={},k.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 Sn=(Rf=e.ownerDocument)!=null?Rf:document;Sn.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 w;if(!td(c.dataTransfer)||!Ts())return;c.preventDefault(),c.stopPropagation(),pd();let g=Array.from((w=c.dataTransfer.files)!=null?w:[]);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),Sn.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 Ar={update(c){var Sr,Vn,lo,vi,Ai,Si,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,Am,Sm,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,Ag,Sg,Tg,Mg,kg,Eg,Lg,Pg,Ig,Rg,Wg,Hg;let g=n.toolCall,w=n.messageActions,A=(Sr=n.layout)==null?void 0:Sr.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,Se=(Ai=n.features)==null?void 0:Ai.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=(Si=n.launcher)==null?void 0:Si.enabled)!=null?Xo:!0,S=(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=h("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 St=Me.clearChatButtonWrapper,Ut=Me.closeButtonWrapper,kr=St||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.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&<.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)!==x&&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,x=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!==b?T?Kt(S,"auto"):(W=!0,Eo()):S!==v&&Kt(S,"auto"),v=S,b=T,yr(),Wr();let ze=JSON.stringify(c.toolCall)!==JSON.stringify(g),Fe=JSON.stringify(n.messageActions)!==JSON.stringify(w),nt=JSON.stringify((nm=n.layout)==null?void 0:nm.messages)!==JSON.stringify(A),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(Se);(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 St=parseFloat(Gt)||24,Ut=Pe(Hr,St*.6,"#ffffff",2);Ut?te.replaceChildren(Ut):te.textContent=(ym=Re.agentIconText)!=null?ym:"\u{1F4AC}"}else if(Re.iconUrl){let St=te.querySelector("img");if(St)St.src=Re.iconUrl,St.style.height=Gt,St.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 St=te.querySelector("svg"),Ut=te.querySelector("img");(St||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=(Am=(vm=n.layout)==null?void 0:vm.header)==null?void 0:Am.showSubtitle;if(qe&&(qe.style.display=Vr===!1?"none":""),tt&&(tt.style.display=Br===!1?"none":""),I){((Tm=(Sm=n.layout)==null?void 0:Sm.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:St}=Me,Ut=tr==="top-right",kr=St==null?void 0:St.classList.contains("persona-absolute");if(St&&Ut!==kr)if(St.remove(),Ut)St.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",be.style.position="relative",be.appendChild(St);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;St.className=Er&&Mt==="inline"?"":"persona-ml-auto";let sn=be.querySelector(".persona-border-b-persona-divider");sn&&sn.appendChild(St)}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),St&&(St._cleanupTooltip&&(St._cleanupTooltip(),delete St._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)};St.addEventListener("mouseenter",Er),St.addEventListener("mouseleave",sn),I.addEventListener("focus",Er),I.addEventListener("blur",sn),St._cleanupTooltip=()=>{sn(),St&&(St.removeEventListener("mouseenter",Er),St.removeEventListener("mouseleave",sn)),I&&(I.removeEventListener("focus",Er),I.removeEventListener("blur",sn))}}}let{clearChatButton:ft,clearChatButtonWrapper:At}=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,St=tr!==void 0?tr:Ot,Ut=($m=ae.placement)!=null?$m:"inline";if(At){At.style.display=St?"":"none";let{closeButtonWrapper:kr}=Me;!B()&&kr&&!kr.classList.contains("persona-absolute")&&(St?kr.classList.remove("persona-ml-auto"):kr.classList.add("persona-ml-auto"));let Ur=Ut==="top-right",Nn=At.classList.contains("persona-absolute");if(!B()&&Ur!==Nn&&St){if(At.remove(),Ur)At.className="persona-absolute persona-top-4 persona-z-50",At.style.right="48px",be.style.position="relative",be.appendChild(At);else{At.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",At.style.right="";let wr=be.querySelector(".persona-border-b-persona-divider"),mn=Me.closeButtonWrapper;wr&&mn&&mn.parentElement===wr?wr.insertBefore(At,mn):wr&&wr.appendChild(At)}let Jr=Me.closeButtonWrapper;Jr&&!Jr.classList.contains("persona-absolute")&&(Ur?Jr.classList.add("persona-ml-auto"):Jr.classList.remove("persona-ml-auto"))}}if(St){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),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._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)};At.addEventListener("mouseenter",Er),At.addEventListener("mouseleave",sn),ft.addEventListener("focus",Er),ft.addEventListener("blur",sn),At._cleanupTooltip=()=>{sn(),At&&(At.removeEventListener("mouseenter",Er),At.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];k=ni({parsers:Gr,handlers:Fr,getSessionMetadata:m,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ve=ay(n,k,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=Ss(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",St=(Qm=Ot.size)!=null?Qm:"40px",Ut=(Zm=ae.iconSize)!=null?Zm:St,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";Ae||(Ae=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ae.style.display="none",ke.insertBefore(Ae,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=h("div","persona-send-button-wrapper"),ct=h("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 St=(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(St,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=h("div","persona-send-button-tooltip");wr.textContent=Jr,Jt.appendChild(wr),ht.append(Jt),!mt&&fe&&Ae&&(mt=cs.fromConfig(ae),mt.setPreviewsContainer(Ae),fe.addEventListener("change",async()=>{mt&&(fe!=null&&fe.files)&&(await mt.handleFileSelect(fe.files),fe.value="")})),be.querySelector(".persona-attachment-drop-overlay")||be.appendChild(iy(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=(Ag=pr.tooltipText)!=null?Ag:"Send message",io=(Sg=pr.showTooltip)!=null?Sg:!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 St,Ut,kr,Ur;return tr==="idle"?(St=ur.idleText)!=null?St: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(),Ao();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(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={},k.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,w;return R.isStreaming()?!1:((w=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:w.type)==="runtype"?(R.isVoiceActive()||(!W&&H()&&Kt(!0,"system"),Pt.manuallyDeactivated=!1,tn(),R.toggleVoice().then(()=>{Pt.active=R.isVoiceActive(),An("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(),An("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 A=R.getMessages().find(_=>{var F;return _.variant==="approval"&&((F=_.approval)==null?void 0:F.id)===c});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${c}`);if(A.approval.toolType==="webmcp"){R.resolveWebMcpApproval(A.id,g);return}return R.resolveApproval(A.approval,g)},getMessages(){return R.getMessages()},getStatus(){return R.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 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 w=Zl({onSubmit:async(A,_)=>{var F;R.isClientTokenMode()&&await R.submitCSATFeedback(A,_),(F=c==null?void 0:c.onSubmit)==null||F.call(c,A,_)},onDismiss:c==null?void 0:c.onDismiss,...c});Ke.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!W&&H()&&Kt(!0,"system");let g=Ke.querySelector(".persona-feedback-container");g&&g.remove();let w=ed({onSubmit:async(A,_)=>{var F;R.isClientTokenMode()&&await R.submitNPSFeedback(A,_),(F=c==null?void 0:c.onSubmit)==null||F.call(c,A,_)},onDismiss:c==null?void 0:c.onDismiss,...c});Ke.appendChild(w),w.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:Ar,getMessages:Ar.getMessages,getStatus:Ar.getStatus,getMetadata:Ar.getPersistentMetadata,updateMetadata:Ar.updatePersistentMetadata,clearHistory:()=>Ar.clearChat(),setVoiceActive:w=>w?Ar.startVoiceRecognition():Ar.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)&&Ar.focusInput()};if(window.addEventListener("persona:focusInput",g),It.push(()=>{window.removeEventListener("persona:focusInput",g)}),we){let V=De=>{let Se=De.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===c)&&Ar.showEventStream()},$=De=>{let Se=De.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===c)&&Ar.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",$),It.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",$)})}let w=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Ar.showArtifacts()},A=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Ar.hideArtifacts()},_=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==c||$!=null&&$.artifact&&Ar.upsertArtifact($.artifact)},F=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==c||typeof($==null?void 0:$.id)=="string"&&Ar.selectArtifact($.id)},U=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===c)&&Ar.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",_),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",U),It.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",_),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",U)})}let Tn=Ev(n.persistState);if(Tn&&H()){let c=Lv(Tn.storage),g=`${Tn.keyPrefix}widget-open`,w=`${Tn.keyPrefix}widget-voice`,A=`${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(w)==="true",U=((Df=Tn.persist)==null?void 0:Df.voiceState)&&c.getItem(A)==="true";if(_&&setTimeout(()=>{Ar.open(),setTimeout(()=>{var V;if(F||U)Ar.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(w,V.active?"true":"false")}),s.on("user:message",V=>{c.setItem(A,V.viaVoice?"true":"false")})),Tn.clearOnChatClear){let V=()=>{c.removeItem(g),c.removeItem(w),c.removeItem(A)},$=()=>V();window.addEventListener("persona:clear-chat",$),It.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return p&&H()&&setTimeout(()=>{Ar.open()},0),so(),Ar};var Pv=(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},ly=(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=""},dy=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=""},Iv=(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))},Rv=(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)},cy=(e,t,r,n,o,s,a)=>{var y,C,k,T,S,M;let i=kn(s),d=i.reveal==="push";Iv(e,t,r,n,d),Rv(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=(C=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?C:!0,u=(T=(k=s==null?void 0:s.launcher)==null?void 0:k.mobileBreakpoint)!=null?T:640,m=l!=null?l.innerWidth<=u:!1;if(p&&m&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),wu(t),bu(n),dy(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=(S=s==null?void 0:s.launcher)==null?void 0:S.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"),dy(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 v=i.animate?"transform 180ms ease":"none",b=i.side==="right"?"translateX(100%)":"translateX(-100%)",x=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=v,n.style.transform=x,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 v=Pv(i.width,e.clientWidth),b=Math.max(0,e.clientWidth),x=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${v}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${v}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=`${b+v}px`,t.style.transition=x,t.style.transform=E,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{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 v=i.reveal==="emerge";v?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let b=a?i.width:"0px",x=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!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=v||E?"hidden":"visible",n.style.transition=x,v&&(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")}},Wv=(e,t)=>{let r=e.ownerDocument.createElement("div");return ly(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){ly(r,n)},destroy(){r.remove()}}},Hv=(e,t)=>{var S,M,v,b;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=(S=t==null?void 0:t.launcher)==null?void 0:S.enabled)==null||M?(b=(v=t==null?void 0:t.launcher)==null?void 0:v.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,e),d.appendChild(e);let m=null,f=()=>{m==null||m.disconnect(),m=null},y=()=>{f(),kn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(m=new ResizeObserver(()=>{cy(a,i,d,l,p,t,u)}),m.observe(a))},C=()=>{cy(a,i,d,l,p,t,u),y()},k=a.ownerDocument.defaultView,T=()=>{C()};return k==null||k.addEventListener("resize",T),kn(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:p,shell:a,syncWidgetState(x){let E=x.launcherEnabled?x.open:!0;u!==E&&(u=E,C())},updateConfig(x){var E,B;t=x,((B=(E=t==null?void 0:t.launcher)==null?void 0:E.enabled)!=null?B:!0)===!1&&(u=!0),C()},destroy(){k==null||k.removeEventListener("resize",T),f(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(e,s):n.appendChild(e)),a.remove()}}},oi=(e,t)=>Tr(t)?Hv(e,t):Wv(e,t);var Au={},Bv=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},Dv=()=>{try{if(typeof Au!="undefined"&&Au.url)return new URL("../widget.css",Au.url).href}catch{}return null},py=(e,t)=>{let r=Dv(),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)}},uy=e=>{var k;let t=Bv(e.target),r=e.useShadowDom===!0,n=t.ownerDocument,o=e.config,s=oi(t,o),a,i=[],d=(T,S)=>{var x,E;let v=!((E=(x=S==null?void 0:S.launcher)==null?void 0:x.enabled)!=null?E:!0)||Tr(S),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),v&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0"),r){let B=T.attachShadow({mode:"open"});B.appendChild(b),py(B,n)}else T.appendChild(b),py(T,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},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()},m=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(k=e.onReady)==null||k.call(e);let f=T=>{m(),s.destroy(),s=oi(t,T),o=T,u()},y={update(T){var E,B,H,W,N,q;let S={...o,...T,launcher:{...(E=o==null?void 0:o.launcher)!=null?E:{},...(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),v=Tr(S),b=Ho(o),x=Ho(S);if(M!==v||b!==x){f(S);return}o=S,s.updateConfig(o),a.update(T),l()},destroy(){m(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(y,{get(T,S,M){if(S==="host")return s.host;if(S in T)return Reflect.get(T,S,M);let v=a[S];return typeof v=="function"?v.bind(a):v}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var xy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ov=new Set(["button","a","input","select","textarea","details","summary"]),_v=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Su=/\b(product|card|item|listing|result)\b/i,Mu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Nv=3e3,$v=100;function yy(e){let t=typeof e.className=="string"?e.className:"";if(Su.test(t)||e.id&&Su.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];if(n.name.startsWith("data-")&&Su.test(n.value))return!0}return!1}function by(e){var t;return Mu.test(((t=e.textContent)!=null?t:"").trim())}function wy(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 Fv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function fy(e){let t=e.match(Mu);return t?t[0]:null}function my(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 Uv(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 zv="commerce-card",qv="result-card";function gy(e){return!yy(e)||!by(e)||!wy(e)&&!Fv(e)?0:5200}function hy(e){var n;return!yy(e)||by(e)||!wy(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:zv,scoreElement(e){return gy(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(gy(e)===0)return null;let{title:r,href:n}=my(e),o=(p=(l=fy(((d=e.textContent)!=null?d:"").trim()))!=null?l:fy(t.text))!=null?p:"",s=Uv(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:qv,scoreElement(e){return hy(e)},formatSummary(e,t){if(hy(e)===0)return null;let{title:r,href:n}=my(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
159
|
+
`)}}];function jv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Vv(e){var p,u,m,f,y,C,k,T,S,M,v,b,x;let t=(p=e.options)!=null?p:{},r=(m=(u=t.maxElements)!=null?u:e.maxElements)!=null?m:80,n=(y=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?y:".persona-host",o=(k=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?k:200,s=(S=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?S:!0,a=(M=t.root)!=null?M:e.root,i=(v=t.mode)!=null?v:"structured",d=(b=t.maxCandidates)!=null?b:Math.max(500,r*10),l=(x=e.rules)!=null?x:ku;return i==="simple"&&e.rules&&e.rules.length>0?(jv(),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 Gv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Kv(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"||Ov.has(t)||r&&_v.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Cy(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 Jv(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 Gv){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 Xv(e){return e==="static"?$v:Nv}function vy(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:Kv(e),attributes:Jv(e)}}function Yv(e,t,r,n){let o=Xv(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 Qv(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 Zv(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(xy.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Cy(l)){i=a.nextNode();continue}let u=vy(l,e.maxTextLength),m=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(k=>k==="role");if(!m&&!f){i=a.nextNode();continue}if(n.has(u.selector)){i=a.nextNode();continue}n.add(u.selector);let{score:y,formattingRule:C}=Yv(l,u,e.rules,r);o.push({el:l,domIndex:s,enriched:u,score:y,formattingRule:C}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,m=p.enriched.interactivity==="static"?1:0;return u!==m?u-m: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;Qv(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,m=p.enriched.interactivity==="static"?1:0;return u!==m?u-m:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var m;let p;if((m=l.formattingRule)!=null&&m.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,r);f&&(p=f)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function eA(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(xy.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Cy(d)){s=o.nextNode();continue}let p=vy(d,e.maxTextLength),u=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!u&&!m){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 Ay(e={}){var n;let t=Vv(e),r=(n=t.root)!=null?n:document.body;return r?t.mode==="simple"?eA(t,r):Zv(t,r):[]}var od=100;function Sy(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:
|
|
160
|
+
${a.map(i=>`- ${i.split(`
|
|
161
161
|
`).join(`
|
|
162
162
|
`)}`).join(`
|
|
163
|
-
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let
|
|
164
|
-
${
|
|
165
|
-
`)}`)}if(o.navigable.length>0){let
|
|
166
|
-
${
|
|
167
|
-
`)}`)}if(o.input.length>0){let
|
|
168
|
-
${
|
|
169
|
-
`)}`)}if(o.static.length>0){let
|
|
170
|
-
${
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
170
|
+
${a.join(`
|
|
171
171
|
`)}`)}return n.join(`
|
|
172
172
|
|
|
173
|
-
`)}var
|
|
173
|
+
`)}var Ty={name:"@runtypelabs/persona",version:"3.23.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=Ty.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 rA(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 My=`({ text, message }: any) => {
|
|
174
174
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
175
175
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
176
176
|
let cleanJson = jsonSource
|
|
@@ -183,7 +183,7 @@ ${s.join(`
|
|
|
183
183
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
184
184
|
} catch (e) { return null; }
|
|
185
185
|
return null;
|
|
186
|
-
}`,
|
|
186
|
+
}`,ky=`function(ctx) {
|
|
187
187
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
188
188
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
189
189
|
var cleanJson = jsonSource
|
|
@@ -196,7 +196,7 @@ ${s.join(`
|
|
|
196
196
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
197
197
|
} catch (e) { return null; }
|
|
198
198
|
return null;
|
|
199
|
-
}`,
|
|
199
|
+
}`,Ey=`(action: any, context: any) => {
|
|
200
200
|
if (action.type !== 'nav_then_click') return;
|
|
201
201
|
const payload = action.payload || action.raw || {};
|
|
202
202
|
const url = payload?.page;
|
|
@@ -213,7 +213,7 @@ ${s.join(`
|
|
|
213
213
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
214
214
|
window.location.href = targetUrl;
|
|
215
215
|
return { handled: true, displayText: text };
|
|
216
|
-
}`,
|
|
216
|
+
}`,Ly=`function(action, context) {
|
|
217
217
|
if (action.type !== 'nav_then_click') return;
|
|
218
218
|
var payload = action.payload || action.raw || {};
|
|
219
219
|
var url = payload.page;
|
|
@@ -230,26 +230,26 @@ ${s.join(`
|
|
|
230
230
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
231
231
|
window.location.href = targetUrl;
|
|
232
232
|
return { handled: true, displayText: text };
|
|
233
|
-
}`,
|
|
233
|
+
}`,nA=`(parsed: any) => {
|
|
234
234
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
235
235
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
236
236
|
if (parsed.action === 'message') return parsed.text || '';
|
|
237
237
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
238
238
|
return parsed.text || null;
|
|
239
|
-
}`,
|
|
239
|
+
}`,oA=`function(parsed) {
|
|
240
240
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
241
241
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
242
242
|
if (parsed.action === 'message') return parsed.text || '';
|
|
243
243
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
244
244
|
return parsed.text || null;
|
|
245
|
-
}`;function
|
|
246
|
-
`)}function
|
|
247
|
-
`)}function Fv(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&&No(n,"theme",e.theme," "),e.launcher&&No(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,a])=>{n.push(` ${o}: "${a}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,a])=>{typeof a=="string"?n.push(` ${o}: "${a}",`):typeof a=="boolean"&&n.push(` ${o}: ${a},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,a])=>{typeof a=="string"?n.push(` ${o}: "${a}",`):typeof a=="boolean"?n.push(` ${o}: ${a},`):typeof a=="number"&&n.push(` ${o}: ${a},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,a])=>{typeof a=="string"?n.push(` ${o}: "${a}",`):typeof a=="boolean"&&n.push(` ${o}: ${a},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,a])=>{n.push(` ${o}: ${a},`)}),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(...rd(e," ")),n.push(...nd(e," ",r)),n.push(...od(e," ")),n.push(...ad(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(${Dv}),`)),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(` ${xy}`),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(` ${xy}`),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(` ${by}`),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(` ${by}`),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
|
|
249
|
-
`)}function
|
|
250
|
-
`).map((
|
|
251
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
252
|
-
`)}var
|
|
245
|
+
}`;function sA(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:sA(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 Py(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}: {`),Py(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}: {`),Py(e,r,`${n} `),e.push(`${n}},`))}function Iy(e,t="esm",r){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let o=r?{...r,hooks:rA(r.hooks)}:void 0;return t==="esm"?aA(n,o):t==="script-installer"?dA(n,o):t==="script-advanced"?pA(n,o):t==="react-component"?iA(n,o):t==="react-advanced"?lA(n,o):cA(n,o)}function aA(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 iA(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 lA(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(${nA}),`)),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(` ${My}`),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(` ${My}`),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(` ${Ey}`),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(` ${Ey}`),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 Ry(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 dA(e,t){let r=Ry(e),n=t!=null&&t.windowKey?{config:r,windowKey:t.windowKey}:r,o=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xs}/dist/install.global.js" data-config='${o}'></script>`}function cA(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 pA(e,t){let r=t==null?void 0:t.hooks,n=Ry(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(${oA});`),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(` ${ky}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${ky}`),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(` ${Ly}`),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(` ${Ly}`),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 Wy={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Hy=.1,By=.15,Dy=1.5,Pu=24,Oy=40,uA=`
|
|
253
253
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
254
254
|
.persona-dc-root {
|
|
255
255
|
display: flex;
|
|
@@ -400,7 +400,7 @@ ${s.join(`
|
|
|
400
400
|
.persona-dc-stage {
|
|
401
401
|
height: 550px;
|
|
402
402
|
min-height: 400px;
|
|
403
|
-
padding: ${
|
|
403
|
+
padding: ${Pu}px;
|
|
404
404
|
overflow: auto;
|
|
405
405
|
background: #f0f1f3;
|
|
406
406
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -490,7 +490,7 @@ ${s.join(`
|
|
|
490
490
|
min-height: 300px;
|
|
491
491
|
}
|
|
492
492
|
}
|
|
493
|
-
`;function
|
|
493
|
+
`;function fA(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=uA,document.head.appendChild(e)}function mA(e,t){let r=e.clientWidth-Pu*2-Oy,n=e.clientHeight-Pu*2-Oy;return r<=0||n<=0?1:Math.min(r/t.w,n/t.h,1)}function gA(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");fA();let p=Math.max(0,Math.min(n,r.length-1)),u=o,m=s,f=null,y=1,C=!1,k=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),S=h("div","persona-dc-toolbar-lead"),M=h("div","persona-dc-toolbar-trail"),v=ir({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>xe(-1)}),b=h("div");b.style.position="relative";let x=h("button","persona-dc-title-btn");x.type="button",x.setAttribute("aria-expanded","false"),x.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),B=h("span","persona-dc-title-chevron"),H=Pe("chevron-down",12,"currentColor",2);H&&B.appendChild(H),x.append(E,B);let W=h("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=h("button","persona-dc-dropdown-item");le.type="button",le.setAttribute("role","option"),le.setAttribute("aria-current",ye===p?"true":"false");let Ye=h("span");if(Ye.textContent=pe.title,le.appendChild(Ye),pe.description){let Me=h("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",x.setAttribute("aria-expanded",N?"true":"false"),N&&q()}function ve(){N&&(N=!1,W.style.display="none",x.setAttribute("aria-expanded","false"))}x.addEventListener("click",ye=>{ye.stopPropagation(),se()});let Ue=()=>ve();document.addEventListener("click",Ue),b.append(x,W);let je=ir({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>xe(1)}),we=h("span","persona-dc-counter");S.append(v,b,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,f=null,G()}}),M.appendChild(Te.element));let We=null;if(a){let ye=h("div","persona-dc-zoom-controls"),pe=ir({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Me=f!=null?f:y;f=Math.max(By,Me-Hy),G()}});We=h("span","persona-dc-zoom-level"),We.title="Reset to 100%",We.style.cursor="pointer",We.addEventListener("click",()=>{f=1,G()});let le=ir({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Me=f!=null?f:y;f=Math.min(Dy,Me+Hy),G()}}),Ye=ir({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,G()}});ye.append(pe,We,le,Ye),M.appendChild(ye)}if(d){let ye=h("div","persona-dc-separator");M.appendChild(ye);let pe=Xa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:m,onSelect:le=>{m=le,j.dataset.colorScheme=m,Z()}});M.appendChild(pe.element)}let Oe=h("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(S,M);let He=h("div","persona-dc-stage"),j=h("div","persona-dc-iframe-wrapper");j.dataset.device=u,j.dataset.colorScheme=m;let Ce=h("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),k.append(T,He),e.appendChild(k);function Z(){var ye;try{let pe=(ye=Ce.contentDocument)==null?void 0:ye.body;if(!pe)return;m==="dark"?pe.classList.add("theme-dark"):pe.classList.remove("theme-dark")}catch{}}Ce.addEventListener("load",()=>Z());function he(){let ye=r[p];E.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(C)return;let ye=(le=Wy[u])!=null?le:Wy.desktop;y=mA(He,ye);let pe=Math.max(By,Math.min(Dy,f!=null?f:y));gA(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(){C||(C=!0,ee.disconnect(),document.removeEventListener("click",Ue),k.remove())}return{element:k,goTo:Ve,next:()=>xe(1),prev:()=>xe(-1),getIndex:()=>p,setDevice(ye){u=ye,j.dataset.device=ye,Te==null||Te.setSelected(ye),f=null,G()},setColorScheme(ye){m=ye,j.dataset.colorScheme=ye},setZoom(ye){f=ye,G()},destroy:Ie}}function Ny(){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 $y(){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 Fy(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 Uy(){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 zy(){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 qy(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var hA={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"}}},jy={components:{panel:{borderRadius:"0",shadow:"none"}}},Iu={id:"shop",label:"Shopping Assistant",config:{theme:hA,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:jy}},Wu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:jy}},Hu={shop:Iu,minimal:Ru,fullscreen:Wu};function Vy(e){return Hu[e]}var xA=`
|
|
494
494
|
@keyframes persona-stream-wipe {
|
|
495
495
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
496
496
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -526,7 +526,7 @@ ${s.join(`
|
|
|
526
526
|
mask-image: none !important;
|
|
527
527
|
}
|
|
528
528
|
}
|
|
529
|
-
`.trim(),
|
|
529
|
+
`.trim(),yA={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:xA};ps(yA);var bA=`
|
|
530
530
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
531
531
|
animation: persona-stream-glyph-cycle-fade
|
|
532
532
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -544,7 +544,7 @@ ${s.join(`
|
|
|
544
544
|
opacity: 1 !important;
|
|
545
545
|
}
|
|
546
546
|
}
|
|
547
|
-
`.trim(),
|
|
547
|
+
`.trim(),si="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",wA=10,CA=120,Bu=120,vA=.4,AA=50,SA=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},eb=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=SA(t);return CA*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},TA=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()<vA&&(o.textContent=Du())}},Gy=new WeakMap,Ky=25,Jy=.5,MA=6,Xy=.25,Yy=new WeakMap,Qy=new WeakMap,kA=(e,t)=>{var o;if(!e)return Ky*Jy;let r=Yy.get(e);Yy.set(e,t);let n=(o=Qy.get(e))!=null?o:Ky;if(r!==void 0){let s=t-r;s>1&&(n=n*(1-Xy)+s*Xy,Qy.set(e,n))}return Math.max(MA,n*Jy)},Ys=new Map,EA=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},LA=e=>{var t;e&&Ys.set(e,((t=Ys.get(e))!=null?t:0)+1)},PA=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)},tb=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=EA(e);r&&(e.dataset.glyphCycleMessageId=r),LA(r);let n=e.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=kA(n,o),a=eb(e),i=wA*a,d=o+i;if(n){let p=Gy.get(n);p!==void 0&&(d=Math.max(d,p)),Gy.set(n,d+s)}IA(e,t,d)},IA=(e,t,r)=>{var a;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let n=eb(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,PA((d=e.dataset.glyphCycleMessageId)!=null?d:null),delete e.dataset.glyphCycleMessageId;return}let i=Du(o);e.textContent=i,o=i,TA(e),setTimeout(s,n)};setTimeout(s,n)},Zy=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))tb(n)},RA=e=>e.nodeType===1,WA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:bA,bufferContent(e){if(e.length<AA)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){Zy(e);let t=new MutationObserver(r=>{for(let n of r)for(let o of Array.from(n.addedNodes))RA(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?tb(o):Zy(o))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ps(WA);return lb(HA);})();
|
|
548
548
|
/*! Bundled license information:
|
|
549
549
|
|
|
550
550
|
dompurify/dist/purify.es.mjs:
|