@runtypelabs/persona 3.28.0 → 3.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-CxvHw0X6.d.cts → types-B_Qazlm4.d.cts} +6 -0
- package/dist/animations/{types-CxvHw0X6.d.ts → types-B_Qazlm4.d.ts} +6 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +11 -11
- package/dist/codegen.d.cts +9 -0
- package/dist/codegen.d.ts +9 -0
- package/dist/codegen.js +12 -12
- package/dist/index.cjs +40 -40
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.global.js +47 -47
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +40 -40
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor.cjs +30 -30
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/theme-editor.js +30 -30
- package/package.json +1 -1
- package/src/client.test.ts +40 -0
- package/src/client.ts +18 -4
- package/src/codegen.test.ts +43 -0
- package/src/generated/runtype-openapi-contract.ts +12 -0
- package/src/session.ts +190 -29
- package/src/session.webmcp.test.ts +326 -6
- package/src/utils/code-generators.ts +38 -9
package/dist/index.global.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var Oy=Object.create;var gs=Object.defineProperty;var _y=Object.getOwnPropertyDescriptor;var Ny=Object.getOwnPropertyNames;var Fy=Object.getPrototypeOf,$y=Object.prototype.hasOwnProperty;var Sg=t=>{throw TypeError(t)};var Uy=(t,e,r)=>e in t?gs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Gn=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kg=(t,e)=>{for(var r in e)gs(t,r,{get:e[r],enumerable:!0})},Mg=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ny(e))!$y.call(t,o)&&o!==r&&gs(t,o,{get:()=>e[o],enumerable:!(n=_y(e,o))||n.enumerable});return t};var od=(t,e,r)=>(r=t!=null?Oy(Fy(t)):{},Mg(e||!t||!t.__esModule?gs(r,"default",{value:t,enumerable:!0}):r,t)),qy=t=>Mg(gs({},"__esModule",{value:!0}),t);var Ht=(t,e,r)=>Uy(t,typeof e!="symbol"?e+"":e,r),zy=(t,e,r)=>e.has(t)||Sg("Cannot "+r);var Eg=(t,e,r)=>e.has(t)?Sg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Ai=(t,e,r)=>(zy(t,e,"access private method"),r);function Ea(t,e){let r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let n=t.length;if(n!==e.length)return!1;for(let o=0;o<n;o++)if(!Ea(t[o],e[o]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(let a of n)if(!Ea(t[a],e[a]))return!1;return!0}return t===e}var Ad=Gn(()=>{"use strict"});function xn(t){return encodeURI(Jb(t))}function Jb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Ri=Gn(()=>{"use strict"});function uo(t,e=Object.create(null),r=e0,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t.$id||t.id;if(s){let a=new URL(s,r.href);a.hash.length>1?e[a.href]=t:(a.hash="",n===""?r=a:uo(t,e,r))}}else if(t!==!0&&t!==!1)return e;let o=r.href+(n?"#"+n:"");if(e[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(e[o]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),t.$ref&&t.__absolute_ref__===void 0){let s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){let s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(Zb[s])continue;let a=`${n}/${xn(s)}`,i=t[s];if(Array.isArray(i)){if(Qb[s]){let d=i.length;for(let l=0;l<d;l++)uo(i[l],e,r,`${a}/${l}`)}}else if(Yb[s])for(let d in i)uo(i[d],e,r,`${a}/${xn(d)}`);else uo(i,e,r,a)}return e}var Qb,Yb,Zb,e0,Wi=Gn(()=>{"use strict";Ri();Qb={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Yb={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Zb={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},e0=typeof self!="undefined"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Xn(t){return t.test.bind(t)}function h0(t){return t%4===0&&(t%100!==0||t%400===0)}function dh(t){let e=t.match(t0);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&h0(r)?29:r0[n])}function ch(t,e){let r=e.match(n0);if(!r)return!1;let n=+r[1],o=+r[2],s=+r[3],a=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!t||a)}function y0(t){let e=t.split(x0);return e.length==2&&dh(e[0])&&ch(!0,e[1])}function v0(t){return b0.test(t)&&w0.test(t)}function A0(t){if(C0.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var t0,r0,n0,o0,a0,s0,i0,l0,d0,c0,p0,u0,f0,m0,g0,Sd,x0,b0,w0,C0,Td=Gn(()=>{"use strict";t0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r0=[0,31,28,31,30,31,30,31,31,30,31,30,31],n0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,o0=/^(?=.{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,a0=/^(?:[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,s0=/^(?:(?:[^\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,i0=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,l0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,d0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,c0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,p0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,u0=t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},f0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,m0=/^((([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,g0=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));Sd={date:dh,time:ch.bind(void 0,!1),"date-time":y0,duration:g0,uri:v0,"uri-reference":Xn(a0),"uri-template":Xn(s0),url:Xn(i0),email:u0,hostname:Xn(o0),ipv4:Xn(f0),ipv6:Xn(m0),regex:A0,uuid:Xn(l0),"json-pointer":Xn(d0),"json-pointer-uri-fragment":Xn(c0),"relative-json-pointer":Xn(p0)};x0=/t|\s/i;b0=/\/|:/,w0=/^(?:[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;C0=/[^\\]\\Z/});var ph,uh=Gn(()=>{"use strict";(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(ph||(ph={}))});function fh(t){let e=0,r=t.length,n=0,o;for(;n<r;)e++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=t.charCodeAt(n),(o&64512)==56320&&n++);return e}var kd=Gn(()=>{"use strict"});function ur(t,e,r="2019-09",n=uo(e),o=!0,s=null,a="#",i="#",d=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let l=typeof t,p;switch(l){case"boolean":case"number":case"string":p=l;break;case"object":t===null?p="null":Array.isArray(t)?p="array":p="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:m,$recursiveRef:u,$recursiveAnchor:f,type:y,const:A,enum:S,required:M,not:k,anyOf:E,allOf:h,oneOf:w,if:x,then:T,else:W,format:R,properties:B,patternProperties:_,additionalProperties:V,unevaluatedProperties:oe,minProperties:be,maxProperties:Qe,propertyNames:je,dependentRequired:ve,dependentSchemas:Ee,dependencies:Ge,prefixItems:_e,items:X,additionalItems:Ue,unevaluatedItems:K,contains:Te,minContains:ae,maxContains:xe,minItems:ke,maxItems:Ke,uniqueItems:ce,minimum:re,maximum:le,exclusiveMinimum:ut,exclusiveMaximum:Ce,multipleOf:he,minLength:tt,maxLength:Ne,pattern:me,__absolute_ref__:J,__absolute_recursive_ref__:ze}=e,Z=[];if(f===!0&&s===null&&(s=e),u==="#"){let z=s===null?n[ze]:s,Re=`${i}/$recursiveRef`,Ae=ur(t,s===null?e:s,r,n,o,z,a,Re,d);Ae.valid||Z.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:Re,error:"A subschema had errors."},...Ae.errors)}if(m!==void 0){let Re=n[J||m];if(Re===void 0){let pe=`Unresolved $ref "${m}".`;throw J&&J!==m&&(pe+=` Absolute URI "${J}".`),pe+=`
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var _y=Object.create;var hs=Object.defineProperty;var Fy=Object.getOwnPropertyDescriptor;var $y=Object.getOwnPropertyNames;var Uy=Object.getPrototypeOf,qy=Object.prototype.hasOwnProperty;var Tg=t=>{throw TypeError(t)};var zy=(t,e,r)=>e in t?hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Gn=(t,e)=>()=>(t&&(e=t(t=0)),e);var Mg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kg=(t,e)=>{for(var r in e)hs(t,r,{get:e[r],enumerable:!0})},Eg=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $y(e))!qy.call(t,o)&&o!==r&&hs(t,o,{get:()=>e[o],enumerable:!(n=Fy(e,o))||n.enumerable});return t};var ad=(t,e,r)=>(r=t!=null?_y(Uy(t)):{},Eg(e||!t||!t.__esModule?hs(r,"default",{value:t,enumerable:!0}):r,t)),Vy=t=>Eg(hs({},"__esModule",{value:!0}),t);var Ht=(t,e,r)=>zy(t,typeof e!="symbol"?e+"":e,r),jy=(t,e,r)=>e.has(t)||Tg("Cannot "+r);var Lg=(t,e,r)=>e.has(t)?Tg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Si=(t,e,r)=>(jy(t,e,"access private method"),r);function La(t,e){let r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let n=t.length;if(n!==e.length)return!1;for(let o=0;o<n;o++)if(!La(t[o],e[o]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(let a of n)if(!La(t[a],e[a]))return!1;return!0}return t===e}var Sd=Gn(()=>{"use strict"});function xn(t){return encodeURI(Yb(t))}function Yb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Wi=Gn(()=>{"use strict"});function uo(t,e=Object.create(null),r=r0,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t.$id||t.id;if(s){let a=new URL(s,r.href);a.hash.length>1?e[a.href]=t:(a.hash="",n===""?r=a:uo(t,e,r))}}else if(t!==!0&&t!==!1)return e;let o=r.href+(n?"#"+n:"");if(e[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(e[o]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),t.$ref&&t.__absolute_ref__===void 0){let s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){let s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(t0[s])continue;let a=`${n}/${xn(s)}`,i=t[s];if(Array.isArray(i)){if(Zb[s]){let d=i.length;for(let l=0;l<d;l++)uo(i[l],e,r,`${a}/${l}`)}}else if(e0[s])for(let d in i)uo(i[d],e,r,`${a}/${xn(d)}`);else uo(i,e,r,a)}return e}var Zb,e0,t0,r0,Bi=Gn(()=>{"use strict";Wi();Zb={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},e0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},t0={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},r0=typeof self!="undefined"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Xn(t){return t.test.bind(t)}function y0(t){return t%4===0&&(t%100!==0||t%400===0)}function ch(t){let e=t.match(n0);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&y0(r)?29:o0[n])}function ph(t,e){let r=e.match(a0);if(!r)return!1;let n=+r[1],o=+r[2],s=+r[3],a=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!t||a)}function w0(t){let e=t.split(b0);return e.length==2&&ch(e[0])&&ph(!0,e[1])}function A0(t){return v0.test(t)&&C0.test(t)}function T0(t){if(S0.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var n0,o0,a0,s0,i0,l0,d0,c0,p0,u0,f0,m0,g0,h0,x0,Td,b0,v0,C0,S0,Md=Gn(()=>{"use strict";n0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o0=[0,31,28,31,30,31,30,31,31,30,31,30,31],a0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s0=/^(?=.{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,i0=/^(?:[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,l0=/^(?:(?:[^\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,d0=/^(?:(?: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,c0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,p0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,u0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,m0=t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},g0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,h0=/^((([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,x0=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));Td={date:ch,time:ph.bind(void 0,!1),"date-time":w0,duration:x0,uri:A0,"uri-reference":Xn(i0),"uri-template":Xn(l0),url:Xn(d0),email:m0,hostname:Xn(s0),ipv4:Xn(g0),ipv6:Xn(h0),regex:T0,uuid:Xn(c0),"json-pointer":Xn(p0),"json-pointer-uri-fragment":Xn(u0),"relative-json-pointer":Xn(f0)};b0=/t|\s/i;v0=/\/|:/,C0=/^(?:[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;S0=/[^\\]\\Z/});var uh,fh=Gn(()=>{"use strict";(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(uh||(uh={}))});function mh(t){let e=0,r=t.length,n=0,o;for(;n<r;)e++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=t.charCodeAt(n),(o&64512)==56320&&n++);return e}var kd=Gn(()=>{"use strict"});function ur(t,e,r="2019-09",n=uo(e),o=!0,s=null,a="#",i="#",d=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let l=typeof t,p;switch(l){case"boolean":case"number":case"string":p=l;break;case"object":t===null?p="null":Array.isArray(t)?p="array":p="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:m,$recursiveRef:u,$recursiveAnchor:f,type:x,const:C,enum:S,required:k,not:T,anyOf:M,allOf:h,oneOf:w,if:y,then:E,else:B,format:P,properties:R,patternProperties:O,additionalProperties:V,unevaluatedProperties:ne,minProperties:be,maxProperties:Ye,propertyNames:Ge,dependentRequired:ve,dependentSchemas:Ee,dependencies:Ke,prefixItems:Ne,items:X,additionalItems:Ue,unevaluatedItems:K,contains:Te,minContains:oe,maxContains:xe,minItems:Me,maxItems:Xe,uniqueItems:ce,minimum:te,maximum:le,exclusiveMinimum:ut,exclusiveMaximum:Ce,multipleOf:he,minLength:rt,maxLength:_e,pattern:me,__absolute_ref__:J,__absolute_recursive_ref__:ze}=e,Z=[];if(f===!0&&s===null&&(s=e),u==="#"){let z=s===null?n[ze]:s,Re=`${i}/$recursiveRef`,Ae=ur(t,s===null?e:s,r,n,o,z,a,Re,d);Ae.valid||Z.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:Re,error:"A subschema had errors."},...Ae.errors)}if(m!==void 0){let Re=n[J||m];if(Re===void 0){let pe=`Unresolved $ref "${m}".`;throw J&&J!==m&&(pe+=` Absolute URI "${J}".`),pe+=`
|
|
2
2
|
Known schemas:
|
|
3
3
|
- ${Object.keys(n).join(`
|
|
4
|
-
- `)}`,new Error(pe)}let Ae=`${i}/$ref`,fe=ur(t,Re,r,n,o,s,a,Ae,d);if(fe.valid||Z.push({instanceLocation:a,keyword:"$ref",keywordLocation:Ae,error:"A subschema had errors."},...fe.errors),r==="4"||r==="7")return{valid:Z.length===0,errors:Z}}if(Array.isArray(y)){let z=y.length,Re=!1;for(let Ae=0;Ae<z;Ae++)if(p===y[Ae]||y[Ae]==="integer"&&p==="number"&&t%1===0&&t===t){Re=!0;break}Re||Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y.join('", "')}".`})}else y==="integer"?(p!=="number"||t%1||t!==t)&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`}):y!==void 0&&p!==y&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`});if(A!==void 0&&(p==="object"||p==="array"?Ea(t,A)||Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(A)}.`}):t!==A&&Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})),S!==void 0&&(p==="object"||p==="array"?S.some(z=>Ea(t,z))||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(z=>t===z)||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),k!==void 0){let z=`${i}/not`;ur(t,k,r,n,o,s,a,z).valid&&Z.push({instanceLocation:a,keyword:"not",keywordLocation:z,error:'Instance matched "not" schema.'})}let ge=[];if(E!==void 0){let z=`${i}/anyOf`,Re=Z.length,Ae=!1;for(let fe=0;fe<E.length;fe++){let pe=E[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${z}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae||Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:z,error:"Instance does not match any subschemas."})}if(h!==void 0){let z=`${i}/allOf`,Re=Z.length,Ae=!0;for(let fe=0;fe<h.length;fe++){let pe=h[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${z}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae&&Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"allOf",keywordLocation:z,error:"Instance does not match every subschema."})}if(w!==void 0){let z=`${i}/oneOf`,Re=Z.length,Ae=w.filter((fe,pe)=>{let Be=Object.create(d),Q=ur(t,fe,r,n,o,f===!0?s:null,a,`${z}/${pe}`,Be);return Z.push(...Q.errors),Q.valid&&ge.push(Be),Q.valid}).length;Ae===1?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:z,error:`Instance does not match exactly one subschema (${Ae} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...ge),x!==void 0){let z=`${i}/if`;if(ur(t,x,r,n,o,s,a,z,d).valid){if(T!==void 0){let Ae=ur(t,T,r,n,o,s,a,`${i}/then`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "then" schema.'},...Ae.errors)}}else if(W!==void 0){let Ae=ur(t,W,r,n,o,s,a,`${i}/else`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "else" schema.'},...Ae.errors)}}if(p==="object"){if(M!==void 0)for(let fe of M)fe in t||Z.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${fe}".`});let z=Object.keys(t);if(be!==void 0&&z.length<be&&Z.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${be} properties.`}),Qe!==void 0&&z.length>Qe&&Z.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Qe} properties.`}),je!==void 0){let fe=`${i}/propertyNames`;for(let pe in t){let Be=`${a}/${xn(pe)}`,Q=ur(pe,je,r,n,o,s,Be,fe);Q.valid||Z.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:fe,error:`Property name "${pe}" does not match schema.`},...Q.errors)}}if(ve!==void 0){let fe=`${i}/dependantRequired`;for(let pe in ve)if(pe in t){let Be=ve[pe];for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`})}}if(Ee!==void 0)for(let fe in Ee){let pe=`${i}/dependentSchemas`;if(fe in t){let Be=ur(t,Ee[fe],r,n,o,s,a,`${pe}/${xn(fe)}`,d);Be.valid||Z.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:pe,error:`Instance has "${fe}" but does not match dependant schema.`},...Be.errors)}}if(Ge!==void 0){let fe=`${i}/dependencies`;for(let pe in Ge)if(pe in t){let Be=Ge[pe];if(Array.isArray(Be))for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`});else{let Q=ur(t,Be,r,n,o,s,a,`${fe}/${xn(pe)}`);Q.valid||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not match dependant schema.`},...Q.errors)}}}let Re=Object.create(null),Ae=!1;if(B!==void 0){let fe=`${i}/properties`;for(let pe in B){if(!(pe in t))continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],B[pe],r,n,o,s,Be,`${fe}/${xn(pe)}`);if(Q.valid)d[pe]=Re[pe]=!0;else if(Ae=o,Z.push({instanceLocation:a,keyword:"properties",keywordLocation:fe,error:`Property "${pe}" does not match schema.`},...Q.errors),Ae)break}}if(!Ae&&_!==void 0){let fe=`${i}/patternProperties`;for(let pe in _){let Be=new RegExp(pe,"u"),Q=_[pe];for(let N in t){if(!Be.test(N))continue;let Me=`${a}/${xn(N)}`,He=ur(t[N],Q,r,n,o,s,Me,`${fe}/${xn(pe)}`);He.valid?d[N]=Re[N]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:fe,error:`Property "${N}" matches pattern "${pe}" but does not match associated schema.`},...He.errors))}}}if(!Ae&&V!==void 0){let fe=`${i}/additionalProperties`;for(let pe in t){if(Re[pe])continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],V,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:fe,error:`Property "${pe}" does not match additional properties schema.`},...Q.errors))}}else if(!Ae&&oe!==void 0){let fe=`${i}/unevaluatedProperties`;for(let pe in t)if(!d[pe]){let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],oe,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:Z.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:fe,error:`Property "${pe}" does not match unevaluated properties schema.`},...Q.errors)}}}else if(p==="array"){Ke!==void 0&&t.length>Ke&&Z.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${t.length} > ${Ke}).`}),ke!==void 0&&t.length<ke&&Z.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${t.length} < ${ke}).`});let z=t.length,Re=0,Ae=!1;if(_e!==void 0){let fe=`${i}/prefixItems`,pe=Math.min(_e.length,z);for(;Re<pe;Re++){let Be=ur(t[Re],_e[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}if(X!==void 0){let fe=`${i}/items`;if(Array.isArray(X)){let pe=Math.min(X.length,z);for(;Re<pe;Re++){let Be=ur(t[Re],X[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}else for(;Re<z;Re++){let pe=ur(t[Re],X,r,n,o,s,`${a}/${Re}`,fe);if(d[Re]=!0,!pe.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...pe.errors),Ae))break}if(!Ae&&Ue!==void 0){let pe=`${i}/additionalItems`;for(;Re<z;Re++){let Be=ur(t[Re],Ue,r,n,o,s,`${a}/${Re}`,pe);d[Re]=!0,Be.valid||(Ae=o,Z.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:pe,error:"Items did not match additional items schema."},...Be.errors))}}}if(Te!==void 0)if(z===0&&ae===void 0)Z.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ae!==void 0&&z<ae)Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${z}) than minContains (${ae}).`});else{let fe=`${i}/contains`,pe=Z.length,Be=0;for(let Q=0;Q<z;Q++){let N=ur(t[Q],Te,r,n,o,s,`${a}/${Q}`,fe);N.valid?(d[Q]=!0,Be++):Z.push(...N.errors)}Be>=(ae||0)&&(Z.length=pe),ae===void 0&&xe===void 0&&Be===0?Z.splice(pe,0,{instanceLocation:a,keyword:"contains",keywordLocation:fe,error:"Array does not contain item matching schema."}):ae!==void 0&&Be<ae?Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${ae} items matching schema. Only ${Be} items were found.`}):xe!==void 0&&Be>xe&&Z.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${xe} items matching schema. ${Be} items were found.`})}if(!Ae&&K!==void 0){let fe=`${i}/unevaluatedItems`;for(Re;Re<z;Re++){if(d[Re])continue;let pe=ur(t[Re],K,r,n,o,s,`${a}/${Re}`,fe);d[Re]=!0,pe.valid||Z.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:fe,error:"Items did not match unevaluated items schema."},...pe.errors)}}if(ce)for(let fe=0;fe<z;fe++){let pe=t[fe],Be=typeof pe=="object"&&pe!==null;for(let Q=0;Q<z;Q++){if(fe===Q)continue;let N=t[Q];(pe===N||Be&&(typeof N=="object"&&N!==null)&&Ea(pe,N))&&(Z.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${fe} and ${Q}.`}),fe=Number.MAX_SAFE_INTEGER,Q=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(re!==void 0&&(ut===!0&&t<=re||t<re)&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${ut?"or equal to ":""} ${re}.`}),le!==void 0&&(Ce===!0&&t>=le||t>le)&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${Ce?"or equal to ":""} ${le}.`})):(re!==void 0&&t<re&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${re}.`}),le!==void 0&&t>le&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${le}.`}),ut!==void 0&&t<=ut&&Z.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${t} is less than ${ut}.`}),Ce!==void 0&&t>=Ce&&Z.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ce}.`})),he!==void 0){let z=t%he;Math.abs(0-z)>=11920929e-14&&Math.abs(he-z)>=11920929e-14&&Z.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${t} is not a multiple of ${he}.`})}}else if(p==="string"){let z=tt===void 0&&Ne===void 0?0:fh(t);tt!==void 0&&z<tt&&Z.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${z} < ${tt}).`}),Ne!==void 0&&z>Ne&&Z.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${z} > ${Ne}).`}),me!==void 0&&!new RegExp(me,"u").test(t)&&Z.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),R!==void 0&&Sd[R]&&!Sd[R](t)&&Z.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${R}".`})}return{valid:Z.length===0,errors:Z}}var Md=Gn(()=>{"use strict";Ad();Wi();Td();Ri();kd()});var Bi,mh=Gn(()=>{"use strict";Wi();Md();Bi=class{constructor(e,r="2019-09",n=!0){Ht(this,"schema");Ht(this,"draft");Ht(this,"shortCircuit");Ht(this,"lookup");this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=uo(e)}validate(e){return ur(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),uo(e,this.lookup)}}});var gh=Gn(()=>{"use strict";Ad();Wi();Td();Ri();uh();kd();Md();mh()});var kh={};kg(kh,{cleanupWebMCPPolyfill:()=>Th,initializeWebMCPPolyfill:()=>Sh,initializeWebModelContextPolyfill:()=>Sh,isPlainObject:()=>Hr,validateArgsWithSchema:()=>vh});function Jn(t){try{return new DOMException(t,"UnknownError")}catch{let e=new Error(t);return e.name="UnknownError",e}}function E0(t){let e;try{e=JSON.parse(t)}catch{throw Jn(hh)}if(!e||typeof e!="object"||Array.isArray(e))throw Jn(hh);return e}function L0(t){if(typeof t=="string")return t;if(Hr(t)&&typeof t.name=="string")return t.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function Hr(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function bh(t){if(!Hr(t))return null;let e=t["~standard"];return Hr(e)?e:null}function P0(t){let e=bh(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function I0(t){let e=bh(t);return!e||e.version!==1||!Hr(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function Di(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!Hr(e))return{issues:[{message:"expected object arguments"}]};let r=vh(e,t);return r?{issues:[r]}:{value:e}}}}}function R0(t){for(let e of S0)try{let r=t["~standard"].jsonSchema.input({target:e});return wh(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function W0(t){if(t===void 0){let r=Hi;return{inputSchema:r,standardValidator:Di(r)}}if(I0(t)){let r=R0(t);return{inputSchema:r,standardValidator:Di(r)}}if(P0(t))return{inputSchema:Hi,standardValidator:t};if(wh(t),Object.keys(t).length===0)return{inputSchema:Hi,standardValidator:Di(Hi)};let e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:Di(e)}}function wh(t){if(!Hr(t))throw new Error("inputSchema must be a JSON Schema object");La(t,"$")}function La(t,e){let r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);let n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);let o=t.properties;if(o!==void 0){if(!Hr(o))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.properties.${i}: expected object schema`);La(d,`${e}.properties.${i}`)}}let s=t.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.items[${i}]: expected object schema`);La(d,`${e}.items[${i}]`)}else if(Hr(s))La(s,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(let i of["allOf","anyOf","oneOf"]){let d=t[i];if(d!==void 0){if(!Array.isArray(d))throw new Error(`Invalid JSON Schema at ${e}: "${i}" must be an array`);for(let[l,p]of d.entries()){if(!Hr(p))throw new Error(`Invalid JSON Schema at ${e}.${i}[${l}]: expected object schema`);La(p,`${e}.${i}[${l}]`)}}}let a=t.not;if(a!==void 0){if(!Hr(a))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);La(a,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function B0(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);let r=W0(t.inputSchema),n=t.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...o?{annotations:o}:{},inputSchema:r.inputSchema,[yh]:r.standardValidator}}function vh(t,e){let r=new Bi(e,"2020-12",!0).validate(t);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function H0(t){if(!t||t.length===0)return null;let e=t.map(r=>Hr(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function D0(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(s){let a=s instanceof Error?`: ${s.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",s),`Input validation error: schema validation failed${a}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let o=H0(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function O0(t,e){return D0(t,e[yh])}function _0(t){return Hr(t)&&Array.isArray(t.content)}function N0(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Ld(t){return N0(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>Ld(e)):Hr(t)?Object.values(t).every(e=>Ld(e)):!1}function F0(t){if(!(!Hr(t)||!Ld(t)))return t}function $0(t){var e;if(typeof t=="string")return t;try{return(e=JSON.stringify(t))!=null?e:String(t)}catch{return String(t)}}function U0(t){if(_0(t))return t;let e=F0(t);return{content:[{type:"text",text:$0(t)}],...e?{structuredContent:e}:{},isError:!1}}function q0(t){var e;for(let r of(e=t.content)!=null?e:[])if(r.type==="text"&&"text"in r&&typeof r.text=="string")return r.text;return null}function z0(t){var r;if(t.isError)throw Jn(((r=q0(t))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||Oi);let e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw Jn(Oi)}}function V0(t,e){return e?e.aborted?Promise.reject(Jn(Ed)):new Promise((r,n)=>{let o=()=>{s(),n(Jn(Ed))},s=()=>{e.removeEventListener("abort",o)};e.addEventListener("abort",o,{once:!0}),t.then(a=>{s(),r(a)},a=>{s(),n(a)})}):t}function Ch(){return typeof navigator!="undefined"?navigator:null}function Ah(){return typeof document!="undefined"?document:null}function j0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function xh(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}function G0(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return _i||(_i=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),e}})}function Sh(t){var d;let e=Ch(),r=Ah();if(!e&&!r||(r==null?void 0:r.modelContext))return;let o=e==null?void 0:e.modelContext,s=!!o;if(lr.installed&&Th(),r&&o){lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),xh(r,o),lr.installedDocumentModelContext=!0,lr.installed=!0;return}if(s)return;let a=new k0,i=a;if(i[T0]=!0,r&&(lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),xh(r,i),lr.installedDocumentModelContext=!0),e){lr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),lr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),_i=!1,G0(e,i),lr.installedNavigatorModelContext=!0;let l=(d=t==null?void 0:t.installTestingShim)!=null?d:"if-missing",p=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!p)&&(j0(e,"modelContextTesting",a.getTestingShim()),lr.installedNavigatorModelContextTesting=!0)}lr.installed=!0}function Th(){if(!lr.installed)return;let t=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},e=Ch(),r=Ah();r&&lr.installedDocumentModelContext&&t(r,"modelContext",lr.previousDocumentModelContextDescriptor),e&&lr.installedNavigatorModelContext&&t(e,"modelContext",lr.previousNavigatorModelContextDescriptor),e&&lr.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",lr.previousNavigatorModelContextTestingDescriptor),lr.installed=!1,lr.previousDocumentModelContextDescriptor=void 0,lr.previousNavigatorModelContextDescriptor=void 0,lr.previousNavigatorModelContextTestingDescriptor=void 0,lr.installedDocumentModelContext=!1,lr.installedNavigatorModelContext=!1,lr.installedNavigatorModelContextTesting=!1,_i=!1}var hh,Oi,Ed,Hi,S0,T0,yh,lr,k0,M0,_i,Mh=Gn(()=>{"use strict";gh();hh="Failed to parse input arguments",Oi="Tool was executed but the invocation failed. For example, the script function threw an error",Ed="Tool was cancelled",Hi={type:"object",properties:{}},S0=["draft-2020-12","draft-07"],T0="__isWebMCPPolyfill",yh=Symbol("standardValidator"),lr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},k0=class extends EventTarget{constructor(){super(...arguments);Ht(this,"tools",new Map);Ht(this,"testingShim",null);Ht(this,"_ontoolchange",null);Ht(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,r){var s;let n=r==null?void 0:r.signal;if(n!=null&&n.aborted){console.warn(`[WebMCPPolyfill] registerTool("${(s=e==null?void 0:e.name)!=null?s:"<unknown>"}") skipped: options.signal was already aborted.`);return}let o=B0(e,this.tools);this.tools.set(o.name,o),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(o.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let r=L0(e);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,r,n){return this.executeToolByName(e.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new M0(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{var n;let r;try{r=JSON.stringify((n=e.inputSchema)!=null?n:{type:"object"})}catch{r='{"type":"object"}'}return{name:e.name,description:e.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{var n,o,s;let r=this.tools.get(e.name);return{...e,title:(n=r==null?void 0:r.title)!=null?n:"",origin:(s=(o=globalThis.location)==null?void 0:o.origin)!=null?s:"",window:globalThis.window}})}async executeToolForTesting(e,r,n){return this.executeToolByName(e,r,n,!0)}async executeToolByName(e,r,n,o){var p;if((p=n==null?void 0:n.signal)!=null&&p.aborted)throw Jn(Ed);let s=this.tools.get(e);if(!s)throw Jn(`Tool not found: ${e}`);let a=E0(r),i=await O0(a,s);if(i)throw Jn(i);let d=!0,l={requestUserInteraction:async m=>{if(!d)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof m!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return m()}};try{let m=s.execute(a,l),u=await V0(Promise.resolve(m),n==null?void 0:n.signal);if(o)return z0(U0(u));let f=JSON.stringify(u);return f===void 0?null:f}catch(m){throw Jn(m instanceof Error?`${Oi}: ${m.message}`:Oi)}finally{d=!1}}notifyToolsChanged(){queueMicrotask(()=>{var r,n;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(o){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",o)}this.dispatchEvent(e),(n=this.testingShim)==null||n.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},M0=class extends EventTarget{constructor(e){super();Ht(this,"context");Ht(this,"_ontoolchange",null);this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,r,n){return this.context.executeToolForTesting(e,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",e)}dispatchToolChange(){var r;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(n){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",n)}this.dispatchEvent(e),this.dispatchEvent(new Event("toolschanged"))}};_i=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let t=window.__webMCPPolyfillOptions;if((t==null?void 0:t.autoInitialize)!==!1)try{Sh(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}});var Id=Tg(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.Allow=Ze.ALL=Ze.COLLECTION=Ze.ATOM=Ze.SPECIAL=Ze.INF=Ze._INFINITY=Ze.INFINITY=Ze.NAN=Ze.BOOL=Ze.NULL=Ze.OBJ=Ze.ARR=Ze.NUM=Ze.STR=void 0;Ze.STR=1;Ze.NUM=2;Ze.ARR=4;Ze.OBJ=8;Ze.NULL=16;Ze.BOOL=32;Ze.NAN=64;Ze.INFINITY=128;Ze._INFINITY=256;Ze.INF=Ze.INFINITY|Ze._INFINITY;Ze.SPECIAL=Ze.NULL|Ze.BOOL|Ze.INF|Ze.NAN;Ze.ATOM=Ze.STR|Ze.NUM|Ze.SPECIAL;Ze.COLLECTION=Ze.ARR|Ze.OBJ;Ze.ALL=Ze.ATOM|Ze.COLLECTION;Ze.Allow={STR:Ze.STR,NUM:Ze.NUM,ARR:Ze.ARR,OBJ:Ze.OBJ,NULL:Ze.NULL,BOOL:Ze.BOOL,NAN:Ze.NAN,INFINITY:Ze.INFINITY,_INFINITY:Ze._INFINITY,INF:Ze.INF,SPECIAL:Ze.SPECIAL,ATOM:Ze.ATOM,COLLECTION:Ze.COLLECTION,ALL:Ze.ALL};Ze.default=Ze.Allow});var Ui=Tg(Dr=>{"use strict";var rw=Dr&&Dr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),nw=Dr&&Dr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&rw(e,t,r)};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.Allow=Dr.MalformedJSON=Dr.PartialJSON=Dr.parseJSON=Dr.parse=void 0;var Zr=Id();Object.defineProperty(Dr,"Allow",{enumerable:!0,get:function(){return Zr.Allow}});nw(Id(),Dr);var Fi=class extends Error{};Dr.PartialJSON=Fi;var $i=class extends Error{};Dr.MalformedJSON=$i;function Ph(t,e=Zr.Allow.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return ow(t.trim(),e)}Dr.parseJSON=Ph;var ow=(t,e)=>{let r=t.length,n=0,o=u=>{throw new Fi(`${u} at position ${n}`)},s=u=>{throw new $i(`${u} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?d():t[n]==="["?l():t.substring(n,n+4)==="null"||Zr.Allow.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||Zr.Allow.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||Zr.Allow.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||Zr.Allow.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||Zr.Allow._INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||Zr.Allow.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):p()),i=()=>{let u=n,f=!1;for(n++;n<r&&(t[n]!=='"'||f&&t[n-1]==="\\");)f=t[n]==="\\"?!f:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(u,++n-Number(f)))}catch(y){s(String(y))}else if(Zr.Allow.STR&e)try{return JSON.parse(t.substring(u,n-Number(f))+'"')}catch{return JSON.parse(t.substring(u,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,m();let u={};try{for(;t[n]!=="}";){if(m(),n>=r&&Zr.Allow.OBJ&e)return u;let f=i();m(),n++;try{let y=a();u[f]=y}catch(y){if(Zr.Allow.OBJ&e)return u;throw y}m(),t[n]===","&&n++}}catch{if(Zr.Allow.OBJ&e)return u;o("Expected '}' at end of object")}return n++,u},l=()=>{n++;let u=[];try{for(;t[n]!=="]";)u.push(a()),m(),t[n]===","&&n++}catch{if(Zr.Allow.ARR&e)return u;o("Expected ']' at end of array")}return n++,u},p=()=>{if(n===0){t==="-"&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(Zr.Allow.NUM&e)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(f))}}let u=n;for(t[n]==="-"&&n++;t[n]&&",]}".indexOf(t[n])===-1;)n++;n==r&&!(Zr.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(u,n))}catch{t.substring(u,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(t.substring(u,t.lastIndexOf("e")))}catch(y){s(String(y))}}},m=()=>{for(;n<r&&`
|
|
5
|
-
\r `.includes(t[n]);)n++};return a()},
|
|
4
|
+
- `)}`,new Error(pe)}let Ae=`${i}/$ref`,fe=ur(t,Re,r,n,o,s,a,Ae,d);if(fe.valid||Z.push({instanceLocation:a,keyword:"$ref",keywordLocation:Ae,error:"A subschema had errors."},...fe.errors),r==="4"||r==="7")return{valid:Z.length===0,errors:Z}}if(Array.isArray(x)){let z=x.length,Re=!1;for(let Ae=0;Ae<z;Ae++)if(p===x[Ae]||x[Ae]==="integer"&&p==="number"&&t%1===0&&t===t){Re=!0;break}Re||Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x.join('", "')}".`})}else x==="integer"?(p!=="number"||t%1||t!==t)&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x}".`}):x!==void 0&&p!==x&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x}".`});if(C!==void 0&&(p==="object"||p==="array"?La(t,C)||Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`}):t!==C&&Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`})),S!==void 0&&(p==="object"||p==="array"?S.some(z=>La(t,z))||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(z=>t===z)||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),T!==void 0){let z=`${i}/not`;ur(t,T,r,n,o,s,a,z).valid&&Z.push({instanceLocation:a,keyword:"not",keywordLocation:z,error:'Instance matched "not" schema.'})}let ge=[];if(M!==void 0){let z=`${i}/anyOf`,Re=Z.length,Ae=!1;for(let fe=0;fe<M.length;fe++){let pe=M[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${z}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae||Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:z,error:"Instance does not match any subschemas."})}if(h!==void 0){let z=`${i}/allOf`,Re=Z.length,Ae=!0;for(let fe=0;fe<h.length;fe++){let pe=h[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${z}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae&&Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"allOf",keywordLocation:z,error:"Instance does not match every subschema."})}if(w!==void 0){let z=`${i}/oneOf`,Re=Z.length,Ae=w.filter((fe,pe)=>{let Be=Object.create(d),Q=ur(t,fe,r,n,o,f===!0?s:null,a,`${z}/${pe}`,Be);return Z.push(...Q.errors),Q.valid&&ge.push(Be),Q.valid}).length;Ae===1?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:z,error:`Instance does not match exactly one subschema (${Ae} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...ge),y!==void 0){let z=`${i}/if`;if(ur(t,y,r,n,o,s,a,z,d).valid){if(E!==void 0){let Ae=ur(t,E,r,n,o,s,a,`${i}/then`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "then" schema.'},...Ae.errors)}}else if(B!==void 0){let Ae=ur(t,B,r,n,o,s,a,`${i}/else`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "else" schema.'},...Ae.errors)}}if(p==="object"){if(k!==void 0)for(let fe of k)fe in t||Z.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${fe}".`});let z=Object.keys(t);if(be!==void 0&&z.length<be&&Z.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${be} properties.`}),Ye!==void 0&&z.length>Ye&&Z.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Ye} properties.`}),Ge!==void 0){let fe=`${i}/propertyNames`;for(let pe in t){let Be=`${a}/${xn(pe)}`,Q=ur(pe,Ge,r,n,o,s,Be,fe);Q.valid||Z.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:fe,error:`Property name "${pe}" does not match schema.`},...Q.errors)}}if(ve!==void 0){let fe=`${i}/dependantRequired`;for(let pe in ve)if(pe in t){let Be=ve[pe];for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`})}}if(Ee!==void 0)for(let fe in Ee){let pe=`${i}/dependentSchemas`;if(fe in t){let Be=ur(t,Ee[fe],r,n,o,s,a,`${pe}/${xn(fe)}`,d);Be.valid||Z.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:pe,error:`Instance has "${fe}" but does not match dependant schema.`},...Be.errors)}}if(Ke!==void 0){let fe=`${i}/dependencies`;for(let pe in Ke)if(pe in t){let Be=Ke[pe];if(Array.isArray(Be))for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`});else{let Q=ur(t,Be,r,n,o,s,a,`${fe}/${xn(pe)}`);Q.valid||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not match dependant schema.`},...Q.errors)}}}let Re=Object.create(null),Ae=!1;if(R!==void 0){let fe=`${i}/properties`;for(let pe in R){if(!(pe in t))continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],R[pe],r,n,o,s,Be,`${fe}/${xn(pe)}`);if(Q.valid)d[pe]=Re[pe]=!0;else if(Ae=o,Z.push({instanceLocation:a,keyword:"properties",keywordLocation:fe,error:`Property "${pe}" does not match schema.`},...Q.errors),Ae)break}}if(!Ae&&O!==void 0){let fe=`${i}/patternProperties`;for(let pe in O){let Be=new RegExp(pe,"u"),Q=O[pe];for(let _ in t){if(!Be.test(_))continue;let ke=`${a}/${xn(_)}`,He=ur(t[_],Q,r,n,o,s,ke,`${fe}/${xn(pe)}`);He.valid?d[_]=Re[_]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:fe,error:`Property "${_}" matches pattern "${pe}" but does not match associated schema.`},...He.errors))}}}if(!Ae&&V!==void 0){let fe=`${i}/additionalProperties`;for(let pe in t){if(Re[pe])continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],V,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:fe,error:`Property "${pe}" does not match additional properties schema.`},...Q.errors))}}else if(!Ae&&ne!==void 0){let fe=`${i}/unevaluatedProperties`;for(let pe in t)if(!d[pe]){let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],ne,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:Z.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:fe,error:`Property "${pe}" does not match unevaluated properties schema.`},...Q.errors)}}}else if(p==="array"){Xe!==void 0&&t.length>Xe&&Z.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${t.length} > ${Xe}).`}),Me!==void 0&&t.length<Me&&Z.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${t.length} < ${Me}).`});let z=t.length,Re=0,Ae=!1;if(Ne!==void 0){let fe=`${i}/prefixItems`,pe=Math.min(Ne.length,z);for(;Re<pe;Re++){let Be=ur(t[Re],Ne[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}if(X!==void 0){let fe=`${i}/items`;if(Array.isArray(X)){let pe=Math.min(X.length,z);for(;Re<pe;Re++){let Be=ur(t[Re],X[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}else for(;Re<z;Re++){let pe=ur(t[Re],X,r,n,o,s,`${a}/${Re}`,fe);if(d[Re]=!0,!pe.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...pe.errors),Ae))break}if(!Ae&&Ue!==void 0){let pe=`${i}/additionalItems`;for(;Re<z;Re++){let Be=ur(t[Re],Ue,r,n,o,s,`${a}/${Re}`,pe);d[Re]=!0,Be.valid||(Ae=o,Z.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:pe,error:"Items did not match additional items schema."},...Be.errors))}}}if(Te!==void 0)if(z===0&&oe===void 0)Z.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(oe!==void 0&&z<oe)Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${z}) than minContains (${oe}).`});else{let fe=`${i}/contains`,pe=Z.length,Be=0;for(let Q=0;Q<z;Q++){let _=ur(t[Q],Te,r,n,o,s,`${a}/${Q}`,fe);_.valid?(d[Q]=!0,Be++):Z.push(..._.errors)}Be>=(oe||0)&&(Z.length=pe),oe===void 0&&xe===void 0&&Be===0?Z.splice(pe,0,{instanceLocation:a,keyword:"contains",keywordLocation:fe,error:"Array does not contain item matching schema."}):oe!==void 0&&Be<oe?Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${oe} items matching schema. Only ${Be} items were found.`}):xe!==void 0&&Be>xe&&Z.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${xe} items matching schema. ${Be} items were found.`})}if(!Ae&&K!==void 0){let fe=`${i}/unevaluatedItems`;for(Re;Re<z;Re++){if(d[Re])continue;let pe=ur(t[Re],K,r,n,o,s,`${a}/${Re}`,fe);d[Re]=!0,pe.valid||Z.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:fe,error:"Items did not match unevaluated items schema."},...pe.errors)}}if(ce)for(let fe=0;fe<z;fe++){let pe=t[fe],Be=typeof pe=="object"&&pe!==null;for(let Q=0;Q<z;Q++){if(fe===Q)continue;let _=t[Q];(pe===_||Be&&(typeof _=="object"&&_!==null)&&La(pe,_))&&(Z.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${fe} and ${Q}.`}),fe=Number.MAX_SAFE_INTEGER,Q=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(te!==void 0&&(ut===!0&&t<=te||t<te)&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${ut?"or equal to ":""} ${te}.`}),le!==void 0&&(Ce===!0&&t>=le||t>le)&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${Ce?"or equal to ":""} ${le}.`})):(te!==void 0&&t<te&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${te}.`}),le!==void 0&&t>le&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${le}.`}),ut!==void 0&&t<=ut&&Z.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${t} is less than ${ut}.`}),Ce!==void 0&&t>=Ce&&Z.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ce}.`})),he!==void 0){let z=t%he;Math.abs(0-z)>=11920929e-14&&Math.abs(he-z)>=11920929e-14&&Z.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${t} is not a multiple of ${he}.`})}}else if(p==="string"){let z=rt===void 0&&_e===void 0?0:mh(t);rt!==void 0&&z<rt&&Z.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${z} < ${rt}).`}),_e!==void 0&&z>_e&&Z.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${z} > ${_e}).`}),me!==void 0&&!new RegExp(me,"u").test(t)&&Z.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),P!==void 0&&Td[P]&&!Td[P](t)&&Z.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${P}".`})}return{valid:Z.length===0,errors:Z}}var Ed=Gn(()=>{"use strict";Sd();Bi();Md();Wi();kd()});var Hi,gh=Gn(()=>{"use strict";Bi();Ed();Hi=class{constructor(e,r="2019-09",n=!0){Ht(this,"schema");Ht(this,"draft");Ht(this,"shortCircuit");Ht(this,"lookup");this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=uo(e)}validate(e){return ur(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),uo(e,this.lookup)}}});var hh=Gn(()=>{"use strict";Sd();Bi();Md();Wi();fh();kd();Ed();gh()});var kh={};kg(kh,{cleanupWebMCPPolyfill:()=>Mh,initializeWebMCPPolyfill:()=>Th,initializeWebModelContextPolyfill:()=>Th,isPlainObject:()=>Hr,validateArgsWithSchema:()=>Ch});function Jn(t){try{return new DOMException(t,"UnknownError")}catch{let e=new Error(t);return e.name="UnknownError",e}}function P0(t){let e;try{e=JSON.parse(t)}catch{throw Jn(xh)}if(!e||typeof e!="object"||Array.isArray(e))throw Jn(xh);return e}function I0(t){if(typeof t=="string")return t;if(Hr(t)&&typeof t.name=="string")return t.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function Hr(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function wh(t){if(!Hr(t))return null;let e=t["~standard"];return Hr(e)?e:null}function R0(t){let e=wh(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function W0(t){let e=wh(t);return!e||e.version!==1||!Hr(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function Oi(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!Hr(e))return{issues:[{message:"expected object arguments"}]};let r=Ch(e,t);return r?{issues:[r]}:{value:e}}}}}function B0(t){for(let e of M0)try{let r=t["~standard"].jsonSchema.input({target:e});return vh(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function H0(t){if(t===void 0){let r=Di;return{inputSchema:r,standardValidator:Oi(r)}}if(W0(t)){let r=B0(t);return{inputSchema:r,standardValidator:Oi(r)}}if(R0(t))return{inputSchema:Di,standardValidator:t};if(vh(t),Object.keys(t).length===0)return{inputSchema:Di,standardValidator:Oi(Di)};let e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:Oi(e)}}function vh(t){if(!Hr(t))throw new Error("inputSchema must be a JSON Schema object");Pa(t,"$")}function Pa(t,e){let r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);let n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);let o=t.properties;if(o!==void 0){if(!Hr(o))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.properties.${i}: expected object schema`);Pa(d,`${e}.properties.${i}`)}}let s=t.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.items[${i}]: expected object schema`);Pa(d,`${e}.items[${i}]`)}else if(Hr(s))Pa(s,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(let i of["allOf","anyOf","oneOf"]){let d=t[i];if(d!==void 0){if(!Array.isArray(d))throw new Error(`Invalid JSON Schema at ${e}: "${i}" must be an array`);for(let[l,p]of d.entries()){if(!Hr(p))throw new Error(`Invalid JSON Schema at ${e}.${i}[${l}]: expected object schema`);Pa(p,`${e}.${i}[${l}]`)}}}let a=t.not;if(a!==void 0){if(!Hr(a))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);Pa(a,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function D0(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);let r=H0(t.inputSchema),n=t.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...o?{annotations:o}:{},inputSchema:r.inputSchema,[bh]:r.standardValidator}}function Ch(t,e){let r=new Hi(e,"2020-12",!0).validate(t);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function O0(t){if(!t||t.length===0)return null;let e=t.map(r=>Hr(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function N0(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(s){let a=s instanceof Error?`: ${s.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",s),`Input validation error: schema validation failed${a}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let o=O0(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function _0(t,e){return N0(t,e[bh])}function F0(t){return Hr(t)&&Array.isArray(t.content)}function $0(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Pd(t){return $0(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>Pd(e)):Hr(t)?Object.values(t).every(e=>Pd(e)):!1}function U0(t){if(!(!Hr(t)||!Pd(t)))return t}function q0(t){var e;if(typeof t=="string")return t;try{return(e=JSON.stringify(t))!=null?e:String(t)}catch{return String(t)}}function z0(t){if(F0(t))return t;let e=U0(t);return{content:[{type:"text",text:q0(t)}],...e?{structuredContent:e}:{},isError:!1}}function V0(t){var e;for(let r of(e=t.content)!=null?e:[])if(r.type==="text"&&"text"in r&&typeof r.text=="string")return r.text;return null}function j0(t){var r;if(t.isError)throw Jn(((r=V0(t))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||Ni);let e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw Jn(Ni)}}function G0(t,e){return e?e.aborted?Promise.reject(Jn(Ld)):new Promise((r,n)=>{let o=()=>{s(),n(Jn(Ld))},s=()=>{e.removeEventListener("abort",o)};e.addEventListener("abort",o,{once:!0}),t.then(a=>{s(),r(a)},a=>{s(),n(a)})}):t}function Ah(){return typeof navigator!="undefined"?navigator:null}function Sh(){return typeof document!="undefined"?document:null}function K0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function yh(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}function X0(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return _i||(_i=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),e}})}function Th(t){var d;let e=Ah(),r=Sh();if(!e&&!r||(r==null?void 0:r.modelContext))return;let o=e==null?void 0:e.modelContext,s=!!o;if(lr.installed&&Mh(),r&&o){lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),yh(r,o),lr.installedDocumentModelContext=!0,lr.installed=!0;return}if(s)return;let a=new E0,i=a;if(i[k0]=!0,r&&(lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),yh(r,i),lr.installedDocumentModelContext=!0),e){lr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),lr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),_i=!1,X0(e,i),lr.installedNavigatorModelContext=!0;let l=(d=t==null?void 0:t.installTestingShim)!=null?d:"if-missing",p=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!p)&&(K0(e,"modelContextTesting",a.getTestingShim()),lr.installedNavigatorModelContextTesting=!0)}lr.installed=!0}function Mh(){if(!lr.installed)return;let t=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},e=Ah(),r=Sh();r&&lr.installedDocumentModelContext&&t(r,"modelContext",lr.previousDocumentModelContextDescriptor),e&&lr.installedNavigatorModelContext&&t(e,"modelContext",lr.previousNavigatorModelContextDescriptor),e&&lr.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",lr.previousNavigatorModelContextTestingDescriptor),lr.installed=!1,lr.previousDocumentModelContextDescriptor=void 0,lr.previousNavigatorModelContextDescriptor=void 0,lr.previousNavigatorModelContextTestingDescriptor=void 0,lr.installedDocumentModelContext=!1,lr.installedNavigatorModelContext=!1,lr.installedNavigatorModelContextTesting=!1,_i=!1}var xh,Ni,Ld,Di,M0,k0,bh,lr,E0,L0,_i,Eh=Gn(()=>{"use strict";hh();xh="Failed to parse input arguments",Ni="Tool was executed but the invocation failed. For example, the script function threw an error",Ld="Tool was cancelled",Di={type:"object",properties:{}},M0=["draft-2020-12","draft-07"],k0="__isWebMCPPolyfill",bh=Symbol("standardValidator"),lr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},E0=class extends EventTarget{constructor(){super(...arguments);Ht(this,"tools",new Map);Ht(this,"testingShim",null);Ht(this,"_ontoolchange",null);Ht(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,r){var s;let n=r==null?void 0:r.signal;if(n!=null&&n.aborted){console.warn(`[WebMCPPolyfill] registerTool("${(s=e==null?void 0:e.name)!=null?s:"<unknown>"}") skipped: options.signal was already aborted.`);return}let o=D0(e,this.tools);this.tools.set(o.name,o),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(o.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let r=I0(e);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,r,n){return this.executeToolByName(e.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new L0(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{var n;let r;try{r=JSON.stringify((n=e.inputSchema)!=null?n:{type:"object"})}catch{r='{"type":"object"}'}return{name:e.name,description:e.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{var n,o,s;let r=this.tools.get(e.name);return{...e,title:(n=r==null?void 0:r.title)!=null?n:"",origin:(s=(o=globalThis.location)==null?void 0:o.origin)!=null?s:"",window:globalThis.window}})}async executeToolForTesting(e,r,n){return this.executeToolByName(e,r,n,!0)}async executeToolByName(e,r,n,o){var p;if((p=n==null?void 0:n.signal)!=null&&p.aborted)throw Jn(Ld);let s=this.tools.get(e);if(!s)throw Jn(`Tool not found: ${e}`);let a=P0(r),i=await _0(a,s);if(i)throw Jn(i);let d=!0,l={requestUserInteraction:async m=>{if(!d)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof m!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return m()}};try{let m=s.execute(a,l),u=await G0(Promise.resolve(m),n==null?void 0:n.signal);if(o)return j0(z0(u));let f=JSON.stringify(u);return f===void 0?null:f}catch(m){throw Jn(m instanceof Error?`${Ni}: ${m.message}`:Ni)}finally{d=!1}}notifyToolsChanged(){queueMicrotask(()=>{var r,n;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(o){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",o)}this.dispatchEvent(e),(n=this.testingShim)==null||n.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},L0=class extends EventTarget{constructor(e){super();Ht(this,"context");Ht(this,"_ontoolchange",null);this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,r,n){return this.context.executeToolForTesting(e,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",e)}dispatchToolChange(){var r;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(n){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",n)}this.dispatchEvent(e),this.dispatchEvent(new Event("toolschanged"))}};_i=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let t=window.__webMCPPolyfillOptions;if((t==null?void 0:t.autoInitialize)!==!1)try{Th(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}});var Rd=Mg(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.Allow=et.ALL=et.COLLECTION=et.ATOM=et.SPECIAL=et.INF=et._INFINITY=et.INFINITY=et.NAN=et.BOOL=et.NULL=et.OBJ=et.ARR=et.NUM=et.STR=void 0;et.STR=1;et.NUM=2;et.ARR=4;et.OBJ=8;et.NULL=16;et.BOOL=32;et.NAN=64;et.INFINITY=128;et._INFINITY=256;et.INF=et.INFINITY|et._INFINITY;et.SPECIAL=et.NULL|et.BOOL|et.INF|et.NAN;et.ATOM=et.STR|et.NUM|et.SPECIAL;et.COLLECTION=et.ARR|et.OBJ;et.ALL=et.ATOM|et.COLLECTION;et.Allow={STR:et.STR,NUM:et.NUM,ARR:et.ARR,OBJ:et.OBJ,NULL:et.NULL,BOOL:et.BOOL,NAN:et.NAN,INFINITY:et.INFINITY,_INFINITY:et._INFINITY,INF:et.INF,SPECIAL:et.SPECIAL,ATOM:et.ATOM,COLLECTION:et.COLLECTION,ALL:et.ALL};et.default=et.Allow});var qi=Mg(Dr=>{"use strict";var ow=Dr&&Dr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),aw=Dr&&Dr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ow(e,t,r)};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.Allow=Dr.MalformedJSON=Dr.PartialJSON=Dr.parseJSON=Dr.parse=void 0;var Zr=Rd();Object.defineProperty(Dr,"Allow",{enumerable:!0,get:function(){return Zr.Allow}});aw(Rd(),Dr);var $i=class extends Error{};Dr.PartialJSON=$i;var Ui=class extends Error{};Dr.MalformedJSON=Ui;function Ih(t,e=Zr.Allow.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return sw(t.trim(),e)}Dr.parseJSON=Ih;var sw=(t,e)=>{let r=t.length,n=0,o=u=>{throw new $i(`${u} at position ${n}`)},s=u=>{throw new Ui(`${u} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?d():t[n]==="["?l():t.substring(n,n+4)==="null"||Zr.Allow.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||Zr.Allow.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||Zr.Allow.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||Zr.Allow.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||Zr.Allow._INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||Zr.Allow.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):p()),i=()=>{let u=n,f=!1;for(n++;n<r&&(t[n]!=='"'||f&&t[n-1]==="\\");)f=t[n]==="\\"?!f:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(u,++n-Number(f)))}catch(x){s(String(x))}else if(Zr.Allow.STR&e)try{return JSON.parse(t.substring(u,n-Number(f))+'"')}catch{return JSON.parse(t.substring(u,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,m();let u={};try{for(;t[n]!=="}";){if(m(),n>=r&&Zr.Allow.OBJ&e)return u;let f=i();m(),n++;try{let x=a();u[f]=x}catch(x){if(Zr.Allow.OBJ&e)return u;throw x}m(),t[n]===","&&n++}}catch{if(Zr.Allow.OBJ&e)return u;o("Expected '}' at end of object")}return n++,u},l=()=>{n++;let u=[];try{for(;t[n]!=="]";)u.push(a()),m(),t[n]===","&&n++}catch{if(Zr.Allow.ARR&e)return u;o("Expected ']' at end of array")}return n++,u},p=()=>{if(n===0){t==="-"&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(Zr.Allow.NUM&e)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(f))}}let u=n;for(t[n]==="-"&&n++;t[n]&&",]}".indexOf(t[n])===-1;)n++;n==r&&!(Zr.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(u,n))}catch{t.substring(u,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(t.substring(u,t.lastIndexOf("e")))}catch(x){s(String(x))}}},m=()=>{for(;n<r&&`
|
|
5
|
+
\r `.includes(t[n]);)n++};return a()},iw=Ih;Dr.parse=iw});var oA={};kg(oA,{ASK_USER_QUESTION_TOOL_NAME:()=>Yp,AgentWidgetClient:()=>sa,AgentWidgetSession:()=>Ba,AttachmentManager:()=>ca,DEFAULT_COMPONENTS:()=>Rp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>hl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>yn,DEFAULT_PALETTE:()=>Pp,DEFAULT_SEMANTIC:()=>Ip,DEFAULT_WIDGET_CONFIG:()=>er,PRESETS:()=>Tu,PRESET_FULLSCREEN:()=>Su,PRESET_MINIMAL:()=>Au,PRESET_SHOP:()=>Cu,THEME_ZONES:()=>Zh,VERSION:()=>vy,WEBMCP_TOOL_PREFIX:()=>Ls,WebMcpBridge:()=>Ia,accessibilityPlugin:()=>Cy,animationsPlugin:()=>Ay,applyThemeVariables:()=>Ro,attachHeaderToContainer:()=>ua,brandPlugin:()=>Sy,buildComposer:()=>_a,buildDefaultHeader:()=>Up,buildHeader:()=>go,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>qp,collectEnrichedPageContext:()=>yy,componentRegistry:()=>yo,createActionManager:()=>ei,createAgentExperience:()=>ed,createAskUserQuestionBubble:()=>Wx,createBestAvailableVoiceProvider:()=>ol,createBubbleWithLayout:()=>yx,createCSATFeedback:()=>Ql,createComboButton:()=>Rl,createComponentMiddleware:()=>Qx,createComponentStreamParser:()=>Gl,createDefaultSanitizer:()=>Ad,createDirectivePostprocessor:()=>Xg,createDropdownMenu:()=>Do,createFlexibleJsonStreamParser:()=>Bh,createIconButton:()=>Er,createImagePart:()=>$h,createJsonStreamParser:()=>Ji,createLabelButton:()=>Gs,createLocalStorageAdapter:()=>jl,createMarkdownProcessor:()=>As,createMarkdownProcessorFromConfig:()=>na,createMessageActions:()=>Kp,createNPSFeedback:()=>Yl,createPlainTextParser:()=>Ki,createPlugin:()=>ky,createRegexJsonParser:()=>Xi,createStandardBubble:()=>Fa,createTextPart:()=>Rs,createTheme:()=>Da,createThemeObserver:()=>wl,createToggleGroup:()=>px,createTypingIndicator:()=>fa,createVoiceProvider:()=>da,createWidgetHostLayout:()=>ti,createXmlParser:()=>Qi,defaultActionHandlers:()=>ha,defaultJsonActionParser:()=>Zs,defaultParseRules:()=>wu,detectColorScheme:()=>Os,directivePostprocessor:()=>Jg,ensureAskUserQuestionSheet:()=>Va,escapeHtml:()=>oa,extractComponentDirectiveFromMessage:()=>Jl,fileToImagePart:()=>Uh,formatEnrichedContext:()=>by,generateAssistantMessageId:()=>ia,generateMessageId:()=>Dh,generateStableSelector:()=>vu,generateUserMessageId:()=>Wa,getActiveTheme:()=>Oa,getColorScheme:()=>Bp,getDisplayText:()=>Nh,getHeaderLayout:()=>zp,getImageParts:()=>Fh,getPreset:()=>Ly,hasComponentDirective:()=>Xl,hasImages:()=>_h,headerLayouts:()=>Wl,highContrastPlugin:()=>My,initAgentWidget:()=>iy,isAskUserQuestionMessage:()=>ho,isComponentDirectiveType:()=>Jx,isDockedMountMode:()=>Ar,isVoiceSupported:()=>Bs,isWebMcpToolName:()=>Io,listRegisteredStreamAnimations:()=>Np,markdownPostprocessor:()=>md,mergeWithDefaults:()=>xl,normalizeContent:()=>Oh,parseAskUserQuestionPayload:()=>xo,pluginRegistry:()=>Ys,reducedMotionPlugin:()=>Ty,registerStreamAnimationPlugin:()=>pa,removeAskUserQuestionSheet:()=>_o,renderComponentDirective:()=>Kl,renderLoadingIndicatorWithFallback:()=>Gp,renderLucideIcon:()=>Ie,resolveDockConfig:()=>kn,resolveSanitizer:()=>Ea,resolveTokens:()=>yl,stripWebMcpPrefix:()=>Id,themeToCssVariables:()=>bl,unregisterStreamAnimationPlugin:()=>Op,validateImageFile:()=>qh,validateTheme:()=>Wp});function ld(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ra=ld();function Hg(t){ra=t}var Dg=/[&<>"']/,Gy=new RegExp(Dg.source,"g"),Og=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Ky=new RegExp(Og.source,"g"),Xy={"&":"&","<":"<",">":">",'"':""","'":"'"},Pg=t=>Xy[t];function gn(t,e){if(e){if(Dg.test(t))return t.replace(Gy,Pg)}else if(Og.test(t))return t.replace(Ky,Pg);return t}var Jy=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Qy(t){return t.replace(Jy,(e,r)=>(r=r.toLowerCase(),r==="colon"?":":r.charAt(0)==="#"?r.charAt(1)==="x"?String.fromCharCode(parseInt(r.substring(2),16)):String.fromCharCode(+r.substring(1)):""))}var Yy=/(^|[^\[])\^/g;function or(t,e){let r=typeof t=="string"?t:t.source;e=e||"";let n={replace:(o,s)=>{let a=typeof s=="string"?s:s.source;return a=a.replace(Yy,"$1"),r=r.replace(o,a),n},getRegex:()=>new RegExp(r,e)};return n}function Ig(t){try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}var ys={exec:()=>null};function Rg(t,e){let r=t.replace(/\|/g,(s,a,i)=>{let d=!1,l=a;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=r.split(/ \|/),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function Ti(t,e,r){let n=t.length;if(n===0)return"";let o=0;for(;o<n;){let s=t.charAt(n-o-1);if(s===e&&!r)o++;else if(s!==e&&r)o++;else break}return t.slice(0,n-o)}function Zy(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let n=0;n<t.length;n++)if(t[n]==="\\")n++;else if(t[n]===e[0])r++;else if(t[n]===e[1]&&(r--,r<0))return n;return-1}function Wg(t,e,r,n){let o=e.href,s=e.title?gn(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");if(t[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:r,href:o,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,i}return{type:"image",raw:r,href:o,title:s,text:gn(a)}}function eb(t,e){let r=t.match(/^(\s+)(?:```)/);if(r===null)return e;let n=r[1];return e.split(`
|
|
6
6
|
`).map(o=>{let s=o.match(/^\s+/);if(s===null)return o;let[a]=s;return a.length>=n.length?o.slice(n.length):o}).join(`
|
|
7
|
-
`)}var
|
|
8
|
-
`)}}}fences(e){let r=this.rules.block.fences.exec(e);if(r){let n=r[0],o=
|
|
9
|
-
$1`);n=
|
|
7
|
+
`)}var Ma=class{constructor(e){Ht(this,"options");Ht(this,"rules");Ht(this,"lexer");this.options=e||ra}space(e){let r=this.rules.block.newline.exec(e);if(r&&r[0].length>0)return{type:"space",raw:r[0]}}code(e){let r=this.rules.block.code.exec(e);if(r){let n=r[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:r[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Ti(n,`
|
|
8
|
+
`)}}}fences(e){let r=this.rules.block.fences.exec(e);if(r){let n=r[0],o=eb(n,r[3]||"");return{type:"code",raw:n,lang:r[2]?r[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):r[2],text:o}}}heading(e){let r=this.rules.block.heading.exec(e);if(r){let n=r[2].trim();if(/#$/.test(n)){let o=Ti(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:r[0],depth:r[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let r=this.rules.block.hr.exec(e);if(r)return{type:"hr",raw:r[0]}}blockquote(e){let r=this.rules.block.blockquote.exec(e);if(r){let n=r[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
|
|
9
|
+
$1`);n=Ti(n.replace(/^ *>[ \t]?/gm,""),`
|
|
10
10
|
`);let o=this.lexer.state.top;this.lexer.state.top=!0;let s=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:r[0],tokens:s,text:n}}}list(e){let r=this.rules.block.list.exec(e);if(r){let n=r[1].trim(),o=n.length>1,s={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let a=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let p=!1;if(!(r=a.exec(e))||this.rules.block.hr.test(e))break;i=r[0],e=e.substring(i.length);let m=r[2].split(`
|
|
11
|
-
`,1)[0].replace(/^\t+/,
|
|
12
|
-
`,1)[0],f=0;this.options.pedantic?(f=2,d=m.trimStart()):(f=r[2].search(/[^ ]/),f=f>4?1:f,d=m.slice(f),f+=r[1].length);let
|
|
13
|
-
`,e=e.substring(u.length+1),p=!0),!p){let
|
|
14
|
-
`,1)[0];if(u=w,this.options.pedantic&&(u=u.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),
|
|
15
|
-
`+u.slice(f);else{if(
|
|
16
|
-
`+u}!
|
|
17
|
-
`,e=e.substring(w.length+1),m=u.slice(f)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let
|
|
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(
|
|
19
|
-
`?r[1].slice(0,-1):r[1];return{type:"paragraph",raw:r[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let r=this.rules.block.text.exec(e);if(r)return{type:"text",raw:r[0],text:r[0],tokens:this.lexer.inline(r[0])}}escape(e){let r=this.rules.inline.escape.exec(e);if(r)return{type:"escape",raw:r[0],text:gn(r[1])}}tag(e){let r=this.rules.inline.tag.exec(e);if(r)return!this.lexer.state.inLink&&/^<a /i.test(r[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(r[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:r[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:r[0]}}link(e){let r=this.rules.inline.link.exec(e);if(r){let n=r[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let a=
|
|
20
|
-
]`).replace("lheading",_g).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()}
|
|
11
|
+
`,1)[0].replace(/^\t+/,k=>" ".repeat(3*k.length)),u=e.split(`
|
|
12
|
+
`,1)[0],f=0;this.options.pedantic?(f=2,d=m.trimStart()):(f=r[2].search(/[^ ]/),f=f>4?1:f,d=m.slice(f),f+=r[1].length);let x=!1;if(!m&&/^ *$/.test(u)&&(i+=u+`
|
|
13
|
+
`,e=e.substring(u.length+1),p=!0),!p){let k=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),T=new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),M=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),h=new RegExp(`^ {0,${Math.min(3,f-1)}}#`);for(;e;){let w=e.split(`
|
|
14
|
+
`,1)[0];if(u=w,this.options.pedantic&&(u=u.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),M.test(u)||h.test(u)||k.test(u)||T.test(e))break;if(u.search(/[^ ]/)>=f||!u.trim())d+=`
|
|
15
|
+
`+u.slice(f);else{if(x||m.search(/[^ ]/)>=4||M.test(m)||h.test(m)||T.test(m))break;d+=`
|
|
16
|
+
`+u}!x&&!u.trim()&&(x=!0),i+=w+`
|
|
17
|
+
`,e=e.substring(w.length+1),m=u.slice(f)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let C=null,S;this.options.gfm&&(C=/^\[[ xX]\] /.exec(d),C&&(S=C[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!C,checked:S,loose:!1,text:d,tokens:[]}),s.raw+=i}s.items[s.items.length-1].raw=i.trimEnd(),s.items[s.items.length-1].text=d.trimEnd(),s.raw=s.raw.trimEnd();for(let p=0;p<s.items.length;p++)if(this.lexer.state.top=!1,s.items[p].tokens=this.lexer.blockTokens(s.items[p].text,[]),!s.loose){let m=s.items[p].tokens.filter(f=>f.type==="space"),u=m.length>0&&m.some(f=>/\n.*\n/.test(f.raw));s.loose=u}if(s.loose)for(let p=0;p<s.items.length;p++)s.items[p].loose=!0;return s}}html(e){let r=this.rules.block.html.exec(e);if(r)return{type:"html",block:!0,raw:r[0],pre:r[1]==="pre"||r[1]==="script"||r[1]==="style",text:r[0]}}def(e){let r=this.rules.block.def.exec(e);if(r){let n=r[1].toLowerCase().replace(/\s+/g," "),o=r[2]?r[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=r[3]?r[3].substring(1,r[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):r[3];return{type:"def",tag:n,raw:r[0],href:o,title:s}}}table(e){let r=this.rules.block.table.exec(e);if(!r||!/[:|]/.test(r[2]))return;let n=Rg(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(Rg(i,a.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return a}}lheading(e){let r=this.rules.block.lheading.exec(e);if(r)return{type:"heading",raw:r[0],depth:r[2].charAt(0)==="="?1:2,text:r[1],tokens:this.lexer.inline(r[1])}}paragraph(e){let r=this.rules.block.paragraph.exec(e);if(r){let n=r[1].charAt(r[1].length-1)===`
|
|
19
|
+
`?r[1].slice(0,-1):r[1];return{type:"paragraph",raw:r[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let r=this.rules.block.text.exec(e);if(r)return{type:"text",raw:r[0],text:r[0],tokens:this.lexer.inline(r[0])}}escape(e){let r=this.rules.inline.escape.exec(e);if(r)return{type:"escape",raw:r[0],text:gn(r[1])}}tag(e){let r=this.rules.inline.tag.exec(e);if(r)return!this.lexer.state.inLink&&/^<a /i.test(r[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(r[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:r[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:r[0]}}link(e){let r=this.rules.inline.link.exec(e);if(r){let n=r[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let a=Ti(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=Zy(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)),Wg(r,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},r[0],this.lexer)}}reflink(e,r){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(/\s+/g," "),s=r[o.toLowerCase()];if(!s){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return Wg(n,s,n[0],this.lexer)}}emStrong(e,r,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o||o[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(o[1]||o[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let a=[...o[0]].length-1,i,d,l=a,p=0,m=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,r=r.slice(-1*e.length+a);(o=m.exec(r))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&a%3&&!((a+d)%3)){p+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+p);let u=[...o[0]][0].length,f=e.slice(0,a+o.index+u+d);if(Math.min(a,d)%2){let C=f.slice(1,-1);return{type:"em",raw:f,text:C,tokens:this.lexer.inlineTokens(C)}}let x=f.slice(2,-2);return{type:"strong",raw:f,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(e){let r=this.rules.inline.code.exec(e);if(r){let n=r[2].replace(/\n/g," "),o=/[^ ]/.test(n),s=/^ /.test(n)&&/ $/.test(n);return o&&s&&(n=n.substring(1,n.length-1)),n=gn(n,!0),{type:"codespan",raw:r[0],text:n}}}br(e){let r=this.rules.inline.br.exec(e);if(r)return{type:"br",raw:r[0]}}del(e){let r=this.rules.inline.del.exec(e);if(r)return{type:"del",raw:r[0],text:r[2],tokens:this.lexer.inlineTokens(r[2])}}autolink(e){let r=this.rules.inline.autolink.exec(e);if(r){let n,o;return r[2]==="@"?(n=gn(r[1]),o="mailto:"+n):(n=gn(r[1]),o=n),{type:"link",raw:r[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,o;let r;if(r=this.rules.inline.url.exec(e)){let s,a;if(r[2]==="@")s=gn(r[0]),a="mailto:"+s;else{let i;do i=r[0],r[0]=(o=(n=this.rules.inline._backpedal.exec(r[0]))==null?void 0:n[0])!=null?o:"";while(i!==r[0]);s=gn(r[0]),r[1]==="www."?a="http://"+r[0]:a=r[0]}return{type:"link",raw:r[0],text:s,href:a,tokens:[{type:"text",raw:s,text:s}]}}}inlineText(e){let r=this.rules.inline.text.exec(e);if(r){let n;return this.lexer.state.inRawBlock?n=r[0]:n=gn(r[0]),{type:"text",raw:r[0],text:n}}}},tb=/^(?: *(?:\n|$))+/,rb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,nb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,vs=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ob=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ng=/(?:[*+-]|\d{1,9}[.)])/,_g=or(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Ng).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(),dd=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ab=/^[^\n]+/,cd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,sb=or(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",cd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ib=or(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ng).getRegex(),Ei="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",pd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,lb=or("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",pd).replace("tag",Ei).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Fg=or(dd).replace("hr",vs).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",Ei).getRegex(),db=or(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Fg).getRegex(),ud={blockquote:db,code:rb,def:sb,fences:nb,heading:ob,hr:vs,html:lb,lheading:_g,list:ib,newline:tb,paragraph:Fg,table:ys,text:ab},Bg=or("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",vs).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",Ei).getRegex(),cb={...ud,table:Bg,paragraph:or(dd).replace("hr",vs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Bg).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",Ei).getRegex()},pb={...ud,html:or(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",pd).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:ys,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:or(dd).replace("hr",vs).replace("heading",` *#{1,6} *[^
|
|
20
|
+
]`).replace("lheading",_g).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},$g=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ub=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ug=/^( {2,}|\\)\n(?!\s*$)/,fb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Cs="\\p{P}\\p{S}",mb=or(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Cs).getRegex(),gb=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,hb=or(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Cs).getRegex(),xb=or("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Cs).getRegex(),yb=or("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Cs).getRegex(),bb=or(/\\([punct])/,"gu").replace(/punct/g,Cs).getRegex(),wb=or(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),vb=or(pd).replace("(?:-->|$)","-->").getRegex(),Cb=or("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",vb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ki=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ab=or(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",ki).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),qg=or(/^!?\[(label)\]\[(ref)\]/).replace("label",ki).replace("ref",cd).getRegex(),zg=or(/^!?\[(ref)\](?:\[\])?/).replace("ref",cd).getRegex(),Sb=or("reflink|nolink(?!\\()","g").replace("reflink",qg).replace("nolink",zg).getRegex(),fd={_backpedal:ys,anyPunctuation:bb,autolink:wb,blockSkip:gb,br:Ug,code:ub,del:ys,emStrongLDelim:hb,emStrongRDelimAst:xb,emStrongRDelimUnd:yb,escape:$g,link:Ab,nolink:zg,punctuation:mb,reflink:qg,reflinkSearch:Sb,tag:Cb,text:fb,url:ys},Tb={...fd,link:or(/^!?\[(label)\]\((.*?)\)/).replace("label",ki).getRegex(),reflink:or(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ki).getRegex()},sd={...fd,escape:or($g).replace("])","~|])").getRegex(),url:or(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Mb={...sd,br:or(Ug).replace("{2,}","*").getRegex(),text:or(sd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mi={normal:ud,gfm:cb,pedantic:pb},xs={normal:fd,gfm:sd,breaks:Mb,pedantic:Tb},co=class t{constructor(e){Ht(this,"tokens");Ht(this,"options");Ht(this,"state");Ht(this,"tokenizer");Ht(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ra,this.options.tokenizer=this.options.tokenizer||new Ma,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:Mi.normal,inline:xs.normal};this.options.pedantic?(r.block=Mi.pedantic,r.inline=xs.pedantic):this.options.gfm&&(r.block=Mi.gfm,this.options.breaks?r.inline=xs.breaks:r.inline=xs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Mi,inline:xs}}static lex(e,r){return new t(r).lex(e)}static lexInline(e,r){return new t(r).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
|
|
21
21
|
`),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,s,a;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=`
|
|
22
22
|
`:r.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
23
23
|
`+n.raw,o.text+=`
|
|
@@ -27,7 +27,7 @@ Known schemas:
|
|
|
27
27
|
`+n.raw,o.text+=`
|
|
28
28
|
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n),a=s.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&o.type==="text"?(o.raw+=`
|
|
29
29
|
`+n.raw,o.text+=`
|
|
30
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){let n,o,s,a=e,i,d,l;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(p=>(n=p.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.emStrong(e,a,l)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.del(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),r.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),r.push(n);continue}if(s=e,this.options.extensions&&this.options.extensions.startInline){let p=1/0,m=e.slice(1),u;this.options.extensions.startInline.forEach(f=>{u=f.call({lexer:this},m),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(s=e.substring(0,p+1))}if(n=this.tokenizer.inlineText(s)){e=e.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=r[r.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return r}},ka=class{constructor(e){Ht(this,"options");this.options=e||
|
|
30
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){let n,o,s,a=e,i,d,l;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(p=>(n=p.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.emStrong(e,a,l)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.del(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),r.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),r.push(n);continue}if(s=e,this.options.extensions&&this.options.extensions.startInline){let p=1/0,m=e.slice(1),u;this.options.extensions.startInline.forEach(f=>{u=f.call({lexer:this},m),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(s=e.substring(0,p+1))}if(n=this.tokenizer.inlineText(s)){e=e.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=r[r.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return r}},ka=class{constructor(e){Ht(this,"options");this.options=e||ra}code(e,r,n){var s;let o=(s=(r||"").match(/^\S*/))==null?void 0:s[0];return e=e.replace(/\n$/,"")+`
|
|
31
31
|
`,o?'<pre><code class="language-'+gn(o)+'">'+(n?e:gn(e,!0))+`</code></pre>
|
|
32
32
|
`:"<pre><code>"+(n?e:gn(e,!0))+`</code></pre>
|
|
33
33
|
`}blockquote(e){return`<blockquote>
|
|
@@ -45,24 +45,24 @@ ${e}</blockquote>
|
|
|
45
45
|
`}tablerow(e){return`<tr>
|
|
46
46
|
${e}</tr>
|
|
47
47
|
`}tablecell(e,r){let n=r.header?"th":"td";return(r.align?`<${n} align="${r.align}">`:`<${n}>`)+e+`</${n}>
|
|
48
|
-
`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,r,n){let o=
|
|
49
|
-
`+(a.tokens?this.parseInline(a.tokens):a.text);n+=r?this.renderer.paragraph(i):i;continue}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,r){r=r||this.renderer;let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){n+=a||"";continue}}switch(s.type){case"escape":{let a=s;n+=r.text(a.text);break}case"html":{let a=s;n+=r.html(a.text);break}case"link":{let a=s;n+=r.link(a.href,a.title,this.parseInline(a.tokens,r));break}case"image":{let a=s;n+=r.image(a.href,a.title,a.text);break}case"strong":{let a=s;n+=r.strong(this.parseInline(a.tokens,r));break}case"em":{let a=s;n+=r.em(this.parseInline(a.tokens,r));break}case"codespan":{let a=s;n+=r.codespan(a.text);break}case"br":{n+=r.br();break}case"del":{let a=s;n+=r.del(this.parseInline(a.tokens,r));break}case"text":{let a=s;n+=r.text(a.text);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}},
|
|
50
|
-
Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+gn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var Zo=new bs;function nr(t,e){return Zo.parse(t,e)}nr.options=nr.setOptions=function(t){return Zo.setOptions(t),nr.defaults=Zo.defaults,Bg(nr.defaults),nr};nr.getDefaults=id;nr.defaults=ta;nr.use=function(...t){return Zo.use(...t),nr.defaults=Zo.defaults,Bg(nr.defaults),nr};nr.walkTokens=function(t,e){return Zo.walkTokens(t,e)};nr.parseInline=Zo.parseInline;nr.Parser=po;nr.parser=po.parse;nr.Renderer=ka;nr.TextRenderer=ys;nr.Lexer=co;nr.lexer=co.lex;nr.Tokenizer=Ta;nr.Hooks=Yo;nr.parse=nr;var aA=nr.options,sA=nr.setOptions,iA=nr.use,lA=nr.walkTokens,dA=nr.parseInline;var cA=po.parse,pA=co.lex;var Tb=t=>{if(t)return t},Cs=t=>{var o,s;let e=t==null?void 0:t.markedOptions,r=new bs({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=Tb(t==null?void 0:t.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},ra=t=>t?Cs({markedOptions:t.options,renderer:t.renderer}):Cs(),kb=Cs(),fd=t=>kb(t),na=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),jg=t=>t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Vg=t=>`%%FORM_PLACEHOLDER_${t}%%`,Gg=(t,e)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Vg(e.length);return e.push({token:a,type:String(s.type)}),a}}catch{return n}return n}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let s=Vg(e.length);return e.push({token:s,type:o}),s}),r},Kg=t=>{let e=ra(t);return r=>{let n=[],o=Gg(r,n),s=e(o);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${jg(i)}"></div>`;s=s.replace(d,p)}),s}},Xg=t=>{let e=[],r=Gg(t,e),n=fd(r);return e.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${jg(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:oh,setPrototypeOf:Jg,isFrozen:Mb,getPrototypeOf:Eb,getOwnPropertyDescriptor:Lb}=Object,{freeze:Qr,seal:kn,create:Pi}=Object,{apply:wd,construct:vd}=typeof Reflect!="undefined"&&Reflect;Qr||(Qr=function(e){return e});kn||(kn=function(e){return e});wd||(wd=function(e,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return e.apply(r,o)});vd||(vd=function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return new e(...n)});var Ei=Yr(Array.prototype.forEach),Pb=Yr(Array.prototype.lastIndexOf),Qg=Yr(Array.prototype.pop),As=Yr(Array.prototype.push),Ib=Yr(Array.prototype.splice),Ii=Yr(String.prototype.toLowerCase),md=Yr(String.prototype.toString),gd=Yr(String.prototype.match),Ss=Yr(String.prototype.replace),Rb=Yr(String.prototype.indexOf),Wb=Yr(String.prototype.trim),hn=Yr(Object.prototype.hasOwnProperty),Jr=Yr(RegExp.prototype.test),Ts=Bb(TypeError);function Yr(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return wd(t,e,n)}}function Bb(t){return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return vd(t,r)}}function It(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ii;Jg&&Jg(t,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let s=r(o);s!==o&&(Mb(e)||(e[n]=s),o=s)}t[o]=!0}return t}function Hb(t){for(let e=0;e<t.length;e++)hn(t,e)||(t[e]=null);return t}function Kn(t){let e=Pi(null);for(let[r,n]of oh(t))hn(t,r)&&(Array.isArray(n)?e[r]=Hb(n):n&&typeof n=="object"&&n.constructor===Object?e[r]=Kn(n):e[r]=n);return e}function ks(t,e){for(;t!==null;){let n=Lb(t,e);if(n){if(n.get)return Yr(n.get);if(typeof n.value=="function")return Yr(n.value)}t=Eb(t)}function r(){return null}return r}var Yg=Qr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),hd=Qr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),xd=Qr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Db=Qr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),yd=Qr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Ob=Qr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Zg=Qr(["#text"]),eh=Qr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),bd=Qr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),th=Qr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Li=Qr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_b=kn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Nb=kn(/<%[\w\W]*|[\w\W]*%>/gm),Fb=kn(/\$\{[\w\W]*/gm),$b=kn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ub=kn(/^aria-[\-\w]+$/),ah=kn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),qb=kn(/^(?:\w+script|data):/i),zb=kn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),sh=kn(/^html$/i),Vb=kn(/^[a-z][.\w]*(-[.\w]+)+$/i),rh=Object.freeze({__proto__:null,ARIA_ATTR:Ub,ATTR_WHITESPACE:zb,CUSTOM_ELEMENT:Vb,DATA_ATTR:$b,DOCTYPE_NAME:sh,ERB_EXPR:Nb,IS_ALLOWED_URI:ah,IS_SCRIPT_OR_DATA:qb,MUSTACHE_EXPR:_b,TMPLIT_EXPR:Fb}),Ms={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},jb=function(){return typeof window=="undefined"?null:window},Gb=function(e,r){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(n=r.getAttribute(o));let s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},nh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ih(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jb(),e=ue=>ih(ue);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Ms.document||!t.Element)return e.isSupported=!1,e;let{document:r}=t,n=r,o=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:u,trustedTypes:f}=t,y=d.prototype,A=ks(y,"cloneNode"),S=ks(y,"remove"),M=ks(y,"nextSibling"),k=ks(y,"childNodes"),E=ks(y,"parentNode");if(typeof a=="function"){let ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let h,w="",{implementation:x,createNodeIterator:T,createDocumentFragment:W,getElementsByTagName:R}=r,{importNode:B}=n,_=nh();e.isSupported=typeof oh=="function"&&typeof E=="function"&&x&&x.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:oe,TMPLIT_EXPR:be,DATA_ATTR:Qe,ARIA_ATTR:je,IS_SCRIPT_OR_DATA:ve,ATTR_WHITESPACE:Ee,CUSTOM_ELEMENT:Ge}=rh,{IS_ALLOWED_URI:_e}=rh,X=null,Ue=It({},[...Yg,...hd,...xd,...yd,...Zg]),K=null,Te=It({},[...eh,...bd,...th,...Li]),ae=Object.seal(Pi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),xe=null,ke=null,Ke=Object.seal(Pi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ce=!0,re=!0,le=!1,ut=!0,Ce=!1,he=!0,tt=!1,Ne=!1,me=!1,J=!1,ze=!1,Z=!1,ge=!0,z=!1,Re="user-content-",Ae=!0,fe=!1,pe={},Be=null,Q=It({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),N=null,Me=It({},["audio","video","img","source","image","track"]),He=null,Ve=It({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Xe="http://www.w3.org/1998/Math/MathML",gt="http://www.w3.org/2000/svg",ot="http://www.w3.org/1999/xhtml",kt=ot,Xt=!1,G=null,Jt=It({},[Xe,gt,ot],md),at=It({},["mi","mo","mn","ms","mtext"]),Nt=It({},["annotation-xml"]),de=It({},["title","style","font","a","script"]),ye=null,Rt=["application/xhtml+xml","text/html"],ar="text/html",Mt=null,mr=null,Ot=r.createElement("form"),Wt=function(P){return P instanceof RegExp||P instanceof Function},St=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(mr&&mr===P)){if((!P||typeof P!="object")&&(P={}),P=Kn(P),ye=Rt.indexOf(P.PARSER_MEDIA_TYPE)===-1?ar:P.PARSER_MEDIA_TYPE,Mt=ye==="application/xhtml+xml"?md:Ii,X=hn(P,"ALLOWED_TAGS")?It({},P.ALLOWED_TAGS,Mt):Ue,K=hn(P,"ALLOWED_ATTR")?It({},P.ALLOWED_ATTR,Mt):Te,G=hn(P,"ALLOWED_NAMESPACES")?It({},P.ALLOWED_NAMESPACES,md):Jt,He=hn(P,"ADD_URI_SAFE_ATTR")?It(Kn(Ve),P.ADD_URI_SAFE_ATTR,Mt):Ve,N=hn(P,"ADD_DATA_URI_TAGS")?It(Kn(Me),P.ADD_DATA_URI_TAGS,Mt):Me,Be=hn(P,"FORBID_CONTENTS")?It({},P.FORBID_CONTENTS,Mt):Q,xe=hn(P,"FORBID_TAGS")?It({},P.FORBID_TAGS,Mt):Kn({}),ke=hn(P,"FORBID_ATTR")?It({},P.FORBID_ATTR,Mt):Kn({}),pe=hn(P,"USE_PROFILES")?P.USE_PROFILES:!1,ce=P.ALLOW_ARIA_ATTR!==!1,re=P.ALLOW_DATA_ATTR!==!1,le=P.ALLOW_UNKNOWN_PROTOCOLS||!1,ut=P.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ce=P.SAFE_FOR_TEMPLATES||!1,he=P.SAFE_FOR_XML!==!1,tt=P.WHOLE_DOCUMENT||!1,J=P.RETURN_DOM||!1,ze=P.RETURN_DOM_FRAGMENT||!1,Z=P.RETURN_TRUSTED_TYPE||!1,me=P.FORCE_BODY||!1,ge=P.SANITIZE_DOM!==!1,z=P.SANITIZE_NAMED_PROPS||!1,Ae=P.KEEP_CONTENT!==!1,fe=P.IN_PLACE||!1,_e=P.ALLOWED_URI_REGEXP||ah,kt=P.NAMESPACE||ot,at=P.MATHML_TEXT_INTEGRATION_POINTS||at,Nt=P.HTML_INTEGRATION_POINTS||Nt,ae=P.CUSTOM_ELEMENT_HANDLING||{},P.CUSTOM_ELEMENT_HANDLING&&Wt(P.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ae.tagNameCheck=P.CUSTOM_ELEMENT_HANDLING.tagNameCheck),P.CUSTOM_ELEMENT_HANDLING&&Wt(P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ae.attributeNameCheck=P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),P.CUSTOM_ELEMENT_HANDLING&&typeof P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(ae.allowCustomizedBuiltInElements=P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ce&&(re=!1),ze&&(J=!0),pe&&(X=It({},Zg),K=Pi(null),pe.html===!0&&(It(X,Yg),It(K,eh)),pe.svg===!0&&(It(X,hd),It(K,bd),It(K,Li)),pe.svgFilters===!0&&(It(X,xd),It(K,bd),It(K,Li)),pe.mathMl===!0&&(It(X,yd),It(K,th),It(K,Li))),hn(P,"ADD_TAGS")||(Ke.tagCheck=null),hn(P,"ADD_ATTR")||(Ke.attributeCheck=null),P.ADD_TAGS&&(typeof P.ADD_TAGS=="function"?Ke.tagCheck=P.ADD_TAGS:(X===Ue&&(X=Kn(X)),It(X,P.ADD_TAGS,Mt))),P.ADD_ATTR&&(typeof P.ADD_ATTR=="function"?Ke.attributeCheck=P.ADD_ATTR:(K===Te&&(K=Kn(K)),It(K,P.ADD_ATTR,Mt))),P.ADD_URI_SAFE_ATTR&&It(He,P.ADD_URI_SAFE_ATTR,Mt),P.FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,P.FORBID_CONTENTS,Mt)),P.ADD_FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,P.ADD_FORBID_CONTENTS,Mt)),Ae&&(X["#text"]=!0),tt&&It(X,["html","head","body"]),X.table&&(It(X,["tbody"]),delete xe.tbody),P.TRUSTED_TYPES_POLICY){if(typeof P.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ts('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof P.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ts('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');h=P.TRUSTED_TYPES_POLICY,w=h.createHTML("")}else h===void 0&&(h=Gb(f,o)),h!==null&&typeof w=="string"&&(w=h.createHTML(""));Qr&&Qr(P),mr=P}},Et=It({},[...hd,...xd,...Db]),sr=It({},[...yd,...Ob]),ft=function(P){let ee=E(P);(!ee||!ee.tagName)&&(ee={namespaceURI:kt,tagName:"template"});let Se=Ii(P.tagName),rt=Ii(ee.tagName);return G[P.namespaceURI]?P.namespaceURI===gt?ee.namespaceURI===ot?Se==="svg":ee.namespaceURI===Xe?Se==="svg"&&(rt==="annotation-xml"||at[rt]):!!Et[Se]:P.namespaceURI===Xe?ee.namespaceURI===ot?Se==="math":ee.namespaceURI===gt?Se==="math"&&Nt[rt]:!!sr[Se]:P.namespaceURI===ot?ee.namespaceURI===gt&&!Nt[rt]||ee.namespaceURI===Xe&&!at[rt]?!1:!sr[Se]&&(de[Se]||!Et[Se]):!!(ye==="application/xhtml+xml"&&G[P.namespaceURI]):!1},dr=function(P){As(e.removed,{element:P});try{E(P).removeChild(P)}catch{S(P)}},wr=function(P,ee){try{As(e.removed,{attribute:ee.getAttributeNode(P),from:ee})}catch{As(e.removed,{attribute:null,from:ee})}if(ee.removeAttribute(P),P==="is")if(J||ze)try{dr(ee)}catch{}else try{ee.setAttribute(P,"")}catch{}},Lr=function(P){let ee=null,Se=null;if(me)P="<remove></remove>"+P;else{let Ft=gd(P,/^[\r\n\t ]+/);Se=Ft&&Ft[0]}ye==="application/xhtml+xml"&&kt===ot&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");let rt=h?h.createHTML(P):P;if(kt===ot)try{ee=new u().parseFromString(rt,ye)}catch{}if(!ee||!ee.documentElement){ee=x.createDocument(kt,"template",null);try{ee.documentElement.innerHTML=Xt?w:rt}catch{}}let Qt=ee.body||ee.documentElement;return P&&Se&&Qt.insertBefore(r.createTextNode(Se),Qt.childNodes[0]||null),kt===ot?R.call(ee,tt?"html":"body")[0]:tt?ee.documentElement:Qt},Or=function(P){return T.call(P.ownerDocument||P,P,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},xt=function(P){return P instanceof m&&(typeof P.nodeName!="string"||typeof P.textContent!="string"||typeof P.removeChild!="function"||!(P.attributes instanceof p)||typeof P.removeAttribute!="function"||typeof P.setAttribute!="function"||typeof P.namespaceURI!="string"||typeof P.insertBefore!="function"||typeof P.hasChildNodes!="function")},sn=function(P){return typeof i=="function"&&P instanceof i};function fr(ue,P,ee){Ei(ue,Se=>{Se.call(e,P,ee,mr)})}let Un=function(P){let ee=null;if(fr(_.beforeSanitizeElements,P,null),xt(P))return dr(P),!0;let Se=Mt(P.nodeName);if(fr(_.uponSanitizeElement,P,{tagName:Se,allowedTags:X}),he&&P.hasChildNodes()&&!sn(P.firstElementChild)&&Jr(/<[/\w!]/g,P.innerHTML)&&Jr(/<[/\w!]/g,P.textContent)||P.nodeType===Ms.progressingInstruction||he&&P.nodeType===Ms.comment&&Jr(/<[/\w]/g,P.data))return dr(P),!0;if(!(Ke.tagCheck instanceof Function&&Ke.tagCheck(Se))&&(!X[Se]||xe[Se])){if(!xe[Se]&&Zn(Se)&&(ae.tagNameCheck instanceof RegExp&&Jr(ae.tagNameCheck,Se)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(Se)))return!1;if(Ae&&!Be[Se]){let rt=E(P)||P.parentNode,Qt=k(P)||P.childNodes;if(Qt&&rt){let Ft=Qt.length;for(let tr=Ft-1;tr>=0;--tr){let Pr=A(Qt[tr],!0);Pr.__removalCount=(P.__removalCount||0)+1,rt.insertBefore(Pr,M(P))}}}return dr(P),!0}return P instanceof d&&!ft(P)||(Se==="noscript"||Se==="noembed"||Se==="noframes")&&Jr(/<\/no(script|embed|frames)/i,P.innerHTML)?(dr(P),!0):(Ce&&P.nodeType===Ms.text&&(ee=P.textContent,Ei([V,oe,be],rt=>{ee=Ss(ee,rt," ")}),P.textContent!==ee&&(As(e.removed,{element:P.cloneNode()}),P.textContent=ee)),fr(_.afterSanitizeElements,P,null),!1)},Rr=function(P,ee,Se){if(ke[ee]||ge&&(ee==="id"||ee==="name")&&(Se in r||Se in Ot))return!1;if(!(re&&!ke[ee]&&Jr(Qe,ee))){if(!(ce&&Jr(je,ee))){if(!(Ke.attributeCheck instanceof Function&&Ke.attributeCheck(ee,P))){if(!K[ee]||ke[ee]){if(!(Zn(P)&&(ae.tagNameCheck instanceof RegExp&&Jr(ae.tagNameCheck,P)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(P))&&(ae.attributeNameCheck instanceof RegExp&&Jr(ae.attributeNameCheck,ee)||ae.attributeNameCheck instanceof Function&&ae.attributeNameCheck(ee,P))||ee==="is"&&ae.allowCustomizedBuiltInElements&&(ae.tagNameCheck instanceof RegExp&&Jr(ae.tagNameCheck,Se)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(Se))))return!1}else if(!He[ee]){if(!Jr(_e,Ss(Se,Ee,""))){if(!((ee==="src"||ee==="xlink:href"||ee==="href")&&P!=="script"&&Rb(Se,"data:")===0&&N[P])){if(!(le&&!Jr(ve,Ss(Se,Ee,"")))){if(Se)return!1}}}}}}}return!0},Zn=function(P){return P!=="annotation-xml"&&gd(P,Ge)},Pn=function(P){fr(_.beforeSanitizeAttributes,P,null);let{attributes:ee}=P;if(!ee||xt(P))return;let Se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0},rt=ee.length;for(;rt--;){let Qt=ee[rt],{name:Ft,namespaceURI:tr,value:Pr}=Qt,_r=Mt(Ft),wn=Pr,Vt=Ft==="value"?wn:Wb(wn);if(Se.attrName=_r,Se.attrValue=Vt,Se.keepAttr=!0,Se.forceKeepAttr=void 0,fr(_.uponSanitizeAttribute,P,Se),Vt=Se.attrValue,z&&(_r==="id"||_r==="name")&&(wr(Ft,P),Vt=Re+Vt),he&&Jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){wr(Ft,P);continue}if(_r==="attributename"&&gd(Vt,"href")){wr(Ft,P);continue}if(Se.forceKeepAttr)continue;if(!Se.keepAttr){wr(Ft,P);continue}if(!ut&&Jr(/\/>/i,Vt)){wr(Ft,P);continue}Ce&&Ei([V,oe,be],Ir=>{Vt=Ss(Vt,Ir," ")});let $t=Mt(P.nodeName);if(!Rr($t,_r,Vt)){wr(Ft,P);continue}if(h&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!tr)switch(f.getAttributeType($t,_r)){case"TrustedHTML":{Vt=h.createHTML(Vt);break}case"TrustedScriptURL":{Vt=h.createScriptURL(Vt);break}}if(Vt!==wn)try{tr?P.setAttributeNS(tr,Ft,Vt):P.setAttribute(Ft,Vt),xt(P)?dr(P):Qg(e.removed)}catch{wr(Ft,P)}}fr(_.afterSanitizeAttributes,P,null)},In=function ue(P){let ee=null,Se=Or(P);for(fr(_.beforeSanitizeShadowDOM,P,null);ee=Se.nextNode();)fr(_.uponSanitizeShadowNode,ee,null),Un(ee),Pn(ee),ee.content instanceof s&&ue(ee.content);fr(_.afterSanitizeShadowDOM,P,null)};return e.sanitize=function(ue){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ee=null,Se=null,rt=null,Qt=null;if(Xt=!ue,Xt&&(ue="<!-->"),typeof ue!="string"&&!sn(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw Ts("dirty is not a string, aborting")}else throw Ts("toString is not a function");if(!e.isSupported)return ue;if(Ne||St(P),e.removed=[],typeof ue=="string"&&(fe=!1),fe){if(ue.nodeName){let Pr=Mt(ue.nodeName);if(!X[Pr]||xe[Pr])throw Ts("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof i)ee=Lr("<!---->"),Se=ee.ownerDocument.importNode(ue,!0),Se.nodeType===Ms.element&&Se.nodeName==="BODY"||Se.nodeName==="HTML"?ee=Se:ee.appendChild(Se);else{if(!J&&!Ce&&!tt&&ue.indexOf("<")===-1)return h&&Z?h.createHTML(ue):ue;if(ee=Lr(ue),!ee)return J?null:Z?w:""}ee&&me&&dr(ee.firstChild);let Ft=Or(fe?ue:ee);for(;rt=Ft.nextNode();)Un(rt),Pn(rt),rt.content instanceof s&&In(rt.content);if(fe)return ue;if(J){if(ze)for(Qt=W.call(ee.ownerDocument);ee.firstChild;)Qt.appendChild(ee.firstChild);else Qt=ee;return(K.shadowroot||K.shadowrootmode)&&(Qt=B.call(n,Qt,!0)),Qt}let tr=tt?ee.outerHTML:ee.innerHTML;return tt&&X["!doctype"]&&ee.ownerDocument&&ee.ownerDocument.doctype&&ee.ownerDocument.doctype.name&&Jr(sh,ee.ownerDocument.doctype.name)&&(tr="<!DOCTYPE "+ee.ownerDocument.doctype.name+`>
|
|
51
|
-
`+tr),Ce&&
|
|
48
|
+
`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,r,n){let o=Ig(e);if(o===null)return n;e=o;let s='<a href="'+e+'"';return r&&(s+=' title="'+r+'"'),s+=">"+n+"</a>",s}image(e,r,n){let o=Ig(e);if(o===null)return n;e=o;let s=`<img src="${e}" alt="${n}"`;return r&&(s+=` title="${r}"`),s+=">",s}text(e){return e}},bs=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,r,n){return""+n}image(e,r,n){return""+n}br(){return""}},po=class t{constructor(e){Ht(this,"options");Ht(this,"renderer");Ht(this,"textRenderer");this.options=e||ra,this.options.renderer=this.options.renderer||new ka,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new bs}static parse(e,r){return new t(r).parse(e)}static parseInline(e,r){return new t(r).parseInline(e)}parse(e,r=!0){let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=s,i=this.options.extensions.renderers[a.type].call({parser:this},a);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(a.type)){n+=i||"";continue}}switch(s.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let a=s;n+=this.renderer.heading(this.parseInline(a.tokens),a.depth,Qy(this.parseInline(a.tokens,this.textRenderer)));continue}case"code":{let a=s;n+=this.renderer.code(a.text,a.lang,!!a.escaped);continue}case"table":{let a=s,i="",d="";for(let p=0;p<a.header.length;p++)d+=this.renderer.tablecell(this.parseInline(a.header[p].tokens),{header:!0,align:a.align[p]});i+=this.renderer.tablerow(d);let l="";for(let p=0;p<a.rows.length;p++){let m=a.rows[p];d="";for(let u=0;u<m.length;u++)d+=this.renderer.tablecell(this.parseInline(m[u].tokens),{header:!1,align:a.align[u]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let a=s,i=this.parse(a.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let a=s,i=a.ordered,d=a.start,l=a.loose,p="";for(let m=0;m<a.items.length;m++){let u=a.items[m],f=u.checked,x=u.task,C="";if(u.task){let S=this.renderer.checkbox(!!f);l?u.tokens.length>0&&u.tokens[0].type==="paragraph"?(u.tokens[0].text=S+" "+u.tokens[0].text,u.tokens[0].tokens&&u.tokens[0].tokens.length>0&&u.tokens[0].tokens[0].type==="text"&&(u.tokens[0].tokens[0].text=S+" "+u.tokens[0].tokens[0].text)):u.tokens.unshift({type:"text",text:S+" "}):C+=S+" "}C+=this.parse(u.tokens,l),p+=this.renderer.listitem(C,x,!!f)}n+=this.renderer.list(p,i,d);continue}case"html":{let a=s;n+=this.renderer.html(a.text,a.block);continue}case"paragraph":{let a=s;n+=this.renderer.paragraph(this.parseInline(a.tokens));continue}case"text":{let a=s,i=a.tokens?this.parseInline(a.tokens):a.text;for(;o+1<e.length&&e[o+1].type==="text";)a=e[++o],i+=`
|
|
49
|
+
`+(a.tokens?this.parseInline(a.tokens):a.text);n+=r?this.renderer.paragraph(i):i;continue}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,r){r=r||this.renderer;let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){n+=a||"";continue}}switch(s.type){case"escape":{let a=s;n+=r.text(a.text);break}case"html":{let a=s;n+=r.html(a.text);break}case"link":{let a=s;n+=r.link(a.href,a.title,this.parseInline(a.tokens,r));break}case"image":{let a=s;n+=r.image(a.href,a.title,a.text);break}case"strong":{let a=s;n+=r.strong(this.parseInline(a.tokens,r));break}case"em":{let a=s;n+=r.em(this.parseInline(a.tokens,r));break}case"codespan":{let a=s;n+=r.codespan(a.text);break}case"br":{n+=r.br();break}case"del":{let a=s;n+=r.del(this.parseInline(a.tokens,r));break}case"text":{let a=s;n+=r.text(a.text);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}},Zo=class{constructor(e){Ht(this,"options");this.options=e||ra}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};Ht(Zo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var ta,id,Vg,ws=class{constructor(...e){Lg(this,ta);Ht(this,"defaults",ld());Ht(this,"options",this.setOptions);Ht(this,"parse",Si(this,ta,id).call(this,co.lex,po.parse));Ht(this,"parseInline",Si(this,ta,id).call(this,co.lexInline,po.parseInline));Ht(this,"Parser",po);Ht(this,"Renderer",ka);Ht(this,"TextRenderer",bs);Ht(this,"Lexer",co);Ht(this,"Tokenizer",Ma);Ht(this,"Hooks",Zo);this.use(...e)}walkTokens(e,r){var o,s;let n=[];for(let a of e)switch(n=n.concat(r.call(this,a)),a.type){case"table":{let i=a;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,r));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,r));break}case"list":{let i=a;n=n.concat(this.walkTokens(i.items,r));break}default:{let i=a;(s=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&s[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,r))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,r)))}}return n}use(...e){let r=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let a=r.renderers[s.name];a?r.renderers[s.name]=function(...i){let d=s.renderer.apply(this,i);return d===!1&&(d=a.apply(this,i)),d}:r.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=r[s.level];a?a.unshift(s.tokenizer):r[s.level]=[s.tokenizer],s.start&&(s.level==="block"?r.startBlock?r.startBlock.push(s.start):r.startBlock=[s.start]:s.level==="inline"&&(r.startInline?r.startInline.push(s.start):r.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(r.childTokens[s.name]=s.childTokens)}),o.extensions=r),n.renderer){let s=this.defaults.renderer||new ka(this.defaults);for(let a in n.renderer){if(!(a in s))throw new Error(`renderer '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.renderer[i],l=s[i];s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m||""}}o.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Ma(this.defaults);for(let a in n.tokenizer){if(!(a in s))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let i=a,d=n.tokenizer[i],l=s[i];s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m}}o.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new 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(u=>l.call(s,u));let m=d.call(s,p);return l.call(s,m)}:s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m}}o.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,a=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(a.call(this,i)),s&&(d=d.concat(s.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,r){return co.lex(e,r!=null?r:this.defaults)}parser(e,r){return po.parse(e,r!=null?r:this.defaults)}};ta=new WeakSet,id=function(e,r){return(n,o)=>{let s={...o},a={...this.defaults,...s};this.defaults.async===!0&&s.async===!1&&(a.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),a.async=!0);let i=Si(this,ta,Vg).call(this,!!a.silent,!!a.async);if(typeof n=="undefined"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(a.hooks&&(a.hooks.options=a),a.async)return Promise.resolve(a.hooks?a.hooks.preprocess(n):n).then(d=>e(d,a)).then(d=>a.hooks?a.hooks.processAllTokens(d):d).then(d=>a.walkTokens?Promise.all(this.walkTokens(d,a.walkTokens)).then(()=>d):d).then(d=>r(d,a)).then(d=>a.hooks?a.hooks.postprocess(d):d).catch(i);try{a.hooks&&(n=a.hooks.preprocess(n));let d=e(n,a);a.hooks&&(d=a.hooks.processAllTokens(d)),a.walkTokens&&this.walkTokens(d,a.walkTokens);let l=r(d,a);return a.hooks&&(l=a.hooks.postprocess(l)),l}catch(d){return i(d)}}},Vg=function(e,r){return n=>{if(n.message+=`
|
|
50
|
+
Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+gn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var ea=new ws;function nr(t,e){return ea.parse(t,e)}nr.options=nr.setOptions=function(t){return ea.setOptions(t),nr.defaults=ea.defaults,Hg(nr.defaults),nr};nr.getDefaults=ld;nr.defaults=ra;nr.use=function(...t){return ea.use(...t),nr.defaults=ea.defaults,Hg(nr.defaults),nr};nr.walkTokens=function(t,e){return ea.walkTokens(t,e)};nr.parseInline=ea.parseInline;nr.Parser=po;nr.parser=po.parse;nr.Renderer=ka;nr.TextRenderer=bs;nr.Lexer=co;nr.lexer=co.lex;nr.Tokenizer=Ma;nr.Hooks=Zo;nr.parse=nr;var iA=nr.options,lA=nr.setOptions,dA=nr.use,cA=nr.walkTokens,pA=nr.parseInline;var uA=po.parse,fA=co.lex;var kb=t=>{if(t)return t},As=t=>{var o,s;let e=t==null?void 0:t.markedOptions,r=new ws({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=kb(t==null?void 0:t.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},na=t=>t?As({markedOptions:t.options,renderer:t.renderer}):As(),Eb=As(),md=t=>Eb(t),oa=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Gg=t=>t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),jg=t=>`%%FORM_PLACEHOLDER_${t}%%`,Kg=(t,e)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=jg(e.length);return e.push({token:a,type:String(s.type)}),a}}catch{return n}return n}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let s=jg(e.length);return e.push({token:s,type:o}),s}),r},Xg=t=>{let e=na(t);return r=>{let n=[],o=Kg(r,n),s=e(o);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Gg(i)}"></div>`;s=s.replace(d,p)}),s}},Jg=t=>{let e=[],r=Kg(t,e),n=md(r);return e.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Gg(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:ah,setPrototypeOf:Qg,isFrozen:Lb,getPrototypeOf:Pb,getOwnPropertyDescriptor:Ib}=Object,{freeze:Qr,seal:Mn,create:Ii}=Object,{apply:vd,construct:Cd}=typeof Reflect!="undefined"&&Reflect;Qr||(Qr=function(e){return e});Mn||(Mn=function(e){return e});vd||(vd=function(e,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return e.apply(r,o)});Cd||(Cd=function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return new e(...n)});var Li=Yr(Array.prototype.forEach),Rb=Yr(Array.prototype.lastIndexOf),Yg=Yr(Array.prototype.pop),Ss=Yr(Array.prototype.push),Wb=Yr(Array.prototype.splice),Ri=Yr(String.prototype.toLowerCase),gd=Yr(String.prototype.toString),hd=Yr(String.prototype.match),Ts=Yr(String.prototype.replace),Bb=Yr(String.prototype.indexOf),Hb=Yr(String.prototype.trim),hn=Yr(Object.prototype.hasOwnProperty),Jr=Yr(RegExp.prototype.test),Ms=Db(TypeError);function Yr(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return vd(t,e,n)}}function Db(t){return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return Cd(t,r)}}function It(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ri;Qg&&Qg(t,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let s=r(o);s!==o&&(Lb(e)||(e[n]=s),o=s)}t[o]=!0}return t}function Ob(t){for(let e=0;e<t.length;e++)hn(t,e)||(t[e]=null);return t}function Kn(t){let e=Ii(null);for(let[r,n]of ah(t))hn(t,r)&&(Array.isArray(n)?e[r]=Ob(n):n&&typeof n=="object"&&n.constructor===Object?e[r]=Kn(n):e[r]=n);return e}function ks(t,e){for(;t!==null;){let n=Ib(t,e);if(n){if(n.get)return Yr(n.get);if(typeof n.value=="function")return Yr(n.value)}t=Pb(t)}function r(){return null}return r}var Zg=Qr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),xd=Qr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),yd=Qr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Nb=Qr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),bd=Qr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),_b=Qr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),eh=Qr(["#text"]),th=Qr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),wd=Qr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),rh=Qr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Pi=Qr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Fb=Mn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),$b=Mn(/<%[\w\W]*|[\w\W]*%>/gm),Ub=Mn(/\$\{[\w\W]*/gm),qb=Mn(/^data-[\-\w.\u00B7-\uFFFF]+$/),zb=Mn(/^aria-[\-\w]+$/),sh=Mn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vb=Mn(/^(?:\w+script|data):/i),jb=Mn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ih=Mn(/^html$/i),Gb=Mn(/^[a-z][.\w]*(-[.\w]+)+$/i),nh=Object.freeze({__proto__:null,ARIA_ATTR:zb,ATTR_WHITESPACE:jb,CUSTOM_ELEMENT:Gb,DATA_ATTR:qb,DOCTYPE_NAME:ih,ERB_EXPR:$b,IS_ALLOWED_URI:sh,IS_SCRIPT_OR_DATA:Vb,MUSTACHE_EXPR:Fb,TMPLIT_EXPR:Ub}),Es={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Kb=function(){return typeof window=="undefined"?null:window},Xb=function(e,r){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(n=r.getAttribute(o));let s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},oh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function lh(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Kb(),e=ue=>lh(ue);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Es.document||!t.Element)return e.isSupported=!1,e;let{document:r}=t,n=r,o=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:u,trustedTypes:f}=t,x=d.prototype,C=ks(x,"cloneNode"),S=ks(x,"remove"),k=ks(x,"nextSibling"),T=ks(x,"childNodes"),M=ks(x,"parentNode");if(typeof a=="function"){let ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let h,w="",{implementation:y,createNodeIterator:E,createDocumentFragment:B,getElementsByTagName:P}=r,{importNode:R}=n,O=oh();e.isSupported=typeof ah=="function"&&typeof M=="function"&&y&&y.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:ne,TMPLIT_EXPR:be,DATA_ATTR:Ye,ARIA_ATTR:Ge,IS_SCRIPT_OR_DATA:ve,ATTR_WHITESPACE:Ee,CUSTOM_ELEMENT:Ke}=nh,{IS_ALLOWED_URI:Ne}=nh,X=null,Ue=It({},[...Zg,...xd,...yd,...bd,...eh]),K=null,Te=It({},[...th,...wd,...rh,...Pi]),oe=Object.seal(Ii(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),xe=null,Me=null,Xe=Object.seal(Ii(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ce=!0,te=!0,le=!1,ut=!0,Ce=!1,he=!0,rt=!1,_e=!1,me=!1,J=!1,ze=!1,Z=!1,ge=!0,z=!1,Re="user-content-",Ae=!0,fe=!1,pe={},Be=null,Q=It({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),_=null,ke=It({},["audio","video","img","source","image","track"]),He=null,Ve=It({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Je="http://www.w3.org/1998/Math/MathML",gt="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml",Mt=at,Xt=!1,G=null,Jt=It({},[Je,gt,at],gd),st=It({},["mi","mo","mn","ms","mtext"]),_t=It({},["annotation-xml"]),de=It({},["title","style","font","a","script"]),ye=null,Rt=["application/xhtml+xml","text/html"],ar="text/html",kt=null,mr=null,Ot=r.createElement("form"),Wt=function(I){return I instanceof RegExp||I instanceof Function},St=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(mr&&mr===I)){if((!I||typeof I!="object")&&(I={}),I=Kn(I),ye=Rt.indexOf(I.PARSER_MEDIA_TYPE)===-1?ar:I.PARSER_MEDIA_TYPE,kt=ye==="application/xhtml+xml"?gd:Ri,X=hn(I,"ALLOWED_TAGS")?It({},I.ALLOWED_TAGS,kt):Ue,K=hn(I,"ALLOWED_ATTR")?It({},I.ALLOWED_ATTR,kt):Te,G=hn(I,"ALLOWED_NAMESPACES")?It({},I.ALLOWED_NAMESPACES,gd):Jt,He=hn(I,"ADD_URI_SAFE_ATTR")?It(Kn(Ve),I.ADD_URI_SAFE_ATTR,kt):Ve,_=hn(I,"ADD_DATA_URI_TAGS")?It(Kn(ke),I.ADD_DATA_URI_TAGS,kt):ke,Be=hn(I,"FORBID_CONTENTS")?It({},I.FORBID_CONTENTS,kt):Q,xe=hn(I,"FORBID_TAGS")?It({},I.FORBID_TAGS,kt):Kn({}),Me=hn(I,"FORBID_ATTR")?It({},I.FORBID_ATTR,kt):Kn({}),pe=hn(I,"USE_PROFILES")?I.USE_PROFILES:!1,ce=I.ALLOW_ARIA_ATTR!==!1,te=I.ALLOW_DATA_ATTR!==!1,le=I.ALLOW_UNKNOWN_PROTOCOLS||!1,ut=I.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ce=I.SAFE_FOR_TEMPLATES||!1,he=I.SAFE_FOR_XML!==!1,rt=I.WHOLE_DOCUMENT||!1,J=I.RETURN_DOM||!1,ze=I.RETURN_DOM_FRAGMENT||!1,Z=I.RETURN_TRUSTED_TYPE||!1,me=I.FORCE_BODY||!1,ge=I.SANITIZE_DOM!==!1,z=I.SANITIZE_NAMED_PROPS||!1,Ae=I.KEEP_CONTENT!==!1,fe=I.IN_PLACE||!1,Ne=I.ALLOWED_URI_REGEXP||sh,Mt=I.NAMESPACE||at,st=I.MATHML_TEXT_INTEGRATION_POINTS||st,_t=I.HTML_INTEGRATION_POINTS||_t,oe=I.CUSTOM_ELEMENT_HANDLING||{},I.CUSTOM_ELEMENT_HANDLING&&Wt(I.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(oe.tagNameCheck=I.CUSTOM_ELEMENT_HANDLING.tagNameCheck),I.CUSTOM_ELEMENT_HANDLING&&Wt(I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(oe.attributeNameCheck=I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),I.CUSTOM_ELEMENT_HANDLING&&typeof I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(oe.allowCustomizedBuiltInElements=I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ce&&(te=!1),ze&&(J=!0),pe&&(X=It({},eh),K=Ii(null),pe.html===!0&&(It(X,Zg),It(K,th)),pe.svg===!0&&(It(X,xd),It(K,wd),It(K,Pi)),pe.svgFilters===!0&&(It(X,yd),It(K,wd),It(K,Pi)),pe.mathMl===!0&&(It(X,bd),It(K,rh),It(K,Pi))),hn(I,"ADD_TAGS")||(Xe.tagCheck=null),hn(I,"ADD_ATTR")||(Xe.attributeCheck=null),I.ADD_TAGS&&(typeof I.ADD_TAGS=="function"?Xe.tagCheck=I.ADD_TAGS:(X===Ue&&(X=Kn(X)),It(X,I.ADD_TAGS,kt))),I.ADD_ATTR&&(typeof I.ADD_ATTR=="function"?Xe.attributeCheck=I.ADD_ATTR:(K===Te&&(K=Kn(K)),It(K,I.ADD_ATTR,kt))),I.ADD_URI_SAFE_ATTR&&It(He,I.ADD_URI_SAFE_ATTR,kt),I.FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,I.FORBID_CONTENTS,kt)),I.ADD_FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,I.ADD_FORBID_CONTENTS,kt)),Ae&&(X["#text"]=!0),rt&&It(X,["html","head","body"]),X.table&&(It(X,["tbody"]),delete xe.tbody),I.TRUSTED_TYPES_POLICY){if(typeof I.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ms('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof I.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ms('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');h=I.TRUSTED_TYPES_POLICY,w=h.createHTML("")}else h===void 0&&(h=Xb(f,o)),h!==null&&typeof w=="string"&&(w=h.createHTML(""));Qr&&Qr(I),mr=I}},Et=It({},[...xd,...yd,...Nb]),sr=It({},[...bd,..._b]),ft=function(I){let ee=M(I);(!ee||!ee.tagName)&&(ee={namespaceURI:Mt,tagName:"template"});let Se=Ri(I.tagName),nt=Ri(ee.tagName);return G[I.namespaceURI]?I.namespaceURI===gt?ee.namespaceURI===at?Se==="svg":ee.namespaceURI===Je?Se==="svg"&&(nt==="annotation-xml"||st[nt]):!!Et[Se]:I.namespaceURI===Je?ee.namespaceURI===at?Se==="math":ee.namespaceURI===gt?Se==="math"&&_t[nt]:!!sr[Se]:I.namespaceURI===at?ee.namespaceURI===gt&&!_t[nt]||ee.namespaceURI===Je&&!st[nt]?!1:!sr[Se]&&(de[Se]||!Et[Se]):!!(ye==="application/xhtml+xml"&&G[I.namespaceURI]):!1},dr=function(I){Ss(e.removed,{element:I});try{M(I).removeChild(I)}catch{S(I)}},wr=function(I,ee){try{Ss(e.removed,{attribute:ee.getAttributeNode(I),from:ee})}catch{Ss(e.removed,{attribute:null,from:ee})}if(ee.removeAttribute(I),I==="is")if(J||ze)try{dr(ee)}catch{}else try{ee.setAttribute(I,"")}catch{}},Lr=function(I){let ee=null,Se=null;if(me)I="<remove></remove>"+I;else{let Ft=hd(I,/^[\r\n\t ]+/);Se=Ft&&Ft[0]}ye==="application/xhtml+xml"&&Mt===at&&(I='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+I+"</body></html>");let nt=h?h.createHTML(I):I;if(Mt===at)try{ee=new u().parseFromString(nt,ye)}catch{}if(!ee||!ee.documentElement){ee=y.createDocument(Mt,"template",null);try{ee.documentElement.innerHTML=Xt?w:nt}catch{}}let Qt=ee.body||ee.documentElement;return I&&Se&&Qt.insertBefore(r.createTextNode(Se),Qt.childNodes[0]||null),Mt===at?P.call(ee,rt?"html":"body")[0]:rt?ee.documentElement:Qt},Or=function(I){return E.call(I.ownerDocument||I,I,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},xt=function(I){return I instanceof m&&(typeof I.nodeName!="string"||typeof I.textContent!="string"||typeof I.removeChild!="function"||!(I.attributes instanceof p)||typeof I.removeAttribute!="function"||typeof I.setAttribute!="function"||typeof I.namespaceURI!="string"||typeof I.insertBefore!="function"||typeof I.hasChildNodes!="function")},sn=function(I){return typeof i=="function"&&I instanceof i};function fr(ue,I,ee){Li(ue,Se=>{Se.call(e,I,ee,mr)})}let Un=function(I){let ee=null;if(fr(O.beforeSanitizeElements,I,null),xt(I))return dr(I),!0;let Se=kt(I.nodeName);if(fr(O.uponSanitizeElement,I,{tagName:Se,allowedTags:X}),he&&I.hasChildNodes()&&!sn(I.firstElementChild)&&Jr(/<[/\w!]/g,I.innerHTML)&&Jr(/<[/\w!]/g,I.textContent)||I.nodeType===Es.progressingInstruction||he&&I.nodeType===Es.comment&&Jr(/<[/\w]/g,I.data))return dr(I),!0;if(!(Xe.tagCheck instanceof Function&&Xe.tagCheck(Se))&&(!X[Se]||xe[Se])){if(!xe[Se]&&Zn(Se)&&(oe.tagNameCheck instanceof RegExp&&Jr(oe.tagNameCheck,Se)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(Se)))return!1;if(Ae&&!Be[Se]){let nt=M(I)||I.parentNode,Qt=T(I)||I.childNodes;if(Qt&&nt){let Ft=Qt.length;for(let tr=Ft-1;tr>=0;--tr){let Pr=C(Qt[tr],!0);Pr.__removalCount=(I.__removalCount||0)+1,nt.insertBefore(Pr,k(I))}}}return dr(I),!0}return I instanceof d&&!ft(I)||(Se==="noscript"||Se==="noembed"||Se==="noframes")&&Jr(/<\/no(script|embed|frames)/i,I.innerHTML)?(dr(I),!0):(Ce&&I.nodeType===Es.text&&(ee=I.textContent,Li([V,ne,be],nt=>{ee=Ts(ee,nt," ")}),I.textContent!==ee&&(Ss(e.removed,{element:I.cloneNode()}),I.textContent=ee)),fr(O.afterSanitizeElements,I,null),!1)},Rr=function(I,ee,Se){if(Me[ee]||ge&&(ee==="id"||ee==="name")&&(Se in r||Se in Ot))return!1;if(!(te&&!Me[ee]&&Jr(Ye,ee))){if(!(ce&&Jr(Ge,ee))){if(!(Xe.attributeCheck instanceof Function&&Xe.attributeCheck(ee,I))){if(!K[ee]||Me[ee]){if(!(Zn(I)&&(oe.tagNameCheck instanceof RegExp&&Jr(oe.tagNameCheck,I)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(I))&&(oe.attributeNameCheck instanceof RegExp&&Jr(oe.attributeNameCheck,ee)||oe.attributeNameCheck instanceof Function&&oe.attributeNameCheck(ee,I))||ee==="is"&&oe.allowCustomizedBuiltInElements&&(oe.tagNameCheck instanceof RegExp&&Jr(oe.tagNameCheck,Se)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(Se))))return!1}else if(!He[ee]){if(!Jr(Ne,Ts(Se,Ee,""))){if(!((ee==="src"||ee==="xlink:href"||ee==="href")&&I!=="script"&&Bb(Se,"data:")===0&&_[I])){if(!(le&&!Jr(ve,Ts(Se,Ee,"")))){if(Se)return!1}}}}}}}return!0},Zn=function(I){return I!=="annotation-xml"&&hd(I,Ke)},Pn=function(I){fr(O.beforeSanitizeAttributes,I,null);let{attributes:ee}=I;if(!ee||xt(I))return;let Se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0},nt=ee.length;for(;nt--;){let Qt=ee[nt],{name:Ft,namespaceURI:tr,value:Pr}=Qt,Nr=kt(Ft),wn=Pr,Vt=Ft==="value"?wn:Hb(wn);if(Se.attrName=Nr,Se.attrValue=Vt,Se.keepAttr=!0,Se.forceKeepAttr=void 0,fr(O.uponSanitizeAttribute,I,Se),Vt=Se.attrValue,z&&(Nr==="id"||Nr==="name")&&(wr(Ft,I),Vt=Re+Vt),he&&Jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){wr(Ft,I);continue}if(Nr==="attributename"&&hd(Vt,"href")){wr(Ft,I);continue}if(Se.forceKeepAttr)continue;if(!Se.keepAttr){wr(Ft,I);continue}if(!ut&&Jr(/\/>/i,Vt)){wr(Ft,I);continue}Ce&&Li([V,ne,be],Ir=>{Vt=Ts(Vt,Ir," ")});let $t=kt(I.nodeName);if(!Rr($t,Nr,Vt)){wr(Ft,I);continue}if(h&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!tr)switch(f.getAttributeType($t,Nr)){case"TrustedHTML":{Vt=h.createHTML(Vt);break}case"TrustedScriptURL":{Vt=h.createScriptURL(Vt);break}}if(Vt!==wn)try{tr?I.setAttributeNS(tr,Ft,Vt):I.setAttribute(Ft,Vt),xt(I)?dr(I):Yg(e.removed)}catch{wr(Ft,I)}}fr(O.afterSanitizeAttributes,I,null)},In=function ue(I){let ee=null,Se=Or(I);for(fr(O.beforeSanitizeShadowDOM,I,null);ee=Se.nextNode();)fr(O.uponSanitizeShadowNode,ee,null),Un(ee),Pn(ee),ee.content instanceof s&&ue(ee.content);fr(O.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(ue){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ee=null,Se=null,nt=null,Qt=null;if(Xt=!ue,Xt&&(ue="<!-->"),typeof ue!="string"&&!sn(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw Ms("dirty is not a string, aborting")}else throw Ms("toString is not a function");if(!e.isSupported)return ue;if(_e||St(I),e.removed=[],typeof ue=="string"&&(fe=!1),fe){if(ue.nodeName){let Pr=kt(ue.nodeName);if(!X[Pr]||xe[Pr])throw Ms("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof i)ee=Lr("<!---->"),Se=ee.ownerDocument.importNode(ue,!0),Se.nodeType===Es.element&&Se.nodeName==="BODY"||Se.nodeName==="HTML"?ee=Se:ee.appendChild(Se);else{if(!J&&!Ce&&!rt&&ue.indexOf("<")===-1)return h&&Z?h.createHTML(ue):ue;if(ee=Lr(ue),!ee)return J?null:Z?w:""}ee&&me&&dr(ee.firstChild);let Ft=Or(fe?ue:ee);for(;nt=Ft.nextNode();)Un(nt),Pn(nt),nt.content instanceof s&&In(nt.content);if(fe)return ue;if(J){if(ze)for(Qt=B.call(ee.ownerDocument);ee.firstChild;)Qt.appendChild(ee.firstChild);else Qt=ee;return(K.shadowroot||K.shadowrootmode)&&(Qt=R.call(n,Qt,!0)),Qt}let tr=rt?ee.outerHTML:ee.innerHTML;return rt&&X["!doctype"]&&ee.ownerDocument&&ee.ownerDocument.doctype&&ee.ownerDocument.doctype.name&&Jr(ih,ee.ownerDocument.doctype.name)&&(tr="<!DOCTYPE "+ee.ownerDocument.doctype.name+`>
|
|
51
|
+
`+tr),Ce&&Li([V,ne,be],Pr=>{tr=Ts(tr,Pr," ")}),h&&Z?h.createHTML(tr):tr},e.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};St(ue),_e=!0},e.clearConfig=function(){mr=null,_e=!1},e.isValidAttribute=function(ue,I,ee){mr||St({});let Se=kt(ue),nt=kt(I);return Rr(Se,nt,ee)},e.addHook=function(ue,I){typeof I=="function"&&Ss(O[ue],I)},e.removeHook=function(ue,I){if(I!==void 0){let ee=Rb(O[ue],I);return ee===-1?void 0:Wb(O[ue],ee,1)[0]}return Yg(O[ue])},e.removeHooks=function(ue){O[ue]=[]},e.removeAllHooks=function(){O=oh()},e}var dh=lh();var Jb={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"]},Qb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ad=()=>{let t=dh(typeof window!="undefined"?window:void 0);return t.addHook("uponSanitizeAttribute",(e,r)=>{if(r.attrName==="src"||r.attrName==="href"){let n=r.attrValue;n.toLowerCase().startsWith("data:")&&!Qb.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),e=>t.sanitize(e,Jb)},Ea=t=>t===!1?null:typeof t=="function"?t:Ad();var Ls="webmcp:",Fi={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}};function Ph(t){if(t.length===0)return"0:empty";let e=t.map(r=>{var n,o;return[r.name,(n=r.description)!=null?n:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(o=r.origin)!=null?o:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${t.length}:${J0(e.join(""))}`}function Lh(t,e){let r=3735928559^e,n=1103547991^e;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);r=Math.imul(r^s,2654435761),n=Math.imul(n^s,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}function J0(t){let e=Lh(t,0).toString(36),r=Lh(t,2654435761).toString(36);return`${e}.${r}`}var Ia=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=e.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let r;try{r=await e.getTools()}catch(o){return Fi.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=Y0(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,r,n){if(await this.ensureReady(),this.config.enabled!==!0)return Fn("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let f=typeof document!="undefined"&&!!document.modelContext;return Fn(f?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Id(e),a;try{a=await o.getTools()}catch(f){let x=f instanceof Error?f.message:String(f);return Fn(`Failed to read WebMCP registry: ${x}`)}let i=a.find(f=>f.name===s);if(!i)return Fn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Fn(`WebMCP tool not allowed by client allowlist: ${s}`);if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let d={toolName:s,args:r,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return Fn("User declined the tool call.");if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),u=()=>l.abort();n&&(n.aborted?l.abort():n.addEventListener("abort",u,{once:!0}));try{let f=await o.executeTool(i,rw(r),{signal:l.signal});return Z0(f)}catch(f){if(p)return Fn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let x=f instanceof Error?f.message:String(f);return Fn(x)}finally{clearTimeout(m),n&&n.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await Promise.resolve().then(()=>(Eh(),kh))).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Fi.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let r=e;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Fi.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var n;let r=(n=this.confirmHandler)!=null?n:ew;try{return await r(e)}catch(o){return Fi.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(n=>Q0(e,n))}},Id=t=>t.startsWith(Ls)?t.slice(Ls.length):t,Io=t=>t.startsWith(Ls),Q0=(t,e)=>{if(e==="*")return!0;let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(t)},Y0=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Z0=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:nw(e)}]}},Fn=t=>({isError:!0,content:[{type:"text",text:t}]}),ew=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=tw(t.args),r=`Allow the AI to call ${t.toolName}`+(e?`
|
|
52
52
|
|
|
53
53
|
Arguments:
|
|
54
54
|
${e}`:"")+(t.description?`
|
|
55
55
|
|
|
56
|
-
${t.description}`:"");return window.confirm(r)},
|
|
57
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
56
|
+
${t.description}`:"");return window.confirm(r)},tw=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},rw=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},nw=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var fo=ad(qi(),1),zi=t=>t.replace(/\\n/g,`
|
|
57
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ra=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},lw=t=>{var a,i;let e=(a=t.completedAt)!=null?a:Date.now(),r=(i=t.startedAt)!=null?i:e,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Rh=t=>t.status==="complete"?lw(t):t.status==="pending"?"Waiting":"",dw=t=>{var o,s,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Wh=t=>t.status==="complete"?dw(t):"Using tool...",Vi=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Is=t=>{var r,n,o;let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((r=t.completedAt)!=null?r:Date.now())-((o=(n=t.startedAt)!=null?n:t.completedAt)!=null?o:Date.now()));return Vi(e)},ji=t=>{var r,n,o;let e=t.durationMs!==void 0?t.durationMs:Math.max(0,((r=t.completedAt)!=null?r:Date.now())-((o=(n=t.startedAt)!=null?n:t.completedAt)!=null?o:Date.now()));return Vi(e)},Wd=(t,e,r)=>{var s;if(!e)return r;let n=((s=t.name)==null?void 0:s.trim())||"tool",o=Is(t);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Gi=(t,e)=>{let r=t.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(r))!==null;)a.index>s&&Ps(n,r.slice(s,a.index),[]),a[1]!==void 0?Ps(n,a[1],["bold"]):a[2]!==void 0?Ps(n,a[2],["italic"]):a[3]!==void 0&&Ps(n,a[3],["dim"]),s=a.index+a[0].length;return s<r.length&&Ps(n,r.slice(s),[]),n},Ps=(t,e,r)=>{let n=e.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&t.push({text:n[o],styles:r}),o<n.length-1&&t.push({text:"{duration}",styles:r,isDuration:!0})},cw=()=>{let t=null,e=0,r=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=n.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
58
58
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
59
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async n=>{if(n.length<=e)return t!==null?{text:t,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(n);return s!==null&&(t=s),e=n.length,t!==null?{text:t,raw:n}:null},close:async()=>{}}},oa=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Gi=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Ki=()=>{var e;let t=lw();return{processChunk:async r=>{let n=r.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},Xi=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,fo.parse)(r,fo.STR|fo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?qi(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=qi(o.text)))}catch{}return e=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Wh=t=>{let e=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?qi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?qi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let i=(0,fo.parse)(s,fo.STR|fo.OBJ),d=o(i);d!==null&&(e=d)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Ji=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let n=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(t=n[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Qi=class{constructor(e,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=r}push(e,r){var s,a,i;let n=(i=(s=r==null?void 0:r.seq)!=null?s:r==null?void 0:r.sequenceIndex)!=null?i:(a=r==null?void 0:r.agentContext)==null?void 0:a.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(e,r),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(e,r);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:e,payload:r,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((r,n)=>r[0]-n[0]);for(let[r,n]of e)this.buffer.delete(r),this.emitter(n.payloadType,n.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var dw="https://api.runtype.com/v1/dispatch",Yi="https://api.runtype.com";function cw(t){var s,a;let e=t.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(n)return`attachment.${n}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Wd=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function pw(t){switch(t){case"json":return Xi;case"regex-json":return Ki;case"xml":return Ji;default:return Gi}}var Bh=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function uw(t,e){if(!t)return e;let r=t.trim(),n=e.trim();if(r.length===0)return e;if(n.length===0)return t;let o=Bh(r);if(!Bh(n))return t;if(!o||n===r||n.startsWith(r))return e;let a=oa(t);return oa(e)!==null&&a===null?e:t}var aa=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,n,o,s;this.apiUrl=(r=e.apiUrl)!=null?r:dw,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:pw(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Pa(e.webmcp):null}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,r,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,r,n):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Yi}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,this.resetClientToolsFingerprint(),(r=(e=this.config).onSessionInit)==null||r.call(e,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Yi}/v1/client/feedback`}async sendFeedback(e){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:r})}async submitCSATFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:e,comment:r})}async submitNPSFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:e,comment:r})}async dispatch(e,r){return this.isAgentMode()?this.dispatchAgent(e,r):this.isClientTokenMode()?this.dispatchClientToken(e,r):this.dispatchProxy(e,r)}async dispatchClientToken(e,r){var o,s,a,i;let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}let l=await this.buildPayload(e.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Wd).map(h=>{var w,x,T;return{id:h.id,role:h.role,content:(T=(x=(w=h.contentParts)!=null?w:h.llmContent)!=null?x:h.rawContent)!=null?T:h.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,f=!!(u&&u.length>0),y=f?Lh(u):void 0,A=this.clientToolsFingerprintSessionId===d.sessionId,S=f&&A&&this.lastSentClientToolsFingerprint===y,M=!1,k=null,E;for(let h=0;;h++){let x={...m,...f&&(M||!S)&&u?{clientTools:u}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),E=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),signal:n.signal}),E.status===409&&h===0&&f){let T=await E.json().catch(()=>null);if((T==null?void 0:T.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}k=T!=null?T:{error:"Chat request failed"}}break}if(!E.ok){let h=k!=null?k:await E.json().catch(()=>({error:"Chat request failed"}));if(E.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:x}),x}if(E.status===429){let x=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:x}),x}let w=new Error(h.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!E.body){let h=new Error("No response body received");throw r({type:"error",error:h}),h}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(E.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(e,r,n){r({type:"status",status:"connected"});try{await this.streamResponse(e,r,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(e,r){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Yi}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(e,r,n){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Yi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:r,streamResponse:(p=n==null?void 0:n.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(e){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Wd).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),n={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}return n}async buildPayload(e){var s;let n={messages:e.slice().filter(Wd).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...n},config:this.config});if(a&&typeof a=="object"){let i=a;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return n}async handleCustomSSEEvent(e,r,n,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return n.current=m,o(m),m},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),a.current=null,r({type:"status",status:"idle"})),i.error&&(a.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r,n){var fe,pe,Be,Q;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=N=>{let Me=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,He=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,Ve=N.tools?N.tools.map(Xe=>({...Xe,chunks:Xe.chunks?[...Xe.chunks]:void 0})):void 0;return{...N,reasoning:Me,toolCall:He,tools:Ve}},m=N=>{if(N.role!=="assistant"||N.variant)return!0;let Me=Array.isArray(N.contentParts)&&N.contentParts.length>0,He=typeof N.rawContent=="string"&&N.rawContent.trim()!=="";return typeof N.content=="string"&&N.content.trim()!==""||Me||He||!!N.stopReason},u=N=>{m(N)&&r({type:"message",message:p(N)})},f=null,y=null,A={current:null},S={current:null},M=!1,k=new Map,E=new Map,h=new Map,w=new Map,x={lastId:null,byStep:new Map},T={lastId:null,byCall:new Map},W=(N,Me,He="")=>`${N}::${Me}::${He}`,R=(N,Me)=>`${N}::${Me}::`,B=(N,Me,He,Ve)=>{let Xe=W(N,Me,He),gt=h.get(Xe);if(gt)return gt;let ot=He?`-${He}`:"",kt={id:`nested-${N}-${Me}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Ve,parentToolId:N,parentStepId:Me}};return h.set(Xe,kt),u(kt),kt},_=N=>{if(N==null)return null;try{return String(N)}catch{return null}},V=N=>{var Me,He,Ve,Xe,gt;return _((gt=(Xe=(Ve=(He=(Me=N.stepId)!=null?Me:N.step_id)!=null?He:N.step)!=null?Ve:N.parentId)!=null?Xe:N.flowStepId)!=null?gt:N.flow_step_id)},oe=N=>{var Me,He,Ve,Xe,gt,ot,kt;return _((kt=(ot=(gt=(Xe=(Ve=(He=(Me=N.callId)!=null?Me:N.call_id)!=null?He:N.requestId)!=null?Ve:N.request_id)!=null?Xe:N.toolCallId)!=null?gt:N.tool_call_id)!=null?ot:N.stepId)!=null?kt:N.step_id)},be=n,Qe=!1,je=()=>{if(f)return f;let N;return!Qe&&be?(N=be,Qe=!0):be&&S.current?N=`${be}_${S.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(f),f},ve=(N,Me)=>{x.lastId=Me,N&&x.byStep.set(N,Me)},Ee=(N,Me)=>{var gt;let He=(gt=N.reasoningId)!=null?gt:N.id,Ve=V(N);if(He){let ot=String(He);return ve(Ve,ot),ot}if(Ve){let ot=x.byStep.get(Ve);if(ot)return x.lastId=ot,ot}if(x.lastId&&!Me)return x.lastId;if(!Me)return null;let Xe=`reason-${l()}`;return ve(Ve,Xe),Xe},Ge=N=>{let Me=k.get(N);if(Me)return Me;let He={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:N,status:"streaming",chunks:[]}};return k.set(N,He),u(He),He},_e=(N,Me)=>{T.lastId=Me,N&&T.byCall.set(N,Me)},X=new Set,Ue=new Map,K=new Set,Te=new Map,ae=N=>{if(!N)return!1;let Me=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return Me==="emit_artifact_markdown"||Me==="emit_artifact_component"},xe=(N,Me)=>{var gt;let He=(gt=N.toolId)!=null?gt:N.id,Ve=oe(N);if(He){let ot=String(He);return _e(Ve,ot),ot}if(Ve){let ot=T.byCall.get(Ve);if(ot)return T.lastId=ot,ot}if(T.lastId&&!Me)return T.lastId;if(!Me)return null;let Xe=`tool-${l()}`;return _e(Ve,Xe),Xe},ke=N=>{let Me=E.get(N);if(Me)return Me;let He={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return E.set(N,He),u(He),He},Ke=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let Me=Number(N);if(!Number.isNaN(Me)&&Number.isFinite(Me))return Me;let He=Date.parse(N);if(!Number.isNaN(He))return He}return Date.now()},ce=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},re=new Map,le=new Map,ut=new Map,Ce=new Map,he=null,tt=(N,Me,He)=>{var kt;let Ve=ut.get(N);Ve||(Ve=[],ut.set(N,Ve));let Xe=0,gt=Ve.length;for(;Xe<gt;){let Xt=Xe+gt>>>1;Ve[Xt].seq<Me?Xe=Xt+1:gt=Xt}((kt=Ve[Xe])==null?void 0:kt.seq)===Me?Ve[Xe]={seq:Me,text:He}:Ve.splice(Xe,0,{seq:Me,text:He});let ot="";for(let Xt=0;Xt<Ve.length;Xt++)ot+=Ve[Xt].text;return ot},Ne=(N,Me)=>{let He=ce(Me),Ve=le.get(N.id),Xe=uw(Ve,He);N.rawContent=Xe;let gt=re.get(N.id),ot=at=>{var de;let Nt=(de=N.content)!=null?de:"";at.trim()!==""&&(Nt.trim().length===0||at.startsWith(Nt)||at.trimStart().startsWith(Nt.trim()))&&(N.content=at)},kt=()=>{var at;if(gt){let Nt=(at=gt.close)==null?void 0:at.call(gt);Nt instanceof Promise&&Nt.catch(()=>{})}re.delete(N.id),le.delete(N.id),N.streaming=!1,u(N)};if(!gt){ot(He),kt();return}let Xt=oa(Xe);if(Xt!==null&&Xt.trim()!==""){ot(Xt),kt();return}let G=at=>{var ye;let Nt=typeof at=="string"?at:(ye=at==null?void 0:at.text)!=null?ye:null;if(Nt!==null&&Nt.trim()!=="")return Nt;let de=gt.getExtractedText();return de!==null&&de.trim()!==""?de:He},Jt;try{Jt=gt.processChunk(Xe)}catch{ot(He),kt();return}if(Jt instanceof Promise){Jt.then(at=>{ot(G(at)),kt()}).catch(()=>{ot(He),kt()});return}ot(G(Jt)),kt()},me=[],J=!1,ze,Z=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ze()}))},ge=new Qi((N,Me)=>{me.push({payloadType:N,payload:Me}),Z()}),z=null,Re=new Map,Ae=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(ze=()=>{var N,Me,He,Ve,Xe,gt,ot,kt,Xt,G,Jt,at,Nt,de,ye,Rt,ar,Mt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,P,ee,Se,rt,Qt,Ft,tr,Pr,_r,wn,Vt,$t,Ir,vn,bo,eo,wo,qn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn,I,pn,Bn,to,zn,Xa,Hn,Dn,On,ro,Fo,ri,Ja,ni,ha,Lt,Qa,An,tn,oi,ai,xa,no,si,$o,Ya,oo,Za,Co,Ao,ii,li,rd,Uo,So,di,es,To,ci,ts,ko,rs,pi,ao,ui,Mo,Kt,ya,ba,ns,Vn,fi,os,as,mi,wa,va,qo,gi,hi,ss,is,ls,ds,zr,un,so,yt,cs,zo,_n,xi;for(let Eo=0;Eo<me.length;Eo++){let st=me[Eo].payloadType,L=me[Eo].payload;if(st==="reason_start"){let q=(N=Ee(L,!0))!=null?N:`reason-${l()}`,O=Ge(q);O.reasoning=(Me=O.reasoning)!=null?Me:{id:q,status:"streaming",chunks:[]},O.reasoning.startedAt=(Ve=O.reasoning.startedAt)!=null?Ve:Ke((He=L.startedAt)!=null?He:L.timestamp),O.reasoning.completedAt=void 0,O.reasoning.durationMs=void 0,O.streaming=!0,O.reasoning.status="streaming",u(O)}else if(st==="reason_delta"||st==="reason_chunk"){let q=(gt=(Xe=Ee(L,!1))!=null?Xe:Ee(L,!0))!=null?gt:`reason-${l()}`,O=Ge(q);O.reasoning=(ot=O.reasoning)!=null?ot:{id:q,status:"streaming",chunks:[]},O.reasoning.startedAt=(Xt=O.reasoning.startedAt)!=null?Xt:Ke((kt=L.startedAt)!=null?kt:L.timestamp);let se=(at=(Jt=(G=L.reasoningText)!=null?G:L.text)!=null?Jt:L.delta)!=null?at:"";if(se&&L.hidden!==!0){let Y=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(Y!==void 0){let te=tt(q,Y,String(se));O.reasoning.chunks=[te]}else O.reasoning.chunks.push(String(se))}if(O.reasoning.status=L.done?"complete":"streaming",L.done){O.reasoning.completedAt=Ke((Nt=L.completedAt)!=null?Nt:L.timestamp);let Y=(de=O.reasoning.startedAt)!=null?de:Date.now();O.reasoning.durationMs=Math.max(0,((ye=O.reasoning.completedAt)!=null?ye:Date.now())-Y)}O.streaming=O.reasoning.status!=="complete",u(O)}else if(st==="reason_complete"){let q=(ar=(Rt=Ee(L,!1))!=null?Rt:Ee(L,!0))!=null?ar:`reason-${l()}`,O=k.get(q);if(O!=null&&O.reasoning){O.reasoning.status="complete",O.reasoning.completedAt=Ke((Mt=L.completedAt)!=null?Mt:L.timestamp);let Y=(mr=O.reasoning.startedAt)!=null?mr:Date.now();O.reasoning.durationMs=Math.max(0,((Ot=O.reasoning.completedAt)!=null?Ot:Date.now())-Y),O.streaming=!1,u(O)}let se=V(L);se&&x.byStep.delete(se)}else if(st==="tool_start"){let q=(Wt=xe(L,!0))!=null?Wt:`tool-${l()}`,O=(St=L.toolName)!=null?St:L.name;if(ae(O)){X.add(q);continue}let se=ke(q),Y=(Et=se.toolCall)!=null?Et:{id:q,status:"pending"};Y.name=O!=null?O:Y.name,Y.status="running",L.args!==void 0?Y.args=L.args:L.parameters!==void 0&&(Y.args=L.parameters),Y.startedAt=(ft=Y.startedAt)!=null?ft:Ke((sr=L.startedAt)!=null?sr:L.timestamp),Y.completedAt=void 0,Y.durationMs=void 0,se.toolCall=Y,se.streaming=!0;let te=L.agentContext;(te||L.executionId)&&(se.agentMetadata={executionId:(dr=te==null?void 0:te.executionId)!=null?dr:L.executionId,iteration:(wr=te==null?void 0:te.iteration)!=null?wr:L.iteration}),u(se)}else if(st==="tool_chunk"||st==="tool_delta"){let q=(Or=(Lr=xe(L,!1))!=null?Lr:xe(L,!0))!=null?Or:`tool-${l()}`;if(X.has(q))continue;let O=ke(q),se=(xt=O.toolCall)!=null?xt:{id:q,status:"running"};se.startedAt=(fr=se.startedAt)!=null?fr:Ke((sn=L.startedAt)!=null?sn:L.timestamp);let Y=(Zn=(Rr=(Un=L.text)!=null?Un:L.delta)!=null?Rr:L.message)!=null?Zn:"";Y&&(se.chunks=(Pn=se.chunks)!=null?Pn:[],se.chunks.push(String(Y))),se.status="running",O.toolCall=se,O.streaming=!0;let te=L.agentContext;(te||L.executionId)&&(O.agentMetadata=(P=O.agentMetadata)!=null?P:{executionId:(In=te==null?void 0:te.executionId)!=null?In:L.executionId,iteration:(ue=te==null?void 0:te.iteration)!=null?ue:L.iteration}),u(O)}else if(st==="tool_complete"){let q=(Se=(ee=xe(L,!1))!=null?ee:xe(L,!0))!=null?Se:`tool-${l()}`;if(X.has(q)){X.delete(q);continue}let O=ke(q),se=(rt=O.toolCall)!=null?rt:{id:q,status:"running"};se.status="complete",L.result!==void 0&&(se.result=L.result),typeof L.duration=="number"&&(se.duration=L.duration),se.completedAt=Ke((Qt=L.completedAt)!=null?Qt:L.timestamp);let Y=(Ft=L.duration)!=null?Ft:L.executionTime;if(typeof Y=="number")se.durationMs=Y;else{let et=(tr=se.startedAt)!=null?tr:Date.now();se.durationMs=Math.max(0,((Pr=se.completedAt)!=null?Pr:Date.now())-et)}O.toolCall=se,O.streaming=!1;let te=L.agentContext;(te||L.executionId)&&(O.agentMetadata=(Vt=O.agentMetadata)!=null?Vt:{executionId:(_r=te==null?void 0:te.executionId)!=null?_r:L.executionId,iteration:(wn=te==null?void 0:te.iteration)!=null?wn:L.iteration}),u(O);let ct=oe(L);ct&&T.byCall.delete(ct)}else if(st==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let q=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,O=($t=q!=null?q:L.toolId)!=null?$t:`local-${l()}`,se=ke(O),Y=(Ir=se.toolCall)!=null?Ir:{id:O,status:"pending"};Y.name=L.toolName,Y.args=L.parameters,Y.status="complete",Y.chunks=(vn=Y.chunks)!=null?vn:[],Y.startedAt=(eo=Y.startedAt)!=null?eo:Ke((bo=L.startedAt)!=null?bo:L.timestamp),Y.completedAt=(wo=Y.completedAt)!=null?wo:Y.startedAt,se.toolCall=Y,se.streaming=!1,se.agentMetadata={...se.agentMetadata,executionId:(ln=L.executionId)!=null?ln:(qn=se.agentMetadata)==null?void 0:qn.executionId,awaitingLocalTool:!0,...q?{webMcpToolCallId:q}:{}},u(se)}else if(st==="text_start"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let q=L.partId;if(q!==void 0&&S.current!==null&&q!==S.current){let O=f;O&&(O.streaming=!1,u(O),he=O,f=null,M=!0)}q!==void 0&&(S.current=q)}else if(st==="text_end"){if((Pt=L.toolContext)!=null&&Pt.toolId)continue;let q=f;q&&(q.streaming=!1,u(q),he=q,f=null,M=!0)}else if(st==="step_chunk"||st==="step_delta"){let q=L.stepType,O=L.executionType;if(q==="tool"||O==="context")continue;let se=L.toolContext;if(se!=null&&se.toolId){let et=String((hr=(gr=L.id)!=null?gr:se.stepId)!=null?hr:`step-${l()}`),mt=L.partId!==void 0&&L.partId!==null?String(L.partId):"",Fe=`${se.toolId}::${et}`,lt=w.get(Fe);if(mt!==""&<!==void 0&<!==""&<!==mt){let _t=h.get(W(se.toolId,et,lt));_t&&_t.streaming!==!1&&(_t.streaming=!1,u(_t))}mt!==""&&w.set(Fe,mt);let jt=B(se.toolId,et,mt,se.executionId),Sr=(Wn=(Cn=(vo=(dn=L.text)!=null?dn:L.delta)!=null?vo:L.content)!=null?Cn:L.chunk)!=null?Wn:"";Sr&&(jt.content+=String(Sr),jt.streaming=!0,u(jt)),L.isComplete&&(jt.streaming=!1,u(jt));continue}let Y=L.partId;if(Y!==void 0&&S.current!==null&&Y!==S.current){let et=f;et&&(et.streaming=!1,u(et),he=et,f=null,M=!0)}Y!==void 0&&(S.current=Y);let te=Y!==void 0&&(cn=Ce.get(Y))!=null?cn:je();Y!==void 0&&(te.partId||(te.partId=Y),Ce.set(Y,te));let ct=(to=(Bn=(pn=(I=L.text)!=null?I:L.delta)!=null?pn:L.content)!=null?Bn:L.chunk)!=null?to:"";if(ct){let et=typeof L.seq=="number"?L.seq:void 0,mt=Y!=null?Y:te.id,Fe=et!==void 0?tt(mt,et,String(ct)):((zn=le.get(te.id))!=null?zn:"")+ct;te.rawContent=Fe,re.has(te.id)||re.set(te.id,this.createStreamParser());let lt=re.get(te.id),jt=Fe.trim().startsWith("{")||Fe.trim().startsWith("[");if(jt&&le.set(te.id,Fe),lt.__isPlainTextParser===!0){te.content=et!==void 0?Fe:te.content+ct,le.delete(te.id),re.delete(te.id),te.rawContent=void 0,u(te);continue}let _t=lt.processChunk(Fe);if(_t instanceof Promise)_t.then(qt=>{var Nr;let Tr=typeof qt=="string"?qt:(Nr=qt==null?void 0:qt.text)!=null?Nr:null;if(Tr!==null&&Tr.trim()!=="")te.content=Tr,u(te);else if(!jt&&!Fe.trim().startsWith("<")){let Vr=f,xr=Vr&&Vr.id===te.id?Vr:te;xr.id===te.id&&(xr.content=et!==void 0?Fe:xr.content+ct,le.delete(xr.id),re.delete(xr.id),xr.rawContent=void 0,u(xr))}}).catch(()=>{te.content=et!==void 0?Fe:te.content+ct,le.delete(te.id),re.delete(te.id),te.rawContent=void 0,u(te)});else{let qt=typeof _t=="string"?_t:(Xa=_t==null?void 0:_t.text)!=null?Xa:null;qt!==null&&qt.trim()!==""?(te.content=qt,u(te)):!jt&&!Fe.trim().startsWith("<")&&(te.content=et!==void 0?Fe:te.content+ct,le.delete(te.id),re.delete(te.id),te.rawContent=void 0,u(te))}}if(L.isComplete){let et=(Dn=(Hn=L.result)==null?void 0:Hn.response)!=null?Dn:te.content;if(et){let mt=le.get(te.id),Fe=mt!=null?mt:ce(et);te.rawContent=Fe;let lt=re.get(te.id),jt=null,Sr=!1;if(lt&&(jt=lt.getExtractedText(),jt===null&&(jt=oa(Fe)),jt===null)){let _t=lt.processChunk(Fe);_t instanceof Promise?(Sr=!0,_t.then(qt=>{var Nr;let Tr=typeof qt=="string"?qt:(Nr=qt==null?void 0:qt.text)!=null?Nr:null;if(Tr!==null){let Vr=f;Vr&&Vr.id===te.id&&(Vr.content=Tr,Vr.streaming=!1,re.delete(Vr.id),le.delete(Vr.id),u(Vr))}})):jt=typeof _t=="string"?_t:(On=_t==null?void 0:_t.text)!=null?On:null}if(!Sr){jt!==null&&jt.trim()!==""?te.content=jt:le.has(te.id)||(te.content=ce(et));let _t=re.get(te.id);if(_t){let qt=(ro=_t.close)==null?void 0:ro.call(_t);qt instanceof Promise&&qt.catch(()=>{}),re.delete(te.id)}le.delete(te.id),te.streaming=!1,u(te)}}}}else if(st==="step_complete"){let q=L.stepType,O=L.executionType;if(q==="tool"||O==="context")continue;let se=L.toolContext;if(se!=null&&se.toolId){let et=String((ri=(Fo=L.id)!=null?Fo:se.stepId)!=null?ri:"");if(et){let mt=R(se.toolId,et);for(let[Fe,lt]of h)Fe.startsWith(mt)&<.streaming!==!1&&(lt.streaming=!1,u(lt));w.delete(`${se.toolId}::${et}`)}continue}let Y=L.stopReason;if(M){if(f!==null){let Fe=f;Y&&(Fe.stopReason=Y),re.delete(Fe.id),le.delete(Fe.id),Fe.streaming!==!1&&(Fe.streaming=!1,u(Fe))}let et=(Ja=L.result)==null?void 0:Ja.response,mt=he;mt&&(Y&&(mt.stopReason=Y),et!=null?Ne(mt,et):(re.delete(mt.id),le.delete(mt.id))),he=null;continue}let te=(ni=L.result)==null?void 0:ni.response,ct=je();if(Y&&(ct.stopReason=Y),te!=null){let et=re.get(ct.id),mt=!1,Fe=!1;if(et){let lt=et.getExtractedText(),jt=le.get(ct.id),Sr=jt!=null?jt:ce(te);if(ct.rawContent=Sr,lt!==null&<.trim()!=="")ct.content=lt,mt=!0;else{let _t=oa(Sr);if(_t!==null)ct.content=_t,mt=!0;else{let qt=et.processChunk(Sr);if(qt instanceof Promise)Fe=!0,qt.then(Tr=>{var Vr;let Nr=typeof Tr=="string"?Tr:(Vr=Tr==null?void 0:Tr.text)!=null?Vr:null;if(Nr!==null&&Nr.trim()!==""){let xr=f;xr&&xr.id===ct.id&&(xr.content=Nr,xr.streaming=!1,re.delete(xr.id),le.delete(xr.id),u(xr))}else{let xr=et.getExtractedText(),Sn=f;Sn&&Sn.id===ct.id&&(xr!==null&&xr.trim()!==""?Sn.content=xr:le.has(Sn.id)||(Sn.content=ce(te)),Sn.streaming=!1,re.delete(Sn.id),le.delete(Sn.id),u(Sn))}});else{let Tr=typeof qt=="string"?qt:(ha=qt==null?void 0:qt.text)!=null?ha:null;if(Tr!==null&&Tr.trim()!=="")ct.content=Tr,mt=!0;else{let Nr=et.getExtractedText();Nr!==null&&Nr.trim()!==""&&(ct.content=Nr,mt=!0)}}}}}if(!Fe){if(!ct.rawContent){let lt=le.get(ct.id);ct.rawContent=lt!=null?lt:ce(te)}if(!mt&&!le.has(ct.id)&&(ct.content=ce(te)),et){let lt=(Lt=et.close)==null?void 0:Lt.call(et);lt instanceof Promise&<.catch(()=>{})}re.delete(ct.id),le.delete(ct.id),ct.streaming=!1,u(ct)}}else re.delete(ct.id),le.delete(ct.id),ct.streaming=!1,u(ct)}else if(st==="flow_complete"){let q=(Qa=L.result)==null?void 0:Qa.response;if(M){if(f!==null){let O=f;re.delete(O.id),le.delete(O.id),O.streaming!==!1&&(O.streaming=!1,u(O))}}else if(q!=null){let O=je(),se=le.get(O.id),Y=se!=null?se:ce(q);O.rawContent=Y;let te=ce(q),ct=re.get(O.id);if(ct){let Fe=oa(Y);if(Fe!==null)te=Fe;else{let lt=ct.processChunk(Y);lt instanceof Promise&<.then(Sr=>{var qt;let _t=typeof Sr=="string"?Sr:(qt=Sr==null?void 0:Sr.text)!=null?qt:null;_t!==null&&(O.content=_t,O.streaming=!1,u(O))});let jt=ct.getExtractedText();jt!==null&&(te=jt)}}re.delete(O.id),le.delete(O.id);let et=te!==O.content,mt=O.streaming!==!1;et&&(O.content=te),O.streaming=!1,(et||mt)&&u(O)}else if(f!==null){let O=f;re.delete(O.id),le.delete(O.id),O.streaming!==!1&&(O.streaming=!1,u(O))}r({type:"status",status:"idle"})}else if(st==="agent_start")z={executionId:L.executionId,agentId:(An=L.agentId)!=null?An:"virtual",agentName:(tn=L.agentName)!=null?tn:"",status:"running",currentIteration:0,maxTurns:(oi=L.maxTurns)!=null?oi:1,startedAt:Ke(L.startedAt)};else if(st==="agent_iteration_start"){if(z&&(z.currentIteration=L.iteration),Ae==="separate"&&L.iteration>1){let q=f;q&&(q.streaming=!1,u(q),Re.set(L.iteration-1,q),f=null)}}else if(st==="agent_turn_start")y=null;else if(st==="agent_turn_delta"){if(L.contentType==="text"){let q=je();q.content+=(ai=L.delta)!=null?ai:"",q.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:z==null?void 0:z.agentName},y=q,u(q)}else if(L.contentType==="thinking"){let q=(xa=L.turnId)!=null?xa:`agent-think-${L.iteration}`,O=Ge(q);O.reasoning=(no=O.reasoning)!=null?no:{id:q,status:"streaming",chunks:[]},O.reasoning.chunks.push((si=L.delta)!=null?si:""),O.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(O)}else if(L.contentType==="tool_input"){let q=($o=L.toolCallId)!=null?$o:T.lastId;if(q){let O=E.get(q);O!=null&&O.toolCall&&(O.toolCall.chunks=(Ya=O.toolCall.chunks)!=null?Ya:[],O.toolCall.chunks.push((oo=L.delta)!=null?oo:""),u(O))}}}else if(st==="agent_turn_complete"){let q=L.turnId;if(q){let Y=k.get(q);if(Y!=null&&Y.reasoning){Y.reasoning.status="complete",Y.reasoning.completedAt=Ke(L.completedAt);let te=(Za=Y.reasoning.startedAt)!=null?Za:Date.now();Y.reasoning.durationMs=Math.max(0,((Co=Y.reasoning.completedAt)!=null?Co:Date.now())-te),Y.streaming=!1,u(Y)}}let O=L.stopReason,se=f!=null?f:y;if(O&&se!==null){let Y=L.turnId;(!Y||((Ao=se.agentMetadata)==null?void 0:Ao.turnId)===Y)&&(se.stopReason=O,u(se))}}else if(st==="agent_tool_start"){f&&(f.streaming=!1,u(f),f=null);let q=(ii=L.toolCallId)!=null?ii:`agent-tool-${l()}`;_e(oe(L),q);let O=ke(q),se=(li=O.toolCall)!=null?li:{id:q,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};se.name=(Uo=(rd=L.toolName)!=null?rd:L.name)!=null?Uo:se.name,se.status="running",L.parameters!==void 0&&(se.args=L.parameters),se.startedAt=Ke((So=L.startedAt)!=null?So:L.timestamp),O.toolCall=se,O.streaming=!0,O.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(O)}else if(st==="agent_tool_delta"){let q=(di=L.toolCallId)!=null?di:T.lastId;if(q){let O=(es=E.get(q))!=null?es:ke(q);O.toolCall&&(O.toolCall.chunks=(To=O.toolCall.chunks)!=null?To:[],O.toolCall.chunks.push((ci=L.delta)!=null?ci:""),O.toolCall.status="running",O.streaming=!0,u(O))}}else if(st==="agent_tool_complete"){let q=(ts=L.toolCallId)!=null?ts:T.lastId;if(q){let O=(ko=E.get(q))!=null?ko:ke(q);if(O.toolCall){O.toolCall.status="complete",L.result!==void 0&&(O.toolCall.result=L.result),typeof L.executionTime=="number"&&(O.toolCall.durationMs=L.executionTime),O.toolCall.completedAt=Ke((rs=L.completedAt)!=null?rs:L.timestamp),O.streaming=!1,u(O);let se=oe(L);se&&T.byCall.delete(se)}}}else if(st==="agent_media"){let q=Array.isArray(L.media)?L.media:[],O=[];for(let se of q){if(!se||typeof se!="object")continue;let Y=se,te=typeof Y.type=="string"?Y.type:void 0,ct=typeof Y.mediaType=="string"?Y.mediaType.toLowerCase():"",et=null,mt="";if(te==="media"){let Fe=typeof Y.data=="string"?Y.data:void 0;if(!Fe)continue;mt=ct.length>0?ct:"application/octet-stream",et=`data:${mt};base64,${Fe}`}else if(te==="image-url"){let Fe=typeof Y.url=="string"?Y.url:void 0;if(!Fe)continue;mt=ct,et=Fe}else if(te==="file-url"){let Fe=typeof Y.url=="string"?Y.url:void 0;if(!Fe)continue;mt=ct,et=Fe}else continue;if(et)if(te==="image-url"||mt.startsWith("image/"))O.push({type:"image",image:et,...mt?{mimeType:mt}:{}});else if(mt.startsWith("audio/"))O.push({type:"audio",audio:et,mimeType:mt});else if(mt.startsWith("video/"))O.push({type:"video",video:et,mimeType:mt});else{let Fe=mt||"application/octet-stream";O.push({type:"file",data:et,mimeType:Fe,filename:cw(Fe)})}}if(O.length>0){let se=l(),Y=L.toolCallId,ct={id:`agent-media-${typeof Y=="string"&&Y.length>0?`${Y}-${se}`:String(se)}`,role:"assistant",content:"",contentParts:O,createdAt:new Date().toISOString(),streaming:!1,sequence:se,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(ct);let et=f;et&&(et.streaming=!1,u(et)),f=null,A.current=null}}else if(st!=="agent_iteration_complete"){if(st==="agent_reflection"||st==="agent_reflect"){let q=`agent-reflection-${L.executionId}-${L.iteration}`,O={id:q,role:"assistant",content:(pi=L.reflection)!=null?pi:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:q,status:"complete",chunks:[(ao=L.reflection)!=null?ao:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(O)}else if(st==="agent_complete"){z&&(z.status=L.success?"complete":"error",z.completedAt=Ke(L.completedAt),z.stopReason=L.stopReason);let q=f;q&&(q.streaming=!1,u(q)),r({type:"status",status:"idle"})}else if(st==="agent_error"){let q=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:",q):r({type:"error",error:new Error(q)})}else if(st!=="agent_ping"){if(st==="agent_approval_start"){let q=(Kt=L.approvalId)!=null?Kt:`approval-${l()}`,O={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(ya=z==null?void 0:z.agentId)!=null?ya:"virtual",executionId:(ns=(ba=L.executionId)!=null?ba:z==null?void 0:z.executionId)!=null?ns:"",toolName:(Vn=L.toolName)!=null?Vn:"",toolType:L.toolType,description:(os=L.description)!=null?os:`Execute ${(fi=L.toolName)!=null?fi:"tool"}`,parameters:L.parameters}};u(O)}else if(st==="step_await"&&L.awaitReason==="approval_required"){let q=(as=L.approvalId)!=null?as:`approval-${l()}`,O={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(mi=z==null?void 0:z.agentId)!=null?mi:"virtual",executionId:(va=(wa=L.executionId)!=null?wa:z==null?void 0:z.executionId)!=null?va:"",toolName:(qo=L.toolName)!=null?qo:"",toolType:L.toolType,description:(hi=L.description)!=null?hi:`Execute ${(gi=L.toolName)!=null?gi:"tool"}`,parameters:L.parameters}};u(O)}else if(st==="agent_approval_complete"){let q=L.approvalId;if(q){let se={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:(ss=L.decision)!=null?ss:"approved",agentId:(is=z==null?void 0:z.agentId)!=null?is:"virtual",executionId:(ds=(ls=L.executionId)!=null?ls:z==null?void 0:z.executionId)!=null?ds:"",toolName:(zr=L.toolName)!=null?zr:"",description:(un=L.description)!=null?un:"",resolvedAt:Date.now()}};u(se)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let q=L.artifactType,O=String(L.id),se=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:O,artifactType:q,title:se,component:typeof L.component=="string"?L.component:void 0}),Te.set(O,{markdown:"",title:se}),!K.has(O)){K.add(O);let Y={id:`artifact-ref-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:O,title:se,artifactType:q,status:"streaming"}})};Ue.set(O,Y),u(Y)}}else if(st==="artifact_delta"){let q=String(L.id),O=typeof L.delta=="string"?L.delta:String((so=L.delta)!=null?so:"");r({type:"artifact_delta",id:q,artDelta:O});let se=Te.get(q);se&&(se.markdown+=O)}else if(st==="artifact_update"){let q=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:q,component:typeof L.component=="string"?L.component:void 0})}else if(st==="artifact_complete"){let q=String(L.id);r({type:"artifact_complete",id:q});let O=Ue.get(q);if(O){O.streaming=!1;try{let se=JSON.parse((yt=O.rawContent)!=null?yt:"{}");if(se.props){se.props.status="complete";let Y=Te.get(q);Y!=null&&Y.markdown&&(se.props.markdown=Y.markdown)}O.rawContent=JSON.stringify(se)}catch{}Te.delete(q),u(O),Ue.delete(q)}}}else if(st==="transcript_insert"){let q=L.message;if(!q||typeof q!="object")continue;let O=String((cs=q.id)!=null?cs:`msg-${l()}`),se=q.role,te={id:O,role:se==="user"?"user":se==="system"?"system":"assistant",content:typeof q.content=="string"?q.content:"",rawContent:typeof q.rawContent=="string"?q.rawContent:void 0,createdAt:typeof q.createdAt=="string"?q.createdAt:new Date().toISOString(),streaming:q.streaming===!0,...typeof q.variant=="string"?{variant:q.variant}:{},sequence:l()};if(u(te),te.rawContent)try{let ct=JSON.parse(te.rawContent),et=(zo=ct==null?void 0:ct.props)==null?void 0:zo.artifactId;typeof et=="string"&&K.add(et)}catch{}f=null,A.current=null,re.delete(O),le.delete(O)}else if(st==="error"||st==="step_error"||st==="dispatch_error"||st==="flow_error"){let q=null;if(L.error instanceof Error)q=L.error;else if(st==="dispatch_error"){let O=(_n=L.message)!=null?_n:L.error;O!=null&&O!==""&&(q=new Error(String(O)))}else if(st==="step_error"||st==="flow_error"){let O=L.error;typeof O=="string"&&O!==""?q=new Error(O):O!=null&&typeof O=="object"&&"message"in O&&(q=new Error(String((xi=O.message)!=null?xi:O)))}else st==="error"&&L.error!=null&&L.error!==""&&(q=new Error(String(L.error)));if(q){r({type:"error",error:q});let O=f;O&&O.streaming&&(O.streaming=!1,u(O)),r({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:N,value:Me}=await o.read();if(N)break;a+=s.decode(Me,{stream:!0});let He=a.split(`
|
|
59
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async n=>{if(n.length<=e)return t!==null?{text:t,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(n);return s!==null&&(t=s),e=n.length,t!==null?{text:t,raw:n}:null},close:async()=>{}}},aa=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Ki=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Xi=()=>{var e;let t=cw();return{processChunk:async r=>{let n=r.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},Ji=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,fo.parse)(r,fo.STR|fo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?zi(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=zi(o.text)))}catch{}return e=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Bh=t=>{let e=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?zi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let i=(0,fo.parse)(s,fo.STR|fo.OBJ),d=o(i);d!==null&&(e=d)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Qi=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let n=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(t=n[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Yi=class{constructor(e,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=r}push(e,r){var s,a,i;let n=(i=(s=r==null?void 0:r.seq)!=null?s:r==null?void 0:r.sequenceIndex)!=null?i:(a=r==null?void 0:r.agentContext)==null?void 0:a.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(e,r),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(e,r);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:e,payload:r,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((r,n)=>r[0]-n[0]);for(let[r,n]of e)this.buffer.delete(r),this.emitter(n.payloadType,n.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var pw="https://api.runtype.com/v1/dispatch",Zi="https://api.runtype.com";function uw(t){var s,a;let e=t.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(n)return`attachment.${n}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Bd=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function fw(t){switch(t){case"json":return Ji;case"regex-json":return Xi;case"xml":return Qi;default:return Ki}}var Hh=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function mw(t,e){if(!t)return e;let r=t.trim(),n=e.trim();if(r.length===0)return e;if(n.length===0)return t;let o=Hh(r);if(!Hh(n))return t;if(!o||n===r||n.startsWith(r))return e;let a=aa(t);return aa(e)!==null&&a===null?e:t}var sa=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,n,o,s;this.apiUrl=(r=e.apiUrl)!=null?r:pw,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:fw(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Ia(e.webmcp):null}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,r,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,r,n):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Zi}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,this.resetClientToolsFingerprint(),(r=(e=this.config).onSessionInit)==null||r.call(e,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Zi}/v1/client/feedback`}async sendFeedback(e){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:r})}async submitCSATFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:e,comment:r})}async submitNPSFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:e,comment:r})}async dispatch(e,r){return this.isAgentMode()?this.dispatchAgent(e,r):this.isClientTokenMode()?this.dispatchClientToken(e,r):this.dispatchProxy(e,r)}async dispatchClientToken(e,r){var o,s,a,i;let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}let l=await this.buildPayload(e.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Bd).map(h=>{var w,y,E;return{id:h.id,role:h.role,content:(E=(y=(w=h.contentParts)!=null?w:h.llmContent)!=null?y:h.rawContent)!=null?E:h.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,f=!!(u&&u.length>0),x=f?Ph(u):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,S=f&&C&&this.lastSentClientToolsFingerprint===x,k=!1,T=null,M;for(let h=0;;h++){let y={...m,...f&&(k||!S)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",y),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y),signal:n.signal}),M.status===409&&h===0&&f){let E=await M.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){k=!0,this.lastSentClientToolsFingerprint=null;continue}T=E!=null?E:{error:"Chat request failed"}}break}if(!M.ok){let h=T!=null?T:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(M.status===429){let y=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let w=new Error(h.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!M.body){let h=new Error("No response body received");throw r({type:"error",error:h}),h}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(M.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(e,r,n){r({type:"status",status:"connected"});try{await this.streamResponse(e,r,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(e,r){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Zi}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(e,r,n){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Zi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:r,streamResponse:(p=n==null?void 0:n.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(e){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Bd).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),n={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}return n}async buildPayload(e){var s;let n={messages:e.slice().filter(Bd).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...n},config:this.config});if(a&&typeof a=="object"){let i=a;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return n}async handleCustomSSEEvent(e,r,n,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return n.current=m,o(m),m},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),a.current=null,r({type:"status",status:"idle"})),i.error&&(a.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r,n){var fe,pe,Be,Q;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,He=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,Ve=_.tools?_.tools.map(Je=>({...Je,chunks:Je.chunks?[...Je.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:He,tools:Ve}},m=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,He=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||He||!!_.stopReason},u=_=>{m(_)&&r({type:"message",message:p(_)})},f=null,x=null,C={current:null},S={current:null},k=!1,T=new Map,M=new Map,h=new Map,w=new Map,y={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},B=(_,ke,He="")=>`${_}::${ke}::${He}`,P=(_,ke)=>`${_}::${ke}::`,R=(_,ke,He,Ve)=>{let Je=B(_,ke,He),gt=h.get(Je);if(gt)return gt;let at=He?`-${He}`:"",Mt={id:`nested-${_}-${ke}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Ve,parentToolId:_,parentStepId:ke}};return h.set(Je,Mt),u(Mt),Mt},O=_=>{if(_==null)return null;try{return String(_)}catch{return null}},V=_=>{var ke,He,Ve,Je,gt;return O((gt=(Je=(Ve=(He=(ke=_.stepId)!=null?ke:_.step_id)!=null?He:_.step)!=null?Ve:_.parentId)!=null?Je:_.flowStepId)!=null?gt:_.flow_step_id)},ne=_=>{var ke,He,Ve,Je,gt,at,Mt;return O((Mt=(at=(gt=(Je=(Ve=(He=(ke=_.callId)!=null?ke:_.call_id)!=null?He:_.requestId)!=null?Ve:_.request_id)!=null?Je:_.toolCallId)!=null?gt:_.tool_call_id)!=null?at:_.stepId)!=null?Mt:_.step_id)},be=n,Ye=!1,Ge=()=>{if(f)return f;let _;return!Ye&&be?(_=be,Ye=!0):be&&S.current?_=`${be}_${S.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(f),f},ve=(_,ke)=>{y.lastId=ke,_&&y.byStep.set(_,ke)},Ee=(_,ke)=>{var gt;let He=(gt=_.reasoningId)!=null?gt:_.id,Ve=V(_);if(He){let at=String(He);return ve(Ve,at),at}if(Ve){let at=y.byStep.get(Ve);if(at)return y.lastId=at,at}if(y.lastId&&!ke)return y.lastId;if(!ke)return null;let Je=`reason-${l()}`;return ve(Ve,Je),Je},Ke=_=>{let ke=T.get(_);if(ke)return ke;let He={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return T.set(_,He),u(He),He},Ne=(_,ke)=>{E.lastId=ke,_&&E.byCall.set(_,ke)},X=new Set,Ue=new Map,K=new Set,Te=new Map,oe=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},xe=(_,ke)=>{var gt;let He=(gt=_.toolId)!=null?gt:_.id,Ve=ne(_);if(He){let at=String(He);return Ne(Ve,at),at}if(Ve){let at=E.byCall.get(Ve);if(at)return E.lastId=at,at}if(E.lastId&&!ke)return E.lastId;if(!ke)return null;let Je=`tool-${l()}`;return Ne(Ve,Je),Je},Me=_=>{let ke=M.get(_);if(ke)return ke;let He={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return M.set(_,He),u(He),He},Xe=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let He=Date.parse(_);if(!Number.isNaN(He))return He}return Date.now()},ce=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},te=new Map,le=new Map,ut=new Map,Ce=new Map,he=null,rt=(_,ke,He)=>{var Mt;let Ve=ut.get(_);Ve||(Ve=[],ut.set(_,Ve));let Je=0,gt=Ve.length;for(;Je<gt;){let Xt=Je+gt>>>1;Ve[Xt].seq<ke?Je=Xt+1:gt=Xt}((Mt=Ve[Je])==null?void 0:Mt.seq)===ke?Ve[Je]={seq:ke,text:He}:Ve.splice(Je,0,{seq:ke,text:He});let at="";for(let Xt=0;Xt<Ve.length;Xt++)at+=Ve[Xt].text;return at},_e=(_,ke)=>{let He=ce(ke),Ve=le.get(_.id),Je=mw(Ve,He);_.rawContent=Je;let gt=te.get(_.id),at=st=>{var de;let _t=(de=_.content)!=null?de:"";st.trim()!==""&&(_t.trim().length===0||st.startsWith(_t)||st.trimStart().startsWith(_t.trim()))&&(_.content=st)},Mt=()=>{var st;if(gt){let _t=(st=gt.close)==null?void 0:st.call(gt);_t instanceof Promise&&_t.catch(()=>{})}te.delete(_.id),le.delete(_.id),_.streaming=!1,u(_)};if(!gt){at(He),Mt();return}let Xt=aa(Je);if(Xt!==null&&Xt.trim()!==""){at(Xt),Mt();return}let G=st=>{var ye;let _t=typeof st=="string"?st:(ye=st==null?void 0:st.text)!=null?ye:null;if(_t!==null&&_t.trim()!=="")return _t;let de=gt.getExtractedText();return de!==null&&de.trim()!==""?de:He},Jt;try{Jt=gt.processChunk(Je)}catch{at(He),Mt();return}if(Jt instanceof Promise){Jt.then(st=>{at(G(st)),Mt()}).catch(()=>{at(He),Mt()});return}at(G(Jt)),Mt()},me=[],J=!1,ze,Z=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ze()}))},ge=new Yi((_,ke)=>{me.push({payloadType:_,payload:ke}),Z()}),z=null,Re=new Map,Ae=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(ze=()=>{var _,ke,He,Ve,Je,gt,at,Mt,Xt,G,Jt,st,_t,de,ye,Rt,ar,kt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,I,ee,Se,nt,Qt,Ft,tr,Pr,Nr,wn,Vt,$t,Ir,vn,bo,eo,wo,qn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn,W,pn,Bn,to,zn,Ja,Hn,Dn,On,ro,$o,ni,Qa,oi,xa,Lt,Ya,An,tn,ai,si,ya,no,ii,Uo,Za,oo,es,Co,Ao,li,di,nd,qo,So,ci,ts,To,pi,rs,Mo,ns,ui,ao,fi,ko,Kt,ba,wa,os,Vn,mi,as,ss,gi,va,Ca,zo,hi,xi,is,ls,ds,cs,zr,un,so,yt,ps,Vo,Nn,yi;for(let Eo=0;Eo<me.length;Eo++){let it=me[Eo].payloadType,L=me[Eo].payload;if(it==="reason_start"){let q=(_=Ee(L,!0))!=null?_:`reason-${l()}`,N=Ke(q);N.reasoning=(ke=N.reasoning)!=null?ke:{id:q,status:"streaming",chunks:[]},N.reasoning.startedAt=(Ve=N.reasoning.startedAt)!=null?Ve:Xe((He=L.startedAt)!=null?He:L.timestamp),N.reasoning.completedAt=void 0,N.reasoning.durationMs=void 0,N.streaming=!0,N.reasoning.status="streaming",u(N)}else if(it==="reason_delta"||it==="reason_chunk"){let q=(gt=(Je=Ee(L,!1))!=null?Je:Ee(L,!0))!=null?gt:`reason-${l()}`,N=Ke(q);N.reasoning=(at=N.reasoning)!=null?at:{id:q,status:"streaming",chunks:[]},N.reasoning.startedAt=(Xt=N.reasoning.startedAt)!=null?Xt:Xe((Mt=L.startedAt)!=null?Mt:L.timestamp);let ae=(st=(Jt=(G=L.reasoningText)!=null?G:L.text)!=null?Jt:L.delta)!=null?st:"";if(ae&&L.hidden!==!0){let ie=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(ie!==void 0){let Y=rt(q,ie,String(ae));N.reasoning.chunks=[Y]}else N.reasoning.chunks.push(String(ae))}if(N.reasoning.status=L.done?"complete":"streaming",L.done){N.reasoning.completedAt=Xe((_t=L.completedAt)!=null?_t:L.timestamp);let ie=(de=N.reasoning.startedAt)!=null?de:Date.now();N.reasoning.durationMs=Math.max(0,((ye=N.reasoning.completedAt)!=null?ye:Date.now())-ie)}N.streaming=N.reasoning.status!=="complete",u(N)}else if(it==="reason_complete"){let q=(ar=(Rt=Ee(L,!1))!=null?Rt:Ee(L,!0))!=null?ar:`reason-${l()}`,N=T.get(q);if(N!=null&&N.reasoning){N.reasoning.status="complete",N.reasoning.completedAt=Xe((kt=L.completedAt)!=null?kt:L.timestamp);let ie=(mr=N.reasoning.startedAt)!=null?mr:Date.now();N.reasoning.durationMs=Math.max(0,((Ot=N.reasoning.completedAt)!=null?Ot:Date.now())-ie),N.streaming=!1,u(N)}let ae=V(L);ae&&y.byStep.delete(ae)}else if(it==="tool_start"){let q=(Wt=xe(L,!0))!=null?Wt:`tool-${l()}`,N=(St=L.toolName)!=null?St:L.name;if(oe(N)){X.add(q);continue}let ae=Me(q),ie=(Et=ae.toolCall)!=null?Et:{id:q,status:"pending"};ie.name=N!=null?N:ie.name,ie.status="running",L.args!==void 0?ie.args=L.args:L.parameters!==void 0&&(ie.args=L.parameters),ie.startedAt=(ft=ie.startedAt)!=null?ft:Xe((sr=L.startedAt)!=null?sr:L.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,ae.toolCall=ie,ae.streaming=!0;let Y=L.agentContext;(Y||L.executionId)&&(ae.agentMetadata={executionId:(dr=Y==null?void 0:Y.executionId)!=null?dr:L.executionId,iteration:(wr=Y==null?void 0:Y.iteration)!=null?wr:L.iteration}),u(ae)}else if(it==="tool_chunk"||it==="tool_delta"){let q=(Or=(Lr=xe(L,!1))!=null?Lr:xe(L,!0))!=null?Or:`tool-${l()}`;if(X.has(q))continue;let N=Me(q),ae=(xt=N.toolCall)!=null?xt:{id:q,status:"running"};ae.startedAt=(fr=ae.startedAt)!=null?fr:Xe((sn=L.startedAt)!=null?sn:L.timestamp);let ie=(Zn=(Rr=(Un=L.text)!=null?Un:L.delta)!=null?Rr:L.message)!=null?Zn:"";ie&&(ae.chunks=(Pn=ae.chunks)!=null?Pn:[],ae.chunks.push(String(ie))),ae.status="running",N.toolCall=ae,N.streaming=!0;let Y=L.agentContext;(Y||L.executionId)&&(N.agentMetadata=(I=N.agentMetadata)!=null?I:{executionId:(In=Y==null?void 0:Y.executionId)!=null?In:L.executionId,iteration:(ue=Y==null?void 0:Y.iteration)!=null?ue:L.iteration}),u(N)}else if(it==="tool_complete"){let q=(Se=(ee=xe(L,!1))!=null?ee:xe(L,!0))!=null?Se:`tool-${l()}`;if(X.has(q)){X.delete(q);continue}let N=Me(q),ae=(nt=N.toolCall)!=null?nt:{id:q,status:"running"};ae.status="complete",L.result!==void 0&&(ae.result=L.result),typeof L.duration=="number"&&(ae.duration=L.duration),ae.completedAt=Xe((Qt=L.completedAt)!=null?Qt:L.timestamp);let ie=(Ft=L.duration)!=null?Ft:L.executionTime;if(typeof ie=="number")ae.durationMs=ie;else{let tt=(tr=ae.startedAt)!=null?tr:Date.now();ae.durationMs=Math.max(0,((Pr=ae.completedAt)!=null?Pr:Date.now())-tt)}N.toolCall=ae,N.streaming=!1;let Y=L.agentContext;(Y||L.executionId)&&(N.agentMetadata=(Vt=N.agentMetadata)!=null?Vt:{executionId:(Nr=Y==null?void 0:Y.executionId)!=null?Nr:L.executionId,iteration:(wn=Y==null?void 0:Y.iteration)!=null?wn:L.iteration}),u(N);let je=ne(L);je&&E.byCall.delete(je)}else if(it==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let q=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,N=($t=q!=null?q:L.toolId)!=null?$t:`local-${l()}`,ae=Me(N),ie=L.toolName,Y=Io(ie),je=(Ir=ae.toolCall)!=null?Ir:{id:N,status:"pending"};je.name=ie,je.args=L.parameters,je.status=Y?"running":"complete",je.chunks=(vn=je.chunks)!=null?vn:[],je.startedAt=(eo=je.startedAt)!=null?eo:Xe((bo=L.startedAt)!=null?bo:L.timestamp),Y?(je.completedAt=void 0,je.duration=void 0,je.durationMs=void 0):je.completedAt=(wo=je.completedAt)!=null?wo:je.startedAt,ae.toolCall=je,ae.streaming=!1,ae.agentMetadata={...ae.agentMetadata,executionId:(ln=L.executionId)!=null?ln:(qn=ae.agentMetadata)==null?void 0:qn.executionId,awaitingLocalTool:!0,...q?{webMcpToolCallId:q}:{}},u(ae)}else if(it==="text_start"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let q=L.partId;if(q!==void 0&&S.current!==null&&q!==S.current){let N=f;N&&(N.streaming=!1,u(N),he=N,f=null,k=!0)}q!==void 0&&(S.current=q)}else if(it==="text_end"){if((Pt=L.toolContext)!=null&&Pt.toolId)continue;let q=f;q&&(q.streaming=!1,u(q),he=q,f=null,k=!0)}else if(it==="step_chunk"||it==="step_delta"){let q=L.stepType,N=L.executionType;if(q==="tool"||N==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let tt=String((hr=(gr=L.id)!=null?gr:ae.stepId)!=null?hr:`step-${l()}`),mt=L.partId!==void 0&&L.partId!==null?String(L.partId):"",Fe=`${ae.toolId}::${tt}`,dt=w.get(Fe);if(mt!==""&&dt!==void 0&&dt!==""&&dt!==mt){let Nt=h.get(B(ae.toolId,tt,dt));Nt&&Nt.streaming!==!1&&(Nt.streaming=!1,u(Nt))}mt!==""&&w.set(Fe,mt);let jt=R(ae.toolId,tt,mt,ae.executionId),Sr=(Wn=(Cn=(vo=(dn=L.text)!=null?dn:L.delta)!=null?vo:L.content)!=null?Cn:L.chunk)!=null?Wn:"";Sr&&(jt.content+=String(Sr),jt.streaming=!0,u(jt)),L.isComplete&&(jt.streaming=!1,u(jt));continue}let ie=L.partId;if(ie!==void 0&&S.current!==null&&ie!==S.current){let tt=f;tt&&(tt.streaming=!1,u(tt),he=tt,f=null,k=!0)}ie!==void 0&&(S.current=ie);let Y=ie!==void 0&&(cn=Ce.get(ie))!=null?cn:Ge();ie!==void 0&&(Y.partId||(Y.partId=ie),Ce.set(ie,Y));let je=(to=(Bn=(pn=(W=L.text)!=null?W:L.delta)!=null?pn:L.content)!=null?Bn:L.chunk)!=null?to:"";if(je){let tt=typeof L.seq=="number"?L.seq:void 0,mt=ie!=null?ie:Y.id,Fe=tt!==void 0?rt(mt,tt,String(je)):((zn=le.get(Y.id))!=null?zn:"")+je;Y.rawContent=Fe,te.has(Y.id)||te.set(Y.id,this.createStreamParser());let dt=te.get(Y.id),jt=Fe.trim().startsWith("{")||Fe.trim().startsWith("[");if(jt&&le.set(Y.id,Fe),dt.__isPlainTextParser===!0){Y.content=tt!==void 0?Fe:Y.content+je,le.delete(Y.id),te.delete(Y.id),Y.rawContent=void 0,u(Y);continue}let Nt=dt.processChunk(Fe);if(Nt instanceof Promise)Nt.then(qt=>{var _r;let Tr=typeof qt=="string"?qt:(_r=qt==null?void 0:qt.text)!=null?_r:null;if(Tr!==null&&Tr.trim()!=="")Y.content=Tr,u(Y);else if(!jt&&!Fe.trim().startsWith("<")){let Vr=f,xr=Vr&&Vr.id===Y.id?Vr:Y;xr.id===Y.id&&(xr.content=tt!==void 0?Fe:xr.content+je,le.delete(xr.id),te.delete(xr.id),xr.rawContent=void 0,u(xr))}}).catch(()=>{Y.content=tt!==void 0?Fe:Y.content+je,le.delete(Y.id),te.delete(Y.id),Y.rawContent=void 0,u(Y)});else{let qt=typeof Nt=="string"?Nt:(Ja=Nt==null?void 0:Nt.text)!=null?Ja:null;qt!==null&&qt.trim()!==""?(Y.content=qt,u(Y)):!jt&&!Fe.trim().startsWith("<")&&(Y.content=tt!==void 0?Fe:Y.content+je,le.delete(Y.id),te.delete(Y.id),Y.rawContent=void 0,u(Y))}}if(L.isComplete){let tt=(Dn=(Hn=L.result)==null?void 0:Hn.response)!=null?Dn:Y.content;if(tt){let mt=le.get(Y.id),Fe=mt!=null?mt:ce(tt);Y.rawContent=Fe;let dt=te.get(Y.id),jt=null,Sr=!1;if(dt&&(jt=dt.getExtractedText(),jt===null&&(jt=aa(Fe)),jt===null)){let Nt=dt.processChunk(Fe);Nt instanceof Promise?(Sr=!0,Nt.then(qt=>{var _r;let Tr=typeof qt=="string"?qt:(_r=qt==null?void 0:qt.text)!=null?_r:null;if(Tr!==null){let Vr=f;Vr&&Vr.id===Y.id&&(Vr.content=Tr,Vr.streaming=!1,te.delete(Vr.id),le.delete(Vr.id),u(Vr))}})):jt=typeof Nt=="string"?Nt:(On=Nt==null?void 0:Nt.text)!=null?On:null}if(!Sr){jt!==null&&jt.trim()!==""?Y.content=jt:le.has(Y.id)||(Y.content=ce(tt));let Nt=te.get(Y.id);if(Nt){let qt=(ro=Nt.close)==null?void 0:ro.call(Nt);qt instanceof Promise&&qt.catch(()=>{}),te.delete(Y.id)}le.delete(Y.id),Y.streaming=!1,u(Y)}}}}else if(it==="step_complete"){let q=L.stepType,N=L.executionType;if(q==="tool"||N==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let tt=String((ni=($o=L.id)!=null?$o:ae.stepId)!=null?ni:"");if(tt){let mt=P(ae.toolId,tt);for(let[Fe,dt]of h)Fe.startsWith(mt)&&dt.streaming!==!1&&(dt.streaming=!1,u(dt));w.delete(`${ae.toolId}::${tt}`)}continue}let ie=L.stopReason;if(k){if(f!==null){let Fe=f;ie&&(Fe.stopReason=ie),te.delete(Fe.id),le.delete(Fe.id),Fe.streaming!==!1&&(Fe.streaming=!1,u(Fe))}let tt=(Qa=L.result)==null?void 0:Qa.response,mt=he;mt&&(ie&&(mt.stopReason=ie),tt!=null?_e(mt,tt):(te.delete(mt.id),le.delete(mt.id))),he=null;continue}let Y=(oi=L.result)==null?void 0:oi.response,je=Ge();if(ie&&(je.stopReason=ie),Y!=null){let tt=te.get(je.id),mt=!1,Fe=!1;if(tt){let dt=tt.getExtractedText(),jt=le.get(je.id),Sr=jt!=null?jt:ce(Y);if(je.rawContent=Sr,dt!==null&&dt.trim()!=="")je.content=dt,mt=!0;else{let Nt=aa(Sr);if(Nt!==null)je.content=Nt,mt=!0;else{let qt=tt.processChunk(Sr);if(qt instanceof Promise)Fe=!0,qt.then(Tr=>{var Vr;let _r=typeof Tr=="string"?Tr:(Vr=Tr==null?void 0:Tr.text)!=null?Vr:null;if(_r!==null&&_r.trim()!==""){let xr=f;xr&&xr.id===je.id&&(xr.content=_r,xr.streaming=!1,te.delete(xr.id),le.delete(xr.id),u(xr))}else{let xr=tt.getExtractedText(),Sn=f;Sn&&Sn.id===je.id&&(xr!==null&&xr.trim()!==""?Sn.content=xr:le.has(Sn.id)||(Sn.content=ce(Y)),Sn.streaming=!1,te.delete(Sn.id),le.delete(Sn.id),u(Sn))}});else{let Tr=typeof qt=="string"?qt:(xa=qt==null?void 0:qt.text)!=null?xa:null;if(Tr!==null&&Tr.trim()!=="")je.content=Tr,mt=!0;else{let _r=tt.getExtractedText();_r!==null&&_r.trim()!==""&&(je.content=_r,mt=!0)}}}}}if(!Fe){if(!je.rawContent){let dt=le.get(je.id);je.rawContent=dt!=null?dt:ce(Y)}if(!mt&&!le.has(je.id)&&(je.content=ce(Y)),tt){let dt=(Lt=tt.close)==null?void 0:Lt.call(tt);dt instanceof Promise&&dt.catch(()=>{})}te.delete(je.id),le.delete(je.id),je.streaming=!1,u(je)}}else te.delete(je.id),le.delete(je.id),je.streaming=!1,u(je)}else if(it==="flow_complete"){let q=(Ya=L.result)==null?void 0:Ya.response;if(k){if(f!==null){let N=f;te.delete(N.id),le.delete(N.id),N.streaming!==!1&&(N.streaming=!1,u(N))}}else if(q!=null){let N=Ge(),ae=le.get(N.id),ie=ae!=null?ae:ce(q);N.rawContent=ie;let Y=ce(q),je=te.get(N.id);if(je){let Fe=aa(ie);if(Fe!==null)Y=Fe;else{let dt=je.processChunk(ie);dt instanceof Promise&&dt.then(Sr=>{var qt;let Nt=typeof Sr=="string"?Sr:(qt=Sr==null?void 0:Sr.text)!=null?qt:null;Nt!==null&&(N.content=Nt,N.streaming=!1,u(N))});let jt=je.getExtractedText();jt!==null&&(Y=jt)}}te.delete(N.id),le.delete(N.id);let tt=Y!==N.content,mt=N.streaming!==!1;tt&&(N.content=Y),N.streaming=!1,(tt||mt)&&u(N)}else if(f!==null){let N=f;te.delete(N.id),le.delete(N.id),N.streaming!==!1&&(N.streaming=!1,u(N))}r({type:"status",status:"idle"})}else if(it==="agent_start")z={executionId:L.executionId,agentId:(An=L.agentId)!=null?An:"virtual",agentName:(tn=L.agentName)!=null?tn:"",status:"running",currentIteration:0,maxTurns:(ai=L.maxTurns)!=null?ai:1,startedAt:Xe(L.startedAt)};else if(it==="agent_iteration_start"){if(z&&(z.currentIteration=L.iteration),Ae==="separate"&&L.iteration>1){let q=f;q&&(q.streaming=!1,u(q),Re.set(L.iteration-1,q),f=null)}}else if(it==="agent_turn_start")x=null;else if(it==="agent_turn_delta"){if(L.contentType==="text"){let q=Ge();q.content+=(si=L.delta)!=null?si:"",q.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:z==null?void 0:z.agentName},x=q,u(q)}else if(L.contentType==="thinking"){let q=(ya=L.turnId)!=null?ya:`agent-think-${L.iteration}`,N=Ke(q);N.reasoning=(no=N.reasoning)!=null?no:{id:q,status:"streaming",chunks:[]},N.reasoning.chunks.push((ii=L.delta)!=null?ii:""),N.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(N)}else if(L.contentType==="tool_input"){let q=(Uo=L.toolCallId)!=null?Uo:E.lastId;if(q){let N=M.get(q);N!=null&&N.toolCall&&(N.toolCall.chunks=(Za=N.toolCall.chunks)!=null?Za:[],N.toolCall.chunks.push((oo=L.delta)!=null?oo:""),u(N))}}}else if(it==="agent_turn_complete"){let q=L.turnId;if(q){let ie=T.get(q);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Xe(L.completedAt);let Y=(es=ie.reasoning.startedAt)!=null?es:Date.now();ie.reasoning.durationMs=Math.max(0,((Co=ie.reasoning.completedAt)!=null?Co:Date.now())-Y),ie.streaming=!1,u(ie)}}let N=L.stopReason,ae=f!=null?f:x;if(N&&ae!==null){let ie=L.turnId;(!ie||((Ao=ae.agentMetadata)==null?void 0:Ao.turnId)===ie)&&(ae.stopReason=N,u(ae))}}else if(it==="agent_tool_start"){f&&(f.streaming=!1,u(f),f=null);let q=(li=L.toolCallId)!=null?li:`agent-tool-${l()}`;Ne(ne(L),q);let N=Me(q),ae=(di=N.toolCall)!=null?di:{id:q,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};ae.name=(qo=(nd=L.toolName)!=null?nd:L.name)!=null?qo:ae.name,ae.status="running",L.parameters!==void 0&&(ae.args=L.parameters),ae.startedAt=Xe((So=L.startedAt)!=null?So:L.timestamp),N.toolCall=ae,N.streaming=!0,N.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(N)}else if(it==="agent_tool_delta"){let q=(ci=L.toolCallId)!=null?ci:E.lastId;if(q){let N=(ts=M.get(q))!=null?ts:Me(q);N.toolCall&&(N.toolCall.chunks=(To=N.toolCall.chunks)!=null?To:[],N.toolCall.chunks.push((pi=L.delta)!=null?pi:""),N.toolCall.status="running",N.streaming=!0,u(N))}}else if(it==="agent_tool_complete"){let q=(rs=L.toolCallId)!=null?rs:E.lastId;if(q){let N=(Mo=M.get(q))!=null?Mo:Me(q);if(N.toolCall){N.toolCall.status="complete",L.result!==void 0&&(N.toolCall.result=L.result),typeof L.executionTime=="number"&&(N.toolCall.durationMs=L.executionTime),N.toolCall.completedAt=Xe((ns=L.completedAt)!=null?ns:L.timestamp),N.streaming=!1,u(N);let ae=ne(L);ae&&E.byCall.delete(ae)}}}else if(it==="agent_media"){let q=Array.isArray(L.media)?L.media:[],N=[];for(let ae of q){if(!ae||typeof ae!="object")continue;let ie=ae,Y=typeof ie.type=="string"?ie.type:void 0,je=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",tt=null,mt="";if(Y==="media"){let Fe=typeof ie.data=="string"?ie.data:void 0;if(!Fe)continue;mt=je.length>0?je:"application/octet-stream",tt=`data:${mt};base64,${Fe}`}else if(Y==="image-url"){let Fe=typeof ie.url=="string"?ie.url:void 0;if(!Fe)continue;mt=je,tt=Fe}else if(Y==="file-url"){let Fe=typeof ie.url=="string"?ie.url:void 0;if(!Fe)continue;mt=je,tt=Fe}else continue;if(tt)if(Y==="image-url"||mt.startsWith("image/"))N.push({type:"image",image:tt,...mt?{mimeType:mt}:{}});else if(mt.startsWith("audio/"))N.push({type:"audio",audio:tt,mimeType:mt});else if(mt.startsWith("video/"))N.push({type:"video",video:tt,mimeType:mt});else{let Fe=mt||"application/octet-stream";N.push({type:"file",data:tt,mimeType:Fe,filename:uw(Fe)})}}if(N.length>0){let ae=l(),ie=L.toolCallId,je={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${ae}`:String(ae)}`,role:"assistant",content:"",contentParts:N,createdAt:new Date().toISOString(),streaming:!1,sequence:ae,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(je);let tt=f;tt&&(tt.streaming=!1,u(tt)),f=null,C.current=null}}else if(it!=="agent_iteration_complete"){if(it==="agent_reflection"||it==="agent_reflect"){let q=`agent-reflection-${L.executionId}-${L.iteration}`,N={id:q,role:"assistant",content:(ui=L.reflection)!=null?ui:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:q,status:"complete",chunks:[(ao=L.reflection)!=null?ao:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(N)}else if(it==="agent_complete"){z&&(z.status=L.success?"complete":"error",z.completedAt=Xe(L.completedAt),z.stopReason=L.stopReason);let q=f;q&&(q.streaming=!1,u(q)),r({type:"status",status:"idle"})}else if(it==="agent_error"){let q=typeof L.error=="string"?L.error:(ko=(fi=L.error)==null?void 0:fi.message)!=null?ko:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",q):r({type:"error",error:new Error(q)})}else if(it!=="agent_ping"){if(it==="agent_approval_start"){let q=(Kt=L.approvalId)!=null?Kt:`approval-${l()}`,N={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(ba=z==null?void 0:z.agentId)!=null?ba:"virtual",executionId:(os=(wa=L.executionId)!=null?wa:z==null?void 0:z.executionId)!=null?os:"",toolName:(Vn=L.toolName)!=null?Vn:"",toolType:L.toolType,description:(as=L.description)!=null?as:`Execute ${(mi=L.toolName)!=null?mi:"tool"}`,parameters:L.parameters}};u(N)}else if(it==="step_await"&&L.awaitReason==="approval_required"){let q=(ss=L.approvalId)!=null?ss:`approval-${l()}`,N={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(gi=z==null?void 0:z.agentId)!=null?gi:"virtual",executionId:(Ca=(va=L.executionId)!=null?va:z==null?void 0:z.executionId)!=null?Ca:"",toolName:(zo=L.toolName)!=null?zo:"",toolType:L.toolType,description:(xi=L.description)!=null?xi:`Execute ${(hi=L.toolName)!=null?hi:"tool"}`,parameters:L.parameters}};u(N)}else if(it==="agent_approval_complete"){let q=L.approvalId;if(q){let ae={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:(is=L.decision)!=null?is:"approved",agentId:(ls=z==null?void 0:z.agentId)!=null?ls:"virtual",executionId:(cs=(ds=L.executionId)!=null?ds:z==null?void 0:z.executionId)!=null?cs:"",toolName:(zr=L.toolName)!=null?zr:"",description:(un=L.description)!=null?un:"",resolvedAt:Date.now()}};u(ae)}}else if(it==="artifact_start"||it==="artifact_delta"||it==="artifact_update"||it==="artifact_complete"){if(it==="artifact_start"){let q=L.artifactType,N=String(L.id),ae=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:N,artifactType:q,title:ae,component:typeof L.component=="string"?L.component:void 0}),Te.set(N,{markdown:"",title:ae}),!K.has(N)){K.add(N);let ie={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:N,title:ae,artifactType:q,status:"streaming"}})};Ue.set(N,ie),u(ie)}}else if(it==="artifact_delta"){let q=String(L.id),N=typeof L.delta=="string"?L.delta:String((so=L.delta)!=null?so:"");r({type:"artifact_delta",id:q,artDelta:N});let ae=Te.get(q);ae&&(ae.markdown+=N)}else if(it==="artifact_update"){let q=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:q,component:typeof L.component=="string"?L.component:void 0})}else if(it==="artifact_complete"){let q=String(L.id);r({type:"artifact_complete",id:q});let N=Ue.get(q);if(N){N.streaming=!1;try{let ae=JSON.parse((yt=N.rawContent)!=null?yt:"{}");if(ae.props){ae.props.status="complete";let ie=Te.get(q);ie!=null&&ie.markdown&&(ae.props.markdown=ie.markdown)}N.rawContent=JSON.stringify(ae)}catch{}Te.delete(q),u(N),Ue.delete(q)}}}else if(it==="transcript_insert"){let q=L.message;if(!q||typeof q!="object")continue;let N=String((ps=q.id)!=null?ps:`msg-${l()}`),ae=q.role,Y={id:N,role:ae==="user"?"user":ae==="system"?"system":"assistant",content:typeof q.content=="string"?q.content:"",rawContent:typeof q.rawContent=="string"?q.rawContent:void 0,createdAt:typeof q.createdAt=="string"?q.createdAt:new Date().toISOString(),streaming:q.streaming===!0,...typeof q.variant=="string"?{variant:q.variant}:{},sequence:l()};if(u(Y),Y.rawContent)try{let je=JSON.parse(Y.rawContent),tt=(Vo=je==null?void 0:je.props)==null?void 0:Vo.artifactId;typeof tt=="string"&&K.add(tt)}catch{}f=null,C.current=null,te.delete(N),le.delete(N)}else if(it==="error"||it==="step_error"||it==="dispatch_error"||it==="flow_error"){let q=null;if(L.error instanceof Error)q=L.error;else if(it==="dispatch_error"){let N=(Nn=L.message)!=null?Nn:L.error;N!=null&&N!==""&&(q=new Error(String(N)))}else if(it==="step_error"||it==="flow_error"){let N=L.error;typeof N=="string"&&N!==""?q=new Error(N):N!=null&&typeof N=="object"&&"message"in N&&(q=new Error(String((yi=N.message)!=null?yi:N)))}else it==="error"&&L.error!=null&&L.error!==""&&(q=new Error(String(L.error)));if(q){r({type:"error",error:q});let N=f;N&&N.streaming&&(N.streaming=!1,u(N)),r({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:_,value:ke}=await o.read();if(_)break;a+=s.decode(ke,{stream:!0});let He=a.split(`
|
|
60
60
|
|
|
61
|
-
`);a=(pe=He.pop())!=null?pe:"";for(let Ve of He){let
|
|
62
|
-
`),gt="message",ot="";for(let G of Xe)G.startsWith("event:")?gt=G.replace("event:","").trim():G.startsWith("data:")&&(ot+=G.replace("data:","").trim());if(!ot)continue;let kt;try{kt=JSON.parse(ot)}catch(G){r({type:"error",error:G instanceof Error?G:new Error("Failed to parse chat stream payload")});continue}let Xt=gt!=="message"?gt:(Be=kt.type)!=null?Be:"message";if((Q=this.onSSEEvent)==null||Q.call(this,Xt,kt),this.parseSSEEvent){A.current=f;let G=await this.handleCustomSSEEvent(kt,r,A,u,l,S);if(A.current&&A.current!==f&&(f=A.current),G)continue}ge.push(Xt,kt),ze()}}ge.flushPending(),ze(),ge.destroy()}};function Hh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${t}_${e}`}function Ra(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function sa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Zi="[Image]";function Dh(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Oh(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function _h(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Nh(t){return typeof t=="string"?[]:t.filter(e=>e.type==="image")}function Rs(t){return{type:"text",text:t}}function Fh(t,e){return{type:"image",image:t,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function $h(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;e({type:"image",image:o,mimeType:t.type,alt:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function Uh(t,e=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var qh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fw=["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,...fw];function mw(t){return qh.includes(t)||t.startsWith("image/")}function el(t){return mw(t.type)}async function zh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;el(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function Vh(t,e=mo,r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function gw(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function jh(t,e){let r=gw(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var tl=class{constructor(e=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=e}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let n=r.AudioContext||r.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let r=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(r),s=n.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=n.createBufferSource();a.buffer=s,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of e)r()}}pcmToFloat32(e){let r=Math.floor(e.length/2),n=new Float32Array(r),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<r;s++){let a=o.getInt16(s*2,!0);n[s]=a/32768}return n}};var rl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,r,n,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(r),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ws=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new rl;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,r,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(e=this.config)==null?void 0:e.host,i=(r=this.config)==null?void 0:r.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((u,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let y=!1,A=M=>{y||(y=!0,clearTimeout(S),f(new Error(M)))},S=setTimeout(()=>A("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(S),u())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",M=>{if(!M.wasClean&&!y){let k=M.code!==1006?` (code ${M.code})`:"";A("WebSocket connection failed"+k+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let r=JSON.parse(e.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var r,n;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(r=e.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(e.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(n=e.response.audio)!=null&&n.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(e.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new tl(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var e,r,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(r=(e=this.config)==null?void 0:e.pauseDuration)!=null?r:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(u=>u("processing")),this.processingStartCallbacks.forEach(u=>u());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,n=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(r=>r(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(e),o=this.getFormatFromMimeType(e.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((r,n)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];r(a)},o.onerror=n,o.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let r=atob(e.base64),n=new Uint8Array(r.length);for(let l=0;l<r.length;l++)n[l]=r.charCodeAt(l);let o=e.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([n],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var ia=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function la(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Ws(t.runtype);case"browser":if(!ia.isSupported())throw new Error("Browser speech recognition not supported");return new ia(t.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function nl(t){if((t==null?void 0:t.type)==="runtype"&&t.runtype)return la({type:"runtype",runtype:t.runtype});if(ia.isSupported())return la({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Bs(t){try{return nl(t),!0}catch{return!1}}function Gh(t,e){let r=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(r);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}
|
|
61
|
+
`);a=(pe=He.pop())!=null?pe:"";for(let Ve of He){let Je=Ve.split(`
|
|
62
|
+
`),gt="message",at="";for(let G of Je)G.startsWith("event:")?gt=G.replace("event:","").trim():G.startsWith("data:")&&(at+=G.replace("data:","").trim());if(!at)continue;let Mt;try{Mt=JSON.parse(at)}catch(G){r({type:"error",error:G instanceof Error?G:new Error("Failed to parse chat stream payload")});continue}let Xt=gt!=="message"?gt:(Be=Mt.type)!=null?Be:"message";if((Q=this.onSSEEvent)==null||Q.call(this,Xt,Mt),this.parseSSEEvent){C.current=f;let G=await this.handleCustomSSEEvent(Mt,r,C,u,l,S);if(C.current&&C.current!==f&&(f=C.current),G)continue}ge.push(Xt,Mt),ze()}}ge.flushPending(),ze(),ge.destroy()}};function Dh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${t}_${e}`}function Wa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ia(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var el="[Image]";function Oh(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Nh(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function _h(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Fh(t){return typeof t=="string"?[]:t.filter(e=>e.type==="image")}function Rs(t){return{type:"text",text:t}}function $h(t,e){return{type:"image",image:t,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function Uh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;e({type:"image",image:o,mimeType:t.type,alt:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function qh(t,e=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var zh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gw=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],mo=[...zh,...gw];function hw(t){return zh.includes(t)||t.startsWith("image/")}function tl(t){return hw(t.type)}async function Vh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;tl(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function jh(t,e=mo,r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function xw(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Gh(t,e){let r=xw(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var rl=class{constructor(e=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=e}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let n=r.AudioContext||r.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let r=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(r),s=n.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=n.createBufferSource();a.buffer=s,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of e)r()}}pcmToFloat32(e){let r=Math.floor(e.length/2),n=new Float32Array(r),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<r;s++){let a=o.getInt16(s*2,!0);n[s]=a/32768}return n}};var nl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,r,n,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(r),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ws=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new nl;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,r,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(e=this.config)==null?void 0:e.host,i=(r=this.config)==null?void 0:r.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((u,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let x=!1,C=k=>{x||(x=!0,clearTimeout(S),f(new Error(k)))},S=setTimeout(()=>C("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(S),u())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",k=>{if(!k.wasClean&&!x){let T=k.code!==1006?` (code ${k.code})`:"";C("WebSocket connection failed"+T+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let r=JSON.parse(e.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var r,n;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(r=e.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(e.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(n=e.response.audio)!=null&&n.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(e.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new rl(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var e,r,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(r=(e=this.config)==null?void 0:e.pauseDuration)!=null?r:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(u=>u("processing")),this.processingStartCallbacks.forEach(u=>u());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,n=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(r=>r(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(e),o=this.getFormatFromMimeType(e.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((r,n)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];r(a)},o.onerror=n,o.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let r=atob(e.base64),n=new Uint8Array(r.length);for(let l=0;l<r.length;l++)n[l]=r.charCodeAt(l);let o=e.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([n],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var la=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function da(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Ws(t.runtype);case"browser":if(!la.isSupported())throw new Error("Browser speech recognition not supported");return new la(t.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function ol(t){if((t==null?void 0:t.type)==="runtype"&&t.runtype)return da({type:"runtype",runtype:t.runtype});if(la.isSupported())return da({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Bs(t){try{return ol(t),!0}catch{return!1}}function Kh(t,e){let r=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(r);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}
|
|
63
63
|
|
|
64
|
-
_Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=e=>{var r,n,o,s,a,i,d,l;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall;((r=e.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Ls(p.name)&&this.enqueueWebMcpAwait(e.message),(n=e.message.agentMetadata)!=null&&n.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(o=e.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=e.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var n,o;this.messages=[...(n=e.initialMessages)!=null?n:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new aa(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Bs((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,r,n;return(n=(r=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:r.call(e))!=null?n:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var r,n,o;try{let s=e||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=la(s);let a=(r=this.config.voiceRecognition)!=null?r:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,u,f,y,A;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((u=l.text)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.text)!=null&&f.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(A=this.pendingVoiceAssistantMessageId)!=null?A:(y=[...this.messages].reverse().find(M=>M.role==="assistant"))==null?void 0:y.id;S&&this.ttsSpokenMessageIds.add(S)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,n,o,s,a,i,d,l,p;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=e.runtype)==null?void 0:n.agentId)||"",clientToken:((o=e.runtype)==null?void 0:o.clientToken)||"",host:(s=e.runtype)==null?void 0:s.host,voiceId:(a=e.runtype)==null?void 0:a.voiceId,pauseDuration:(i=e.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=e.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=e.browser)==null?void 0:l.language)||"en-US",continuous:(p=e.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var e,r;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(r=(e=this.callbacks).onError)==null||r.call(e,n instanceof Error?n:new Error(String(n))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,r){return this.client.submitMessageFeedback(e,r)}async submitCSATFeedback(e,r){return this.client.submitCSATFeedback(e,r)}async submitNPSFeedback(e,r){return this.client.submitNPSFeedback(e,r)}updateConfig(e){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config={...this.config,...e},this.client=new aa(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:r,content:n,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=e,f={id:a!=null?a:r==="user"?Ra():r==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let r=[];for(let n of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:u,rawContent:f}=n,A={id:d!=null?d:o==="user"?Ra():o==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};r.push(A)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(e){let{component:r,props:n={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,l={text:o,component:r,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,r){var l,p,m,u,f;let n=e.trim();if(!n&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Ra(),s=sa(),a={id:o,role:"user",content:n||Zi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){let A=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!A){let S=Gh(y,this.config.errorMessage);if(S){let M={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,A||(y instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,y):(f=(u=this.callbacks).onError)==null||f.call(u,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=sa();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:r.signal,assistantMessageId:e},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Gh(l,this.config.errorMessage);if(m){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,r){var o,s,a;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(e,r){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:r,resolvedAt:Date.now()}}),n(r==="approved")}async resolveApproval(e,r){var d,l,p,m;let n=`approval-${e.id}`,o={...e,status:r,resolvedAt:Date.now()},s={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},r):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},r),u){let f=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error((l=y==null?void 0:y.error)!=null?l:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let f=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||(m=(p=this.callbacks).onError)==null||m.call(p,u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(e,r){var p,m,u,f,y,A,S,M,k,E,h,w;let n=this.messages.find(x=>x.id===e.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(y=(f=this.callbacks).onError)==null||y.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof r=="string"?void 0:r;if(a===void 0&&typeof r=="string"){let x=(A=e.toolCall)==null?void 0:A.args,T=Array.isArray(x==null?void 0:x.questions)?x.questions:[];if(T.length===1){let W=typeof((S=T[0])==null?void 0:S.question)=="string"?T[0].question:"";W&&(a={[W]:r})}}this.markAskUserQuestionResolved(e,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(k=e.toolCall)==null?void 0:k.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(([T,W])=>`${T}: ${Array.isArray(W)?W.join(", "):W}`).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((T,W)=>{let R=typeof(T==null?void 0:T.question)=="string"?T.question:"";if(!R)return;let B=x[R],_=Array.isArray(B)?B.join(", "):typeof B=="string"?B:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let x=await this.client.resumeFlow(o,{[s]:r});if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((E=T==null?void 0:T.error)!=null?E:`Resume failed: ${x.status}`)}x.body?await this.connectStream(x.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(x){let T=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(w=(h=this.callbacks).onError)==null||w.call(h,x instanceof Error?x:new Error(String(x)))}}enqueueWebMcpAwait(e){var s,a;let r=(s=e.agentMetadata)==null?void 0:s.executionId,n=(a=e.toolCall)==null?void 0:a.id;if(!r||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(r);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,o)),!o.seen.has(n)&&(o.seen.add(n),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(e){let r=this.webMcpAwaitBatches.get(e);if(!r)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=r;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(e,n)}async resolveWebMcpToolCallBatch(e,r){var i,d,l;let n=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(r.map(async p=>{var k,E,h,w,x,T,W;let m=(k=p.toolCall)==null?void 0:k.name,u=(E=p.toolCall)==null?void 0:E.id;if(!m||!u)return null;let f=`${e}:${u}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f))return null;this.webMcpInflightKeys.add(f),n.push(f),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let y=new AbortController;this.webMcpResolveControllers.add(y),o.push(y);let A=(w=(h=p.agentMetadata)==null?void 0:h.webMcpToolCallId)!=null?w:m,S=this.client.executeWebMcpToolCall(m,(x=p.toolCall)==null?void 0:x.args,y.signal),M;if(!S)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await S}catch(R){return R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"))||(W=(T=this.callbacks).onError)==null||W.call(T,R instanceof Error?R:new Error(String(R))),this.webMcpInflightKeys.delete(f),null}return y.signal.aborted?(this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:A,output:M}}));try{let p=a.filter(f=>f!==null);if(p.length===0)return;let m={};for(let f of p)m[f.resumeKey]=f.output;let u=await this.client.resumeFlow(e,m,{signal:s.signal});if(!u.ok){let f=await u.json().catch(()=>null);throw new Error((i=f==null?void 0:f.error)!=null?i:`Resume failed: ${u.status}`)}for(let f of p)this.webMcpResolvedKeys.add(f.dedupeKey);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of n)this.webMcpInflightKeys.delete(p);for(let p of o)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var p,m,u,f,y,A,S,M,k,E,h,w;let r=(p=e.agentMetadata)==null?void 0:p.executionId,n=(m=e.toolCall)==null?void 0:m.name,o=(u=e.toolCall)==null?void 0:u.id;if(!r){(y=(f=this.callbacks).onError)==null||y.call(f,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let 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(T){(S=(A=this.callbacks).onError)==null||S.call(A,T instanceof Error?T:new Error(String(T)))}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({...e,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(M=e.toolCall)==null?void 0:M.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 T=(E=(k=e.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?E:n;await this.resumeWithToolOutput(r,T,x,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(x){x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"))||(w=(h=this.callbacks).onError)==null||w.call(h,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(e,r,n,o){var a,i;let s=await this.client.resumeFlow(e,{[r]:n},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let r=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:r,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(r,s),this.selectedArtifactId=r,this.emitArtifactsState(),s}let n={id:r,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(r,n),this.selectedArtifactId=r,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,r;(r=(e=this.callbacks).onArtifactsState)==null||r.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var r,n;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(r=e.component)!=null?r:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,r=null){this.artifacts.clear();for(let n of e)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let r=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),r&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let n=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,e)}speak(e,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(e),s=n.getVoices();if(r.voice){let a=s.find(i=>i.name===r.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):t.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(e){var n;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=e.find(a=>a.name===o);if(s)return s}return(n=e.find(o=>o.lang.startsWith("en")))!=null?n:e[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),n=this.messages.findIndex(o=>o.id===r.id);if(n===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>{var p,m,u,f,y,A;if(s!==n)return o;let a={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(a.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=r.toolCall)==null?void 0:m.name,d=(u=r.agentMetadata)==null?void 0:u.executionId,l=(f=r.toolCall)==null?void 0:f.id;if(i&&Ls(i)&&d&&l&&((y=r.agentMetadata)==null?void 0:y.awaitingLocalTool)===!0){let S=`${d}:${l}`;(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))&&(a.agentMetadata={...(A=a.agentMetadata)!=null?A:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,n)=>{var d,l;let o=new Date(r.createdAt).getTime(),s=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=r.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return a!==i?a-i:r.id.localeCompare(n.id)})}};var v=(t,e)=>{let r=document.createElement(t);return e&&(r.className=e),r},Qn=(t,e,r)=>{let n=t.createElement(e);return r&&(n.className=r),n};var Bd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Hd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Dd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Od=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var _d=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Nd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Fd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var $d=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Ud=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var qd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var zd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Vd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var jd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Gd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Kd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Xd=[["path",{d:"M20 6 9 17l-5-5"}]];var Jd=[["path",{d:"m6 9 6 6 6-6"}]];var Qd=[["path",{d:"m15 18-6-6 6-6"}]];var Yd=[["path",{d:"m9 18 6-6-6-6"}]];var Zd=[["path",{d:"m18 15-6-6-6 6"}]];var ol=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var al=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var ec=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var tc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var rc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var nc=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var oc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var ac=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var sc=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var sl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var il=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var ic=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var lc=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var dc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var cc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var pc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var uc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var fc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var mc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var gc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var hc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var xc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var yc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var ll=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var bc=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1"}],["path",{d:"M12 8v13"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"}]];var wc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var vc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Cc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Ac=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Sc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var dl=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Tc=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var kc=[["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 Mc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Ec=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Lc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var cl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Pc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Ic=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Rc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Wc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Bc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Hc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Dc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Oc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var _c=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Nc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Fc=[["path",{d:"M5 12h14"}]];var $c=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Uc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var qc=[["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 zc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Vc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var jc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Gc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Kc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Xc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Jc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Qc=[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}],["path",{d:"M12 17.5v-11"}]];var Yc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Zc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var ep=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var tp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var rp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var np=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var op=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var ap=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var sp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var pl=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var ip=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var lp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var dp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var cp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var ul=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var pp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var up=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var fp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var mp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var gp=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var hp=[["path",{d:"M17 14V2"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}]];var xp=[["path",{d:"M7 10v12"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}]];var yp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var bp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var wp=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var fl=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var vp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Cp=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Ap=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Sp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Tp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var kp=[["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 Mp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ep=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var hw={activity:Bd,"arrow-down":Hd,"arrow-up":Nd,"arrow-up-right":_d,bot:zd,"chevron-down":Jd,"chevron-up":Zd,"chevron-right":Yd,"chevron-left":Qd,check:Xd,clipboard:tc,"clipboard-copy":ec,copy:nc,file:fc,"file-code":cc,"file-spreadsheet":pc,"file-text":uc,"image-plus":Tc,loader:Pc,"loader-circle":cl,mic:_c,paperclip:zc,"refresh-cw":Yc,search:tp,send:rp,"shield-alert":ap,"shield-check":sp,"shield-x":pl,square:pp,"thumbs-down":hp,"thumbs-up":xp,upload:Cp,"volume-2":Sp,x:Mp,user:Ap,mail:Rc,phone:Kc,calendar:Gd,clock:rc,building:Vd,"map-pin":Wc,lock:Ic,key:Ec,"credit-card":oc,"at-sign":Fd,hash:vc,globe:wc,link:Lc,"circle-check":ol,"circle-x":al,"triangle-alert":fl,info:Mc,ban:$d,shield:ip,"arrow-left":Dd,"arrow-right":Od,"external-link":ic,ellipsis:il,"ellipsis-vertical":sl,menu:Hc,house:dl,plus:Jc,minus:Fc,pencil:jc,trash:wp,"trash-2":bp,save:ep,download:sc,share:op,funnel:ll,settings:np,"rotate-cw":Zc,maximize:Bc,minimize:Nc,"shopping-cart":dp,"shopping-bag":lp,package:qc,truck:vp,tag:gp,gift:bc,receipt:Qc,wallet:kp,store:fp,"dollar-sign":ac,percent:Gc,play:Xc,pause:Vc,"volume-x":Tp,camera:Kd,image:kc,film:gc,headphones:Cc,"message-circle":Dc,"message-square":Oc,bell:Ud,heart:Ac,star:up,eye:dc,"eye-off":lc,bookmark:qd,"calendar-days":jd,history:Sc,timer:yp,folder:yc,"folder-open":xc,files:mc,sparkles:ul,zap:Ep,sun:mp,moon:Uc,flag:hc,monitor:$c,smartphone:cp},Ie=(t,e=24,r="currentColor",n=2)=>{let o=hw[t];return o?xw(o,e,r,n):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function xw(t,e,r,n){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var ml={allowedTypes:mo,maxFileSize:10*1024*1024,maxFiles:4};function yw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bw(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var da=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=e.allowedTypes)!=null?r:ml.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:ml.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:ml.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ml.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var r,n,o,s,a,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(n=(r=this.config).onFileRejected)==null||n.call(r,l,"count");continue}let p=Vh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await zh(l),u=el(l)?URL.createObjectURL(l):null,f={id:yw(),file:l,previewUrl:u,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let r=this.attachments.findIndex(d=>d.id===e);if(r===-1)return;let n=this.attachments[r];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,r;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(e=this.config).onAttachmentsChange)==null||r.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let r=el(e.file),n=v("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",e.id),n.style.width="48px",n.style.height="48px",r&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=bw(e.file.type),d=Ie(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=v("span");l.textContent=jh(e.file.type,e.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),n.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,r){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:r})}};var Kh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Hs(t,e){if(!t)return e;if(!e)return t;let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];Kh(s)&&Kh(o)?r[n]=Hs(s,o):r[n]=o}return r}var yn="min(440px, calc(100vw - 24px))",gl="440px",er={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:yn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xh(t,e){if(!(!t&&!e))return t?e?Hs(t,e):t:e}function hl(t){var e,r,n,o,s,a,i,d,l,p,m,u,f,y,A,S,M,k,E,h,w;return t?{...er,...t,theme:Xh(er.theme,t.theme),darkTheme:Xh(er.darkTheme,t.darkTheme),launcher:{...er.launcher,...t.launcher,dock:{...(e=er.launcher)==null?void 0:e.dock,...(r=t.launcher)==null?void 0:r.dock},clearChat:{...(n=er.launcher)==null?void 0:n.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...er.copy,...t.copy},sendButton:{...er.sendButton,...t.sendButton},statusIndicator:{...er.statusIndicator,...t.statusIndicator},voiceRecognition:{...er.voiceRecognition,...t.voiceRecognition},features:(()=>{var Ee,Ge,_e,X,Ue,K,Te,ae;let x=(Ee=er.features)==null?void 0:Ee.artifacts,T=(Ge=t.features)==null?void 0:Ge.artifacts,W=(_e=er.features)==null?void 0:_e.scrollToBottom,R=(X=t.features)==null?void 0:X.scrollToBottom,B=(Ue=er.features)==null?void 0:Ue.streamAnimation,_=(K=t.features)==null?void 0:K.streamAnimation,V=(Te=er.features)==null?void 0:Te.askUserQuestion,oe=(ae=t.features)==null?void 0:ae.askUserQuestion,be=x===void 0&&T===void 0?void 0:{...x,...T,layout:{...x==null?void 0:x.layout,...T==null?void 0:T.layout}},Qe=W===void 0&&R===void 0?void 0:{...W,...R},je=B===void 0&&_===void 0?void 0:{...B,..._},ve=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{...er.features,...t.features,...Qe!==void 0?{scrollToBottom:Qe}:{},...be!==void 0?{artifacts:be}:{},...je!==void 0?{streamAnimation:je}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:er.suggestionChips,suggestionChipsConfig:{...er.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...er.layout,...t.layout,header:{...(a=er.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=er.layout)==null?void 0:d.messages,...(l=t.layout)==null?void 0:l.messages,avatar:{...(m=(p=er.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(f=(u=t.layout)==null?void 0:u.messages)==null?void 0:f.avatar},timestamp:{...(A=(y=er.layout)==null?void 0:y.messages)==null?void 0:A.timestamp,...(M=(S=t.layout)==null?void 0:S.messages)==null?void 0:M.timestamp}},slots:{...(k=er.layout)==null?void 0:k.slots,...(E=t.layout)==null?void 0:E.slots}},markdown:{...er.markdown,...t.markdown,options:{...(h=er.markdown)==null?void 0:h.options,...(w=t.markdown)==null?void 0:w.options}},messageActions:{...er.messageActions,...t.messageActions}}:er}var Lp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Pp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Ip={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:yn,maxWidth:gl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ba(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let r=e.split("."),n=t;for(let o of r){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ba(t,n):n}function xl(t){let e={};function r(n,o){for(let[s,a]of Object.entries(n)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ba(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&r(a,i)}}return r(t.palette,"palette"),r(t.semantic,"semantic"),r(t.components,"components"),e}function Rp(t){let e=[],r=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:r}}function Jh(t,e){let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?r[n]=Jh(s,o):r[n]=o}return r}function ww(t,e){return e?Jh(t,e):t}function Ha(t,e={}){var o,s,a,i,d,l,p,m,u,f,y,A,S;let r={palette:Lp,semantic:Pp,components:Ip},n={palette:{...r.palette,...t==null?void 0:t.palette,colors:{...r.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...r.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...r.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...r.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...r.palette.radius,...(l=t==null?void 0:t.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...t==null?void 0:t.semantic,colors:{...r.semantic.colors,...(p=t==null?void 0:t.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(y=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:y.feedback}},spacing:{...r.semantic.spacing,...(A=t==null?void 0:t.semantic)==null?void 0:A.spacing},typography:{...r.semantic.typography,...(S=t==null?void 0:t.semantic)==null?void 0:S.typography}},components:ww(r.components,t==null?void 0:t.components)};if(e.validate!==!1){let M=Rp(n);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(k=>k.message).join(", ")}`)}if(e.plugins)for(let M of e.plugins)n=M.transform(n);return n}function yl(t){var A,S,M,k,E,h,w,x,T,W,R,B,_,V,oe,be,Qe,je,ve,Ee,Ge,_e,X,Ue,K,Te,ae,xe,ke,Ke,ce,re,le,ut,Ce,he,tt,Ne,me,J,ze,Z,ge,z,Re,Ae,fe,pe,Be,Q,N,Me,He,Ve,Xe,gt,ot,kt,Xt,G,Jt,at,Nt,de,ye,Rt,ar,Mt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,P,ee,Se,rt,Qt,Ft,tr,Pr,_r,wn,Vt,$t,Ir,vn,bo,eo,wo,qn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn;let e=xl(t),r={};for(let[I,pn]of Object.entries(e)){let Bn=I.replace(/\./g,"-");r[`--persona-${Bn}`]=pn.value}r["--persona-primary"]=(A=r["--persona-semantic-colors-primary"])!=null?A:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(S=r["--persona-semantic-colors-secondary"])!=null?S:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(M=r["--persona-semantic-colors-accent"])!=null?M:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(k=r["--persona-semantic-colors-surface"])!=null?k:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(E=r["--persona-semantic-colors-background"])!=null?E:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(h=r["--persona-semantic-colors-container"])!=null?h: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"]=(x=r["--persona-semantic-colors-text-muted"])!=null?x:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(T=r["--persona-semantic-colors-text-inverse"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(R=r["--persona-semantic-colors-divider"])!=null?R:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(B=r["--persona-components-voice-recording-indicator"])!=null?B:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(_=r["--persona-components-voice-recording-background"])!=null?_:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(V=r["--persona-components-voice-processing-icon"])!=null?V:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(oe=r["--persona-components-voice-speaking-icon"])!=null?oe:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(be=r["--persona-components-approval-requested-background"])!=null?be:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Qe=r["--persona-components-approval-requested-border"])!=null?Qe:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(je=r["--persona-components-approval-requested-text"])!=null?je:r["--persona-palette-colors-gray-900"],r["--persona-approval-approve-bg"]=(ve=r["--persona-components-approval-approve-background"])!=null?ve:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Ee=r["--persona-components-approval-deny-background"])!=null?Ee:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(Ge=r["--persona-components-attachment-image-background"])!=null?Ge:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(_e=r["--persona-components-attachment-image-border"])!=null?_e:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(X=r["--persona-semantic-typography-fontFamily"])!=null?X:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(Ue=r["--persona-semantic-typography-fontSize"])!=null?Ue:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(K=r["--persona-semantic-typography-fontWeight"])!=null?K:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Te=r["--persona-semantic-typography-lineHeight"])!=null?Te:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(ae=r["--persona-palette-radius-sm"])!=null?ae:"0.125rem",r["--persona-radius-md"]=(xe=r["--persona-palette-radius-md"])!=null?xe:"0.375rem",r["--persona-radius-lg"]=(ke=r["--persona-palette-radius-lg"])!=null?ke:"0.5rem",r["--persona-radius-xl"]=(Ke=r["--persona-palette-radius-xl"])!=null?Ke:"0.75rem",r["--persona-radius-full"]=(ce=r["--persona-palette-radius-full"])!=null?ce:"9999px",r["--persona-launcher-radius"]=(le=(re=r["--persona-components-launcher-borderRadius"])!=null?re:r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-bg"]=(ut=r["--persona-components-launcher-background"])!=null?ut:r["--persona-primary"],r["--persona-launcher-fg"]=(Ce=r["--persona-components-launcher-foreground"])!=null?Ce:r["--persona-text-inverse"],r["--persona-launcher-border"]=(he=r["--persona-components-launcher-border"])!=null?he:r["--persona-border"],r["--persona-button-primary-bg"]=(tt=r["--persona-components-button-primary-background"])!=null?tt:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ne=r["--persona-components-button-primary-foreground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-button-radius"]=(J=(me=r["--persona-components-button-primary-borderRadius"])!=null?me:r["--persona-palette-radius-full"])!=null?J:"9999px",r["--persona-panel-radius"]=(Z=(ze=r["--persona-components-panel-borderRadius"])!=null?ze:r["--persona-radius-xl"])!=null?Z:"0.75rem",r["--persona-panel-border"]=(ge=r["--persona-components-panel-border"])!=null?ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Re=(z=r["--persona-components-panel-shadow"])!=null?z:r["--persona-palette-shadows-xl"])!=null?Re:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-input-radius"]=(fe=(Ae=r["--persona-components-input-borderRadius"])!=null?Ae:r["--persona-radius-lg"])!=null?fe:"0.5rem",r["--persona-message-user-radius"]=(Be=(pe=r["--persona-components-message-user-borderRadius"])!=null?pe:r["--persona-radius-lg"])!=null?Be:"0.5rem",r["--persona-message-assistant-radius"]=(N=(Q=r["--persona-components-message-assistant-borderRadius"])!=null?Q:r["--persona-radius-lg"])!=null?N:"0.5rem",r["--persona-header-bg"]=(Me=r["--persona-components-header-background"])!=null?Me:r["--persona-surface"],r["--persona-header-border"]=(He=r["--persona-components-header-border"])!=null?He:r["--persona-divider"],r["--persona-header-icon-bg"]=(Ve=r["--persona-components-header-iconBackground"])!=null?Ve:r["--persona-primary"],r["--persona-header-icon-fg"]=(Xe=r["--persona-components-header-iconForeground"])!=null?Xe:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(gt=r["--persona-components-header-titleForeground"])!=null?gt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(ot=r["--persona-components-header-subtitleForeground"])!=null?ot:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(kt=r["--persona-components-header-actionIconForeground"])!=null?kt:r["--persona-muted"];let n=(Xt=t.components)==null?void 0:Xt.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(G=t.components)==null?void 0:G.introCard;r["--persona-intro-card-bg"]=(Jt=r["--persona-components-introCard-background"])!=null?Jt:r["--persona-surface"],r["--persona-intro-card-radius"]=(at=r["--persona-components-introCard-borderRadius"])!=null?at:"1rem",r["--persona-intro-card-padding"]=(Nt=r["--persona-components-introCard-padding"])!=null?Nt:"1.5rem",r["--persona-intro-card-shadow"]=(ye=(de=o==null?void 0:o.shadow)!=null?de:r["--persona-components-introCard-shadow"])!=null?ye:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Rt=r["--persona-components-input-background"])!=null?Rt:r["--persona-surface"],r["--persona-input-placeholder"]=(ar=r["--persona-components-input-placeholder"])!=null?ar:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Mt=r["--persona-components-message-user-background"])!=null?Mt:r["--persona-accent"],r["--persona-message-user-text"]=(mr=r["--persona-components-message-user-text"])!=null?mr:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Ot=r["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Wt=r["--persona-components-message-assistant-background"])!=null?Wt:r["--persona-surface"],r["--persona-message-assistant-text"]=(St=r["--persona-components-message-assistant-text"])!=null?St:r["--persona-text"],r["--persona-message-assistant-border"]=(Et=r["--persona-components-message-assistant-border"])!=null?Et:r["--persona-border"],r["--persona-message-assistant-shadow"]=(sr=r["--persona-components-message-assistant-shadow"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(dr=(ft=r["--persona-components-scrollToBottom-background"])!=null?ft:r["--persona-button-primary-bg"])!=null?dr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Lr=(wr=r["--persona-components-scrollToBottom-foreground"])!=null?wr:r["--persona-button-primary-fg"])!=null?Lr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(Or=r["--persona-components-scrollToBottom-border"])!=null?Or:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(xt=r["--persona-components-scrollToBottom-size"])!=null?xt:"40px",r["--persona-scroll-to-bottom-radius"]=(Un=(fr=(sn=r["--persona-components-scrollToBottom-borderRadius"])!=null?sn:r["--persona-button-radius"])!=null?fr:r["--persona-radius-full"])!=null?Un:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Zn=(Rr=r["--persona-components-scrollToBottom-shadow"])!=null?Rr:r["--persona-palette-shadows-sm"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Pn=r["--persona-components-scrollToBottom-padding"])!=null?Pn:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(In=r["--persona-components-scrollToBottom-gap"])!=null?In:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(P=(ue=r["--persona-components-scrollToBottom-fontSize"])!=null?ue:r["--persona-palette-typography-fontSize-sm"])!=null?P:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(ee=r["--persona-components-scrollToBottom-iconSize"])!=null?ee:"14px",r["--persona-tool-bubble-shadow"]=(Se=r["--persona-components-toolBubble-shadow"])!=null?Se:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(rt=r["--persona-components-reasoningBubble-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Qt=r["--persona-components-composer-shadow"])!=null?Qt:"none",r["--persona-md-inline-code-bg"]=(Ft=r["--persona-components-markdown-inlineCode-background"])!=null?Ft:r["--persona-container"],r["--persona-md-inline-code-color"]=(tr=r["--persona-components-markdown-inlineCode-foreground"])!=null?tr:r["--persona-text"],r["--persona-md-link-color"]=(_r=(Pr=r["--persona-components-markdown-link-foreground"])!=null?Pr:r["--persona-accent"])!=null?_r:"#0f0f0f";let s=r["--persona-components-markdown-heading-h1-fontSize"];s&&(r["--persona-md-h1-size"]=s);let a=r["--persona-components-markdown-heading-h1-fontWeight"];a&&(r["--persona-md-h1-weight"]=a);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let d=r["--persona-components-markdown-heading-h2-fontWeight"];d&&(r["--persona-md-h2-weight"]=d);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(wn=r["--persona-components-markdown-codeBlock-background"])!=null?wn:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Vt=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Vt:r["--persona-border"],r["--persona-md-code-block-text-color"]=($t=r["--persona-components-markdown-codeBlock-textColor"])!=null?$t:"inherit",r["--persona-md-table-header-bg"]=(Ir=r["--persona-components-markdown-table-headerBackground"])!=null?Ir:r["--persona-container"],r["--persona-md-table-border-color"]=(vn=r["--persona-components-markdown-table-borderColor"])!=null?vn:r["--persona-border"],r["--persona-md-hr-color"]=(bo=r["--persona-components-markdown-hr-color"])!=null?bo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(eo=r["--persona-components-markdown-blockquote-borderColor"])!=null?eo:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(wo=r["--persona-components-markdown-blockquote-background"])!=null?wo:"transparent",r["--persona-md-blockquote-text-color"]=(qn=r["--persona-components-markdown-blockquote-textColor"])!=null?qn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(ln=r["--persona-components-collapsibleWidget-container"])!=null?ln:r["--persona-surface"],r["--cw-surface"]=(Rn=r["--persona-components-collapsibleWidget-surface"])!=null?Rn:r["--persona-surface"],r["--cw-border"]=(Pt=r["--persona-components-collapsibleWidget-border"])!=null?Pt:r["--persona-border"],r["--persona-message-border"]=(gr=r["--persona-components-message-border"])!=null?gr:r["--persona-border"];let p=t.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(r["--persona-icon-btn-bg"]=m.background),m.border&&(r["--persona-icon-btn-border"]=m.border),m.color&&(r["--persona-icon-btn-color"]=m.color),m.padding&&(r["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(r["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(r["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(r["--persona-icon-btn-active-border"]=m.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let I=y.toolbar;I.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=I.iconHoverColor),I.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=I.iconHoverBackground),I.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=I.iconPadding),I.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=I.iconBorderRadius),I.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=I.iconBorder),I.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=I.toggleGroupGap),I.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=I.toggleBorderRadius),I.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=I.copyBackground),I.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=I.copyBorder),I.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=I.copyColor),I.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=I.copyBorderRadius),I.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=I.copyPadding),I.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=I.copyMenuBackground,r["--persona-dropdown-bg"]=(hr=r["--persona-dropdown-bg"])!=null?hr:I.copyMenuBackground),I.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=I.copyMenuBorder,r["--persona-dropdown-border"]=(dn=r["--persona-dropdown-border"])!=null?dn:I.copyMenuBorder),I.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=I.copyMenuShadow,r["--persona-dropdown-shadow"]=(vo=r["--persona-dropdown-shadow"])!=null?vo:I.copyMenuShadow),I.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=I.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Cn=r["--persona-dropdown-radius"])!=null?Cn:I.copyMenuBorderRadius),I.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=I.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Wn=r["--persona-dropdown-item-hover-bg"])!=null?Wn:I.copyMenuItemHoverBackground),I.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=I.iconBackground),I.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=I.toolbarBorder)}if(y!=null&&y.tab){let I=y.tab;I.background&&(r["--persona-artifact-tab-bg"]=I.background),I.activeBackground&&(r["--persona-artifact-tab-active-bg"]=I.activeBackground),I.activeBorder&&(r["--persona-artifact-tab-active-border"]=I.activeBorder),I.borderRadius&&(r["--persona-artifact-tab-radius"]=I.borderRadius),I.textColor&&(r["--persona-artifact-tab-color"]=I.textColor),I.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=I.hoverBackground),I.listBackground&&(r["--persona-artifact-tab-list-bg"]=I.listBackground),I.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=I.listBorderColor),I.listPadding&&(r["--persona-artifact-tab-list-padding"]=I.listPadding)}if(y!=null&&y.pane){let I=y.pane;if(I.toolbarBackground){let pn=(cn=Ba(t,I.toolbarBackground))!=null?cn:I.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pn}}return r}var Qh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var vw={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Yh=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ds=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Cw=t=>{var r;let e=(r=t==null?void 0:t.colorScheme)!=null?r:"light";return e==="light"?"light":e==="dark"?"dark":Ds()},Wp=t=>Cw(t),Aw=t=>Ha(t),Sw=t=>{var r;let e=Ha(void 0,{validate:!1});return Ha({...t,palette:{...e.palette,colors:{...vw.colors,...(r=t==null?void 0:t.palette)==null?void 0:r.colors}}},{validate:!1})},Da=t=>{let e=Wp(t),r=Yh(t==null?void 0:t.theme),n=Yh(t==null?void 0:t.darkTheme);return e==="dark"?Sw(Hs(r!=null?r:{},n!=null?n:{})):Aw(r)},Tw=t=>yl(t),Io=(t,e)=>{var s;let r=Da(e),n=Tw(r);for(let[a,i]of Object.entries(n))t.style.setProperty(a,i);let o=(s=e==null?void 0:e.toolCall)==null?void 0:s.shadow;o!==void 0&&t.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},bl=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Ds())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>t(Ds());r.addEventListener?(r.addEventListener("change",n),e.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),e.push(()=>r.removeListener(n)))}return()=>{e.forEach(r=>r())}};var Zh=(function(){"use strict";let t=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:t,afterNodeAdded:t,beforeNodeMorphed:t,afterNodeMorphed:t,beforeNodeRemoved:t,afterNodeRemoved:t,beforeAttributeUpdated:t},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:t,afterHeadMorphed:t},restoreFocus:!0};function r(u,f,y={}){u=p(u);let A=m(f),S=l(u,A,y),M=o(S,()=>i(S,u,A,k=>k.morphStyle==="innerHTML"?(s(k,u,A),Array.from(u.childNodes)):n(k,u,A)));return S.pantry.remove(),M}function n(u,f,y){let A=m(f);return s(u,A,y,f,f.nextSibling),Array.from(A.childNodes)}function o(u,f){var E;if(!u.config.restoreFocus)return f();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return f();let{id:A,selectionStart:S,selectionEnd:M}=y,k=f();return A&&A!==((E=document.activeElement)==null?void 0:E.getAttribute("id"))&&(y=u.target.querySelector(`[id="${A}"]`),y==null||y.focus()),y&&!y.selectionEnd&&M&&y.setSelectionRange(S,M),k}let s=(function(){function u(h,w,x,T=null,W=null){w instanceof HTMLTemplateElement&&x instanceof HTMLTemplateElement&&(w=w.content,x=x.content),T||(T=w.firstChild);for(let R of x.childNodes){if(T&&T!=W){let _=y(h,R,T,W);if(_){_!==T&&S(h,T,_),a(_,R,h),T=_.nextSibling;continue}}if(R instanceof Element){let _=R.getAttribute("id");if(h.persistentIds.has(_)){let V=M(w,_,T,h);a(V,R,h),T=V.nextSibling;continue}}let B=f(w,R,T,h);B&&(T=B.nextSibling)}for(;T&&T!=W;){let R=T;T=T.nextSibling,A(h,R)}}function f(h,w,x,T){if(T.callbacks.beforeNodeAdded(w)===!1)return null;if(T.idMap.has(w)){let W=document.createElement(w.tagName);return h.insertBefore(W,x),a(W,w,T),T.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(w,!0);return h.insertBefore(W,x),T.callbacks.afterNodeAdded(W),W}}let y=(function(){function h(T,W,R,B){let _=null,V=W.nextSibling,oe=0,be=R;for(;be&&be!=B;){if(x(be,W)){if(w(T,be,W))return be;_===null&&(T.idMap.has(be)||(_=be))}if(_===null&&V&&x(be,V)&&(oe++,V=V.nextSibling,oe>=2&&(_=void 0)),T.activeElementAndParents.includes(be))break;be=be.nextSibling}return _||null}function w(T,W,R){let B=T.idMap.get(W),_=T.idMap.get(R);if(!_||!B)return!1;for(let V of B)if(_.has(V))return!0;return!1}function x(T,W){var _,V,oe;let R=T,B=W;return R.nodeType===B.nodeType&&R.tagName===B.tagName&&(!((_=R.getAttribute)!=null&&_.call(R,"id"))||((V=R.getAttribute)==null?void 0:V.call(R,"id"))===((oe=B.getAttribute)==null?void 0:oe.call(B,"id")))}return h})();function A(h,w){var x;if(h.idMap.has(w))E(h.pantry,w,null);else{if(h.callbacks.beforeNodeRemoved(w)===!1)return;(x=w.parentNode)==null||x.removeChild(w),h.callbacks.afterNodeRemoved(w)}}function S(h,w,x){let T=w;for(;T&&T!==x;){let W=T;T=T.nextSibling,A(h,W)}return T}function M(h,w,x,T){var R,B;let W=((B=(R=T.target).getAttribute)==null?void 0:B.call(R,"id"))===w&&T.target||T.target.querySelector(`[id="${w}"]`)||T.pantry.querySelector(`[id="${w}"]`);return k(W,T),E(h,W,x),W}function k(h,w){let x=h.getAttribute("id");for(;h=h.parentNode;){let T=w.idMap.get(h);T&&(T.delete(x),T.size||w.idMap.delete(h))}}function E(h,w,x){if(h.moveBefore)try{h.moveBefore(w,x)}catch{h.insertBefore(w,x)}else h.insertBefore(w,x)}return u})(),a=(function(){function u(k,E,h){return h.ignoreActive&&k===document.activeElement?null:(h.callbacks.beforeNodeMorphed(k,E)===!1||(k instanceof HTMLHeadElement&&h.head.ignore||(k instanceof HTMLHeadElement&&h.head.style!=="morph"?d(k,E,h):(f(k,E,h),M(k,h)||s(h,k,E))),h.callbacks.afterNodeMorphed(k,E)),k)}function f(k,E,h){let w=E.nodeType;if(w===1){let x=k,T=E,W=x.attributes,R=T.attributes;for(let B of R)S(B.name,x,"update",h)||x.getAttribute(B.name)!==B.value&&x.setAttribute(B.name,B.value);for(let B=W.length-1;0<=B;B--){let _=W[B];if(_&&!T.hasAttribute(_.name)){if(S(_.name,x,"remove",h))continue;x.removeAttribute(_.name)}}M(x,h)||y(x,T,h)}(w===8||w===3)&&k.nodeValue!==E.nodeValue&&(k.nodeValue=E.nodeValue)}function y(k,E,h){if(k instanceof HTMLInputElement&&E instanceof HTMLInputElement&&E.type!=="file"){let w=E.value,x=k.value;A(k,E,"checked",h),A(k,E,"disabled",h),E.hasAttribute("value")?x!==w&&(S("value",k,"update",h)||(k.setAttribute("value",w),k.value=w)):S("value",k,"remove",h)||(k.value="",k.removeAttribute("value"))}else if(k instanceof HTMLOptionElement&&E instanceof HTMLOptionElement)A(k,E,"selected",h);else if(k instanceof HTMLTextAreaElement&&E instanceof HTMLTextAreaElement){let w=E.value,x=k.value;if(S("value",k,"update",h))return;w!==x&&(k.value=w),k.firstChild&&k.firstChild.nodeValue!==w&&(k.firstChild.nodeValue=w)}}function A(k,E,h,w){let x=E[h],T=k[h];if(x!==T){let W=S(h,k,"update",w);W||(k[h]=E[h]),x?W||k.setAttribute(h,""):S(h,k,"remove",w)||k.removeAttribute(h)}}function S(k,E,h,w){return k==="value"&&w.ignoreActiveValue&&E===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(k,E,h)===!1}function M(k,E){return!!E.ignoreActiveValue&&k===document.activeElement&&k!==document.body}return u})();function i(u,f,y,A){if(u.head.block){let S=f.querySelector("head"),M=y.querySelector("head");if(S&&M){let k=d(S,M,u);return Promise.all(k).then(()=>{let E=Object.assign(u,{head:{block:!1,ignore:!0}});return A(E)})}}return A(u)}function d(u,f,y){let A=[],S=[],M=[],k=[],E=new Map;for(let w of f.children)E.set(w.outerHTML,w);for(let w of u.children){let x=E.has(w.outerHTML),T=y.head.shouldReAppend(w),W=y.head.shouldPreserve(w);x||W?T?S.push(w):(E.delete(w.outerHTML),M.push(w)):y.head.style==="append"?T&&(S.push(w),k.push(w)):y.head.shouldRemove(w)!==!1&&S.push(w)}k.push(...E.values());let h=[];for(let w of k){let x=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(x)!==!1){if("href"in x&&x.href||"src"in x&&x.src){let T,W=new Promise(function(R){T=R});x.addEventListener("load",function(){T()}),h.push(W)}u.appendChild(x),y.callbacks.afterNodeAdded(x),A.push(x)}}for(let w of S)y.callbacks.beforeNodeRemoved(w)!==!1&&(u.removeChild(w),y.callbacks.afterNodeRemoved(w));return y.head.afterHeadMorphed(u,{added:A,kept:M,removed:S}),h}let l=(function(){function u(h,w,x){let{persistentIds:T,idMap:W}=k(h,w),R=f(x),B=R.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(B))throw`Do not understand how to morph style ${B}`;return{target:h,newContent:w,config:R,morphStyle:B,ignoreActive:R.ignoreActive,ignoreActiveValue:R.ignoreActiveValue,restoreFocus:R.restoreFocus,idMap:W,persistentIds:T,pantry:y(),activeElementAndParents:A(h),callbacks:R.callbacks,head:R.head}}function f(h){let w=Object.assign({},e);return Object.assign(w,h),w.callbacks=Object.assign({},e.callbacks,h.callbacks),w.head=Object.assign({},e.head,h.head),w}function y(){let h=document.createElement("div");return h.hidden=!0,document.body.insertAdjacentElement("afterend",h),h}function A(h){let w=[],x=document.activeElement;if((x==null?void 0:x.tagName)!=="BODY"&&h.contains(x))for(;x&&(w.push(x),x!==h);)x=x.parentElement;return w}function S(h){var x;let w=Array.from(h.querySelectorAll("[id]"));return(x=h.getAttribute)!=null&&x.call(h,"id")&&w.push(h),w}function M(h,w,x,T){for(let W of T){let R=W.getAttribute("id");if(w.has(R)){let B=W;for(;B;){let _=h.get(B);if(_==null&&(_=new Set,h.set(B,_)),_.add(R),B===x)break;B=B.parentElement}}}}function k(h,w){let x=S(h),T=S(w),W=E(x,T),R=new Map;M(R,W,h,x);let B=w.__idiomorphRoot||w;return M(R,W,B,T),{persistentIds:W,idMap:R}}function E(h,w){let x=new Set,T=new Map;for(let{id:R,tagName:B}of h)T.has(R)?x.add(R):T.set(R,B);let W=new Set;for(let{id:R,tagName:B}of w)W.has(R)?x.add(R):T.get(R)===B&&W.add(R);for(let R of x)W.delete(R);return W}return u})(),{normalizeElement:p,normalizeParent:m}=(function(){let u=new WeakSet;function f(M){return M instanceof Document?M.documentElement:M}function y(M){if(M==null)return document.createElement("div");if(typeof M=="string")return y(S(M));if(u.has(M))return M;if(M instanceof Node){if(M.parentNode)return new A(M);{let k=document.createElement("div");return k.append(M),k}}else{let k=document.createElement("div");for(let E of[...M])k.append(E);return k}}class A{constructor(k){this.originalNode=k,this.realParentNode=k.parentNode,this.previousSibling=k.previousSibling,this.nextSibling=k.nextSibling}get childNodes(){let k=[],E=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;E&&E!=this.nextSibling;)k.push(E),E=E.nextSibling;return k}querySelectorAll(k){return this.childNodes.reduce((E,h)=>{if(h instanceof Element){h.matches(k)&&E.push(h);let w=h.querySelectorAll(k);for(let x=0;x<w.length;x++)E.push(w[x])}return E},[])}insertBefore(k,E){return this.realParentNode.insertBefore(k,E)}moveBefore(k,E){return this.realParentNode.moveBefore(k,E)}get __idiomorphRoot(){return this.originalNode}}function S(M){let k=new DOMParser,E=M.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(E.match(/<\/html>/)||E.match(/<\/head>/)||E.match(/<\/body>/)){let h=k.parseFromString(M,"text/html");if(E.match(/<\/html>/))return u.add(h),h;{let w=h.firstChild;return w&&u.add(w),w}}else{let w=k.parseFromString("<body><template>"+M+"</template></body>","text/html").body.querySelector("template").content;return u.add(w),w}}return{normalizeElement:f,normalizeParent:y}})();return{morph:r,defaults:e}})();var wl=(t,e,r={})=>{let{preserveTypingAnimation:n=!0}=r;Zh.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var vl={index:-1,draft:""};function ex(t){let{direction:e,history:r,currentValue:n,atStart:o,state:s}=t,a=s.index!==-1;if(r.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:n}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<r.length-1){let i=s.index+1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...vl}}}function tx(t,e){var r,n,o,s,a,i,d,l,p,m,u,f,y,A,S,M,k,E,h,w,x,T,W,R,B,_,V,oe,be,Qe,je,ve,Ee,Ge,_e,X,Ue,K;return[t.id,t.role,(n=(r=t.content)==null?void 0:r.length)!=null?n:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=t.llmContent)==null?void 0:l.length)!=null?p:0,(u=(m=t.approval)==null?void 0:m.status)!=null?u:"",(y=(f=t.toolCall)==null?void 0:f.status)!=null?y:"",(S=(A=t.toolCall)==null?void 0:A.name)!=null?S:"",(E=(k=(M=t.toolCall)==null?void 0:M.chunks)==null?void 0:k.length)!=null?E:0,(T=(x=(w=(h=t.toolCall)==null?void 0:h.chunks)==null?void 0:w[t.toolCall.chunks.length-1])==null?void 0:x.slice(-32))!=null?T:"",typeof((W=t.toolCall)==null?void 0:W.args)=="string"?t.toolCall.args.length:(R=t.toolCall)!=null&&R.args?JSON.stringify(t.toolCall.args).length:0,(V=(_=(B=t.reasoning)==null?void 0:B.chunks)==null?void 0:_.length)!=null?V:0,(je=(Qe=(be=(oe=t.reasoning)==null?void 0:oe.chunks)==null?void 0:be[t.reasoning.chunks.length-1])==null?void 0:Qe.length)!=null?je:0,(_e=(Ge=(Ee=(ve=t.reasoning)==null?void 0:ve.chunks)==null?void 0:Ee[t.reasoning.chunks.length-1])==null?void 0:Ge.slice(-32))!=null?_e:"",(Ue=(X=t.contentParts)==null?void 0:X.length)!=null?Ue:0,(K=t.stopReason)!=null?K:"",e].join("\0")}function rx(){return new Map}function nx(t,e,r){let n=t.get(e);return n&&n.fingerprint===r?n.wrapper:null}function ox(t,e,r,n){t.set(e,{fingerprint:r,wrapper:n})}function ax(t,e){for(let r of t.keys())e.has(r)||t.delete(r)}function Cl(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Os(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function _s(t,e){return Os(t)-t.scrollTop<=e}function Al(t){let{following:e,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=t,p=r-n;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:r}:!e&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Sl(t){let{following:e,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=t;return e&&r<0?"pause":!e&&o&&r>0&&n?"resume":"none"}var Ur={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},qr=1e5,Ro=qr+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},kw=["pre","code","a","script","style"],Tl=t=>{var e,r,n,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Ns.type,placeholder:(r=t==null?void 0:t.placeholder)!=null?r:Ns.placeholder,speed:(n=t==null?void 0:t.speed)!=null?n:Ns.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Ns.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Ns.buffer}},ix=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Fs=new Map;for(let t of ix)Fs.set(t.name,t);var ca=t=>{Fs.set(t.name,t)},Dp=t=>{ix.some(e=>e.name===t)||Fs.delete(t)},Op=()=>Array.from(Fs.keys()),$s=(t,e)=>{var r,n;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(r=e[t])!=null?r:null:(n=Fs.get(t))!=null?n:null},kl=(t,e,r,n,o)=>{if(!o)return t;if(r!=null&&r.bufferContent)return r.bufferContent(t,n);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
65
|
-
`);return s<0?"":t.slice(0,s)}return t},
|
|
64
|
+
_Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]}),Xh=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Ba=class t{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=e=>{var r,n,o,s,a,i,d,l;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall;((r=e.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Io(p.name)&&this.enqueueWebMcpAwait(e.message),(n=e.message.agentMetadata)!=null&&n.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(o=e.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=e.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var n,o;this.messages=[...(n=e.initialMessages)!=null?n:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new sa(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Bs((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,r,n;return(n=(r=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:r.call(e))!=null?n:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var r,n,o;try{let s=e||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=da(s);let a=(r=this.config.voiceRecognition)!=null?r:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,u,f,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}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((u=l.text)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.text)!=null&&f.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(C=this.pendingVoiceAssistantMessageId)!=null?C:(x=[...this.messages].reverse().find(k=>k.role==="assistant"))==null?void 0:x.id;S&&this.ttsSpokenMessageIds.add(S)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,n,o,s,a,i,d,l,p;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=e.runtype)==null?void 0:n.agentId)||"",clientToken:((o=e.runtype)==null?void 0:o.clientToken)||"",host:(s=e.runtype)==null?void 0:s.host,voiceId:(a=e.runtype)==null?void 0:a.voiceId,pauseDuration:(i=e.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=e.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=e.browser)==null?void 0:l.language)||"en-US",continuous:(p=e.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var e,r;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(r=(e=this.callbacks).onError)==null||r.call(e,n instanceof Error?n:new Error(String(n))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,r){return this.client.submitMessageFeedback(e,r)}async submitCSATFeedback(e,r){return this.client.submitCSATFeedback(e,r)}async submitNPSFeedback(e,r){return this.client.submitNPSFeedback(e,r)}updateConfig(e){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config={...this.config,...e},this.client=new sa(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:r,content:n,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=e,f={id:a!=null?a:r==="user"?Wa():r==="assistant"?ia():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let r=[];for(let n of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:u,rawContent:f}=n,C={id:d!=null?d:o==="user"?Wa():o==="assistant"?ia():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(e){let{component:r,props:n={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,l={text:o,component:r,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,r){var l,p,m,u,f;let n=e.trim();if(!n&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Wa(),s=ia(),a={id:o,role:"user",content:n||el,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(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let S=Kh(x,this.config.errorMessage);if(S){let k={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(k)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(f=(u=this.callbacks).onError)==null||f.call(u,new Error(String(x))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=ia();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:r.signal,assistantMessageId:e},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Kh(l,this.config.errorMessage);if(m){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,r){var o,s,a;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(e,r){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:r,resolvedAt:Date.now()}}),n(r==="approved")}async resolveApproval(e,r){var d,l,p,m;let n=`approval-${e.id}`,o={...e,status:r,resolvedAt:Date.now()},s={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},r):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},r),u){let f=null;if(u instanceof Response){if(!u.ok){let x=await u.json().catch(()=>null);throw new Error((l=x==null?void 0:x.error)!=null?l:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let f=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||(m=(p=this.callbacks).onError)==null||m.call(p,u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(e,r){var p,m,u,f,x,C,S,k,T,M,h,w;let n=this.messages.find(y=>y.id===e.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(x=(f=this.callbacks).onError)==null||x.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 y=(C=e.toolCall)==null?void 0:C.args,E=Array.isArray(y==null?void 0:y.questions)?y.questions:[];if(E.length===1){let B=typeof((S=E[0])==null?void 0:S.question)=="string"?E[0].question:"";B&&(a={[B]:r})}}this.markAskUserQuestionResolved(e,a),(k=this.abortController)==null||k.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let y=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:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let y=a!=null?a:{};l.forEach((E,B)=>{let P=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!P)return;let R=y[P],O=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${B}`,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${B}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let y=await this.client.resumeFlow(o,{[s]:r});if(!y.ok){let E=await y.json().catch(()=>null);throw new Error((M=E==null?void 0:E.error)!=null?M:`Resume failed: ${y.status}`)}y.body?await this.connectStream(y.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(y){let E=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(w=(h=this.callbacks).onError)==null||w.call(h,y instanceof Error?y:new Error(String(y)))}}enqueueWebMcpAwait(e){var s,a;let r=(s=e.agentMetadata)==null?void 0:s.executionId,n=(a=e.toolCall)==null?void 0:a.id;if(!r||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(r);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,o)),!o.seen.has(n)&&(o.seen.add(n),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(e){let r=this.webMcpAwaitBatches.get(e);if(!r)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=r;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(e,n)}resolveWebMcpToolStartedAt(e){var o,s;let r=this.messages.find(a=>a.id===e.id),n=[(o=r==null?void 0:r.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of n)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(e){let r=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),r}markWebMcpToolComplete(e,r,n,o=Date.now()){this.messages.some(s=>s.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:r,startedAt:n,completedAt:o,duration:void 0,durationMs:Math.max(0,o-n)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,r){var d,l,p;let n=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(r.map(async m=>{var h,w,y,E,B,P,R;let u=(h=m.toolCall)==null?void 0:h.name,f=(w=m.toolCall)==null?void 0:w.id;if(!u||!f)return null;let x=`${e}:${f}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x))return null;this.webMcpInflightKeys.add(x),n.push(x);let C=this.markWebMcpToolRunning(m),S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let k=(E=(y=m.agentMetadata)==null?void 0:y.webMcpToolCallId)!=null?E:u,T=this.client.executeWebMcpToolCall(u,(B=m.toolCall)==null?void 0:B.args,S.signal),M;if(!T)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await T}catch(O){let V=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return V||(R=(P=this.callbacks).onError)==null||R.call(P,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(m,Hs(V?"Aborted by cancel()":Xh(O)),C),this.webMcpInflightKeys.delete(x),null}return S.signal.aborted?(this.markWebMcpToolComplete(m,Hs("Aborted by cancel()"),C),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:k,output:M,toolMessage:m,startedAt:C,completedAt:Date.now()}})),i=[];try{if(i=a.filter(f=>f!==null),i.length===0)return;let m={};for(let f of i)m[f.resumeKey]=f.output;let u=await this.client.resumeFlow(e,m,{signal:s.signal});if(!u.ok){let f=await u.json().catch(()=>null);throw new Error((d=f==null?void 0:f.error)!=null?d:`Resume failed: ${u.status}`)}for(let f of i)this.webMcpResolvedKeys.add(f.dedupeKey),this.markWebMcpToolComplete(f.toolMessage,f.output,f.startedAt,f.completedAt);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(m){if(!(m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,m instanceof Error?m:new Error(String(m)));else for(let f of i)this.markWebMcpToolComplete(f.toolMessage,Hs("Aborted by cancel()"),f.startedAt)}finally{for(let m of n)this.webMcpInflightKeys.delete(m);for(let m of o)this.webMcpResolveControllers.delete(m);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var f,x,C,S,k,T,M,h,w,y,E,B;let r=(f=e.agentMetadata)==null?void 0:f.executionId,n=(x=e.toolCall)==null?void 0:x.name,o=(C=e.toolCall)==null?void 0:C.id;if(!r){(k=(S=this.callbacks).onError)==null||k.call(S,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let P=`${r}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);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(P)}catch(R){(M=(T=this.callbacks).onError)==null||M.call(T,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(P)}return}let s=`${r}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(h=e.toolCall)==null?void 0:h.args,p=this.client.executeWebMcpToolCall(n,l,d),m="execute",u=a;try{let P;if(p?P=await p:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Hs("Aborted by cancel()"),a);return}let R=(y=(w=e.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?y:n;m="resume",await this.resumeWithToolOutput(r,R,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,P,a,u)},signal:d})}catch(P){let R=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(m==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(e,Hs(R||d.aborted?"Aborted by cancel()":Xh(P)),a),R||(B=(E=this.callbacks).onError)==null||B.call(E,P instanceof Error?P:new Error(String(P)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,r,n,o){var a,i;let s=await this.client.resumeFlow(e,{[r]:n},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let r=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:r,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(r,s),this.selectedArtifactId=r,this.emitArtifactsState(),s}let n={id:r,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(r,n),this.selectedArtifactId=r,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,r;(r=(e=this.callbacks).onArtifactsState)==null||r.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var r,n;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(r=e.component)!=null?r:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,r=null){this.artifacts.clear();for(let n of e)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let r=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),r&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let n=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,e)}speak(e,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(e),s=n.getVoices();if(r.voice){let a=s.find(i=>i.name===r.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):t.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(e){var n;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=e.find(a=>a.name===o);if(s)return s}return(n=e.find(o=>o.lang.startsWith("en")))!=null?n:e[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),n=this.messages.findIndex(o=>o.id===r.id);if(n===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>{var p,m,u,f,x,C,S,k,T,M;if(s!==n)return o;let a={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(a.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=r.toolCall)==null?void 0:m.name,d=(u=r.agentMetadata)==null?void 0:u.executionId,l=(f=r.toolCall)==null?void 0:f.id;if(i&&Io(i)&&d&&l&&((x=r.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let h=`${d}:${l}`,w=this.webMcpInflightKeys.has(h),y=this.webMcpResolvedKeys.has(h),E=(C=o.toolCall)==null?void 0:C.name,B=((S=o.agentMetadata)==null?void 0:S.executionId)===d&&((k=o.toolCall)==null?void 0:k.id)===l&&E!==void 0&&Io(E)&&((T=o.toolCall)==null?void 0:T.status)==="complete";(w||y||B)&&(a.agentMetadata={...(M=a.agentMetadata)!=null?M:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,n)=>{var d,l;let o=new Date(r.createdAt).getTime(),s=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=r.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return a!==i?a-i:r.id.localeCompare(n.id)})}};var v=(t,e)=>{let r=document.createElement(t);return e&&(r.className=e),r},Qn=(t,e,r)=>{let n=t.createElement(e);return r&&(n.className=r),n};var Hd=[["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 Dd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Od=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Nd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var _d=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Fd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var $d=[["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 Ud=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var qd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var zd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var Vd=[["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 Gd=[["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 Kd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Xd=[["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 Jd=[["path",{d:"M20 6 9 17l-5-5"}]];var Qd=[["path",{d:"m6 9 6 6 6-6"}]];var Yd=[["path",{d:"m15 18-6-6 6-6"}]];var Zd=[["path",{d:"m9 18 6-6-6-6"}]];var ec=[["path",{d:"m18 15-6-6-6 6"}]];var al=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var sl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var tc=[["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 rc=[["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 nc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var oc=[["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 ac=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var sc=[["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 ic=[["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 il=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var ll=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var lc=[["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 dc=[["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 cc=[["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 pc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var uc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var fc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];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"}]];var gc=[["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 hc=[["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 xc=[["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 yc=[["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 bc=[["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 dl=[["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 wc=[["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 vc=[["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 Cc=[["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 Ac=[["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 Sc=[["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 Tc=[["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 cl=[["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 Mc=[["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 kc=[["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 Ec=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Lc=[["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 Pc=[["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 pl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Ic=[["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 Rc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Wc=[["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 Bc=[["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 Hc=[["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 Dc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Oc=[["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 Nc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var _c=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Fc=[["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 $c=[["path",{d:"M5 12h14"}]];var Uc=[["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 qc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var zc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Vc=[["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 Gc=[["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 Kc=[["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 Xc=[["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 Jc=[["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 Qc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Yc=[["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 Zc=[["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 ep=[["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 tp=[["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 rp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var np=[["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 op=[["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 ap=[["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 sp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var ip=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var ul=[["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 lp=[["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 dp=[["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 cp=[["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 pp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var fl=[["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 up=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var fp=[["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 mp=[["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 gp=[["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 hp=[["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 xp=[["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 yp=[["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 bp=[["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 wp=[["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 vp=[["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 ml=[["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 Cp=[["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 Ap=[["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 Sp=[["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 Tp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Mp=[["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 kp=[["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 Ep=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Lp=[["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 yw={activity:Hd,"arrow-down":Dd,"arrow-up":Fd,"arrow-up-right":_d,bot:Vd,"chevron-down":Qd,"chevron-up":ec,"chevron-right":Zd,"chevron-left":Yd,check:Jd,clipboard:rc,"clipboard-copy":tc,copy:oc,file:mc,"file-code":pc,"file-spreadsheet":uc,"file-text":fc,"image-plus":Mc,loader:Ic,"loader-circle":pl,mic:_c,paperclip:Vc,"refresh-cw":Zc,search:rp,send:np,"shield-alert":sp,"shield-check":ip,"shield-x":ul,square:up,"thumbs-down":xp,"thumbs-up":yp,upload:Ap,"volume-2":Tp,x:Ep,user:Sp,mail:Wc,phone:Xc,calendar:Kd,clock:nc,building:jd,"map-pin":Bc,lock:Rc,key:Lc,"credit-card":ac,"at-sign":$d,hash:Cc,globe:vc,link:Pc,"circle-check":al,"circle-x":sl,"triangle-alert":ml,info:Ec,ban:Ud,shield:lp,"arrow-left":Od,"arrow-right":Nd,"external-link":lc,ellipsis:ll,"ellipsis-vertical":il,menu:Dc,house:cl,plus:Qc,minus:$c,pencil:Gc,trash:vp,"trash-2":wp,save:tp,download:ic,share:ap,funnel:dl,settings:op,"rotate-cw":ep,maximize:Hc,minimize:Fc,"shopping-cart":cp,"shopping-bag":dp,package:zc,truck:Cp,tag:hp,gift:wc,receipt:Yc,wallet:kp,store:mp,"dollar-sign":sc,percent:Kc,play:Jc,pause:jc,"volume-x":Mp,camera:Xd,image:kc,film:hc,headphones:Ac,"message-circle":Oc,"message-square":Nc,bell:qd,heart:Sc,star:fp,eye:cc,"eye-off":dc,bookmark:zd,"calendar-days":Gd,history:Tc,timer:bp,folder:bc,"folder-open":yc,files:gc,sparkles:fl,zap:Lp,sun:gp,moon:qc,flag:xc,monitor:Uc,smartphone:pp},Ie=(t,e=24,r="currentColor",n=2)=>{let o=yw[t];return o?bw(o,e,r,n):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function bw(t,e,r,n){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var gl={allowedTypes:mo,maxFileSize:10*1024*1024,maxFiles:4};function ww(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vw(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var ca=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=e.allowedTypes)!=null?r:gl.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:gl.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:gl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:gl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var r,n,o,s,a,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(n=(r=this.config).onFileRejected)==null||n.call(r,l,"count");continue}let p=jh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await Vh(l),u=tl(l)?URL.createObjectURL(l):null,f={id:ww(),file:l,previewUrl:u,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let r=this.attachments.findIndex(d=>d.id===e);if(r===-1)return;let n=this.attachments[r];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,r;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(e=this.config).onAttachmentsChange)==null||r.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let r=tl(e.file),n=v("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",e.id),n.style.width="48px",n.style.height="48px",r&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=vw(e.file.type),d=Ie(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=v("span");l.textContent=Gh(e.file.type,e.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),n.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,r){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:r})}};var Jh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ds(t,e){if(!t)return e;if(!e)return t;let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];Jh(s)&&Jh(o)?r[n]=Ds(s,o):r[n]=o}return r}var yn="min(440px, calc(100vw - 24px))",hl="440px",er={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:yn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Qh(t,e){if(!(!t&&!e))return t?e?Ds(t,e):t:e}function xl(t){var e,r,n,o,s,a,i,d,l,p,m,u,f,x,C,S,k,T,M,h,w;return t?{...er,...t,theme:Qh(er.theme,t.theme),darkTheme:Qh(er.darkTheme,t.darkTheme),launcher:{...er.launcher,...t.launcher,dock:{...(e=er.launcher)==null?void 0:e.dock,...(r=t.launcher)==null?void 0:r.dock},clearChat:{...(n=er.launcher)==null?void 0:n.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...er.copy,...t.copy},sendButton:{...er.sendButton,...t.sendButton},statusIndicator:{...er.statusIndicator,...t.statusIndicator},voiceRecognition:{...er.voiceRecognition,...t.voiceRecognition},features:(()=>{var Ee,Ke,Ne,X,Ue,K,Te,oe;let y=(Ee=er.features)==null?void 0:Ee.artifacts,E=(Ke=t.features)==null?void 0:Ke.artifacts,B=(Ne=er.features)==null?void 0:Ne.scrollToBottom,P=(X=t.features)==null?void 0:X.scrollToBottom,R=(Ue=er.features)==null?void 0:Ue.streamAnimation,O=(K=t.features)==null?void 0:K.streamAnimation,V=(Te=er.features)==null?void 0:Te.askUserQuestion,ne=(oe=t.features)==null?void 0:oe.askUserQuestion,be=y===void 0&&E===void 0?void 0:{...y,...E,layout:{...y==null?void 0:y.layout,...E==null?void 0:E.layout}},Ye=B===void 0&&P===void 0?void 0:{...B,...P},Ge=R===void 0&&O===void 0?void 0:{...R,...O},ve=V===void 0&&ne===void 0?void 0:{...V,...ne,styles:{...V==null?void 0:V.styles,...ne==null?void 0:ne.styles}};return{...er.features,...t.features,...Ye!==void 0?{scrollToBottom:Ye}:{},...be!==void 0?{artifacts:be}:{},...Ge!==void 0?{streamAnimation:Ge}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:er.suggestionChips,suggestionChipsConfig:{...er.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...er.layout,...t.layout,header:{...(a=er.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=er.layout)==null?void 0:d.messages,...(l=t.layout)==null?void 0:l.messages,avatar:{...(m=(p=er.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(f=(u=t.layout)==null?void 0:u.messages)==null?void 0:f.avatar},timestamp:{...(C=(x=er.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(k=(S=t.layout)==null?void 0:S.messages)==null?void 0:k.timestamp}},slots:{...(T=er.layout)==null?void 0:T.slots,...(M=t.layout)==null?void 0:M.slots}},markdown:{...er.markdown,...t.markdown,options:{...(h=er.markdown)==null?void 0:h.options,...(w=t.markdown)==null?void 0:w.options}},messageActions:{...er.messageActions,...t.messageActions}}:er}var Pp={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"}},Ip={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"}},Rp={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:hl,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(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let r=e.split("."),n=t;for(let o of r){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ha(t,n):n}function yl(t){let e={};function r(n,o){for(let[s,a]of Object.entries(n)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ha(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&r(a,i)}}return r(t.palette,"palette"),r(t.semantic,"semantic"),r(t.components,"components"),e}function Wp(t){let e=[],r=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:r}}function Yh(t,e){let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?r[n]=Yh(s,o):r[n]=o}return r}function Cw(t,e){return e?Yh(t,e):t}function Da(t,e={}){var o,s,a,i,d,l,p,m,u,f,x,C,S;let r={palette:Pp,semantic:Ip,components:Rp},n={palette:{...r.palette,...t==null?void 0:t.palette,colors:{...r.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...r.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...r.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...r.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...r.palette.radius,...(l=t==null?void 0:t.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...t==null?void 0:t.semantic,colors:{...r.semantic.colors,...(p=t==null?void 0:t.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(x=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=t==null?void 0:t.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(S=t==null?void 0:t.semantic)==null?void 0:S.typography}},components:Cw(r.components,t==null?void 0:t.components)};if(e.validate!==!1){let k=Wp(n);if(!k.valid)throw new Error(`Theme validation failed: ${k.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let k of e.plugins)n=k.transform(n);return n}function bl(t){var C,S,k,T,M,h,w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve,Ee,Ke,Ne,X,Ue,K,Te,oe,xe,Me,Xe,ce,te,le,ut,Ce,he,rt,_e,me,J,ze,Z,ge,z,Re,Ae,fe,pe,Be,Q,_,ke,He,Ve,Je,gt,at,Mt,Xt,G,Jt,st,_t,de,ye,Rt,ar,kt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,I,ee,Se,nt,Qt,Ft,tr,Pr,Nr,wn,Vt,$t,Ir,vn,bo,eo,wo,qn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn;let e=yl(t),r={};for(let[W,pn]of Object.entries(e)){let Bn=W.replace(/\./g,"-");r[`--persona-${Bn}`]=pn.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(S=r["--persona-semantic-colors-secondary"])!=null?S:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(k=r["--persona-semantic-colors-accent"])!=null?k:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(T=r["--persona-semantic-colors-surface"])!=null?T: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"]=(h=r["--persona-semantic-colors-container"])!=null?h: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"]=(y=r["--persona-semantic-colors-text-muted"])!=null?y: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"]=(P=r["--persona-semantic-colors-divider"])!=null?P:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(R=r["--persona-components-voice-recording-indicator"])!=null?R:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(O=r["--persona-components-voice-recording-background"])!=null?O:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(V=r["--persona-components-voice-processing-icon"])!=null?V:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(ne=r["--persona-components-voice-speaking-icon"])!=null?ne:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(be=r["--persona-components-approval-requested-background"])!=null?be:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ye=r["--persona-components-approval-requested-border"])!=null?Ye:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ge=r["--persona-components-approval-requested-text"])!=null?Ge:r["--persona-palette-colors-gray-900"],r["--persona-approval-approve-bg"]=(ve=r["--persona-components-approval-approve-background"])!=null?ve:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Ee=r["--persona-components-approval-deny-background"])!=null?Ee:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(Ke=r["--persona-components-attachment-image-background"])!=null?Ke:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(Ne=r["--persona-components-attachment-image-border"])!=null?Ne:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(X=r["--persona-semantic-typography-fontFamily"])!=null?X:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(Ue=r["--persona-semantic-typography-fontSize"])!=null?Ue:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(K=r["--persona-semantic-typography-fontWeight"])!=null?K:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Te=r["--persona-semantic-typography-lineHeight"])!=null?Te:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(oe=r["--persona-palette-radius-sm"])!=null?oe:"0.125rem",r["--persona-radius-md"]=(xe=r["--persona-palette-radius-md"])!=null?xe:"0.375rem",r["--persona-radius-lg"]=(Me=r["--persona-palette-radius-lg"])!=null?Me:"0.5rem",r["--persona-radius-xl"]=(Xe=r["--persona-palette-radius-xl"])!=null?Xe:"0.75rem",r["--persona-radius-full"]=(ce=r["--persona-palette-radius-full"])!=null?ce:"9999px",r["--persona-launcher-radius"]=(le=(te=r["--persona-components-launcher-borderRadius"])!=null?te:r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-bg"]=(ut=r["--persona-components-launcher-background"])!=null?ut:r["--persona-primary"],r["--persona-launcher-fg"]=(Ce=r["--persona-components-launcher-foreground"])!=null?Ce:r["--persona-text-inverse"],r["--persona-launcher-border"]=(he=r["--persona-components-launcher-border"])!=null?he:r["--persona-border"],r["--persona-button-primary-bg"]=(rt=r["--persona-components-button-primary-background"])!=null?rt:r["--persona-primary"],r["--persona-button-primary-fg"]=(_e=r["--persona-components-button-primary-foreground"])!=null?_e:r["--persona-text-inverse"],r["--persona-button-radius"]=(J=(me=r["--persona-components-button-primary-borderRadius"])!=null?me:r["--persona-palette-radius-full"])!=null?J:"9999px",r["--persona-panel-radius"]=(Z=(ze=r["--persona-components-panel-borderRadius"])!=null?ze:r["--persona-radius-xl"])!=null?Z:"0.75rem",r["--persona-panel-border"]=(ge=r["--persona-components-panel-border"])!=null?ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Re=(z=r["--persona-components-panel-shadow"])!=null?z:r["--persona-palette-shadows-xl"])!=null?Re:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-input-radius"]=(fe=(Ae=r["--persona-components-input-borderRadius"])!=null?Ae:r["--persona-radius-lg"])!=null?fe:"0.5rem",r["--persona-message-user-radius"]=(Be=(pe=r["--persona-components-message-user-borderRadius"])!=null?pe:r["--persona-radius-lg"])!=null?Be:"0.5rem",r["--persona-message-assistant-radius"]=(_=(Q=r["--persona-components-message-assistant-borderRadius"])!=null?Q:r["--persona-radius-lg"])!=null?_:"0.5rem",r["--persona-header-bg"]=(ke=r["--persona-components-header-background"])!=null?ke:r["--persona-surface"],r["--persona-header-border"]=(He=r["--persona-components-header-border"])!=null?He:r["--persona-divider"],r["--persona-header-icon-bg"]=(Ve=r["--persona-components-header-iconBackground"])!=null?Ve:r["--persona-primary"],r["--persona-header-icon-fg"]=(Je=r["--persona-components-header-iconForeground"])!=null?Je:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(gt=r["--persona-components-header-titleForeground"])!=null?gt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(at=r["--persona-components-header-subtitleForeground"])!=null?at:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Mt=r["--persona-components-header-actionIconForeground"])!=null?Mt:r["--persona-muted"];let n=(Xt=t.components)==null?void 0:Xt.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(G=t.components)==null?void 0:G.introCard;r["--persona-intro-card-bg"]=(Jt=r["--persona-components-introCard-background"])!=null?Jt:r["--persona-surface"],r["--persona-intro-card-radius"]=(st=r["--persona-components-introCard-borderRadius"])!=null?st:"1rem",r["--persona-intro-card-padding"]=(_t=r["--persona-components-introCard-padding"])!=null?_t:"1.5rem",r["--persona-intro-card-shadow"]=(ye=(de=o==null?void 0:o.shadow)!=null?de:r["--persona-components-introCard-shadow"])!=null?ye:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Rt=r["--persona-components-input-background"])!=null?Rt:r["--persona-surface"],r["--persona-input-placeholder"]=(ar=r["--persona-components-input-placeholder"])!=null?ar:r["--persona-text-muted"],r["--persona-message-user-bg"]=(kt=r["--persona-components-message-user-background"])!=null?kt:r["--persona-accent"],r["--persona-message-user-text"]=(mr=r["--persona-components-message-user-text"])!=null?mr:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Ot=r["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Wt=r["--persona-components-message-assistant-background"])!=null?Wt:r["--persona-surface"],r["--persona-message-assistant-text"]=(St=r["--persona-components-message-assistant-text"])!=null?St:r["--persona-text"],r["--persona-message-assistant-border"]=(Et=r["--persona-components-message-assistant-border"])!=null?Et:r["--persona-border"],r["--persona-message-assistant-shadow"]=(sr=r["--persona-components-message-assistant-shadow"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(dr=(ft=r["--persona-components-scrollToBottom-background"])!=null?ft:r["--persona-button-primary-bg"])!=null?dr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Lr=(wr=r["--persona-components-scrollToBottom-foreground"])!=null?wr:r["--persona-button-primary-fg"])!=null?Lr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(Or=r["--persona-components-scrollToBottom-border"])!=null?Or:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(xt=r["--persona-components-scrollToBottom-size"])!=null?xt:"40px",r["--persona-scroll-to-bottom-radius"]=(Un=(fr=(sn=r["--persona-components-scrollToBottom-borderRadius"])!=null?sn:r["--persona-button-radius"])!=null?fr:r["--persona-radius-full"])!=null?Un:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Zn=(Rr=r["--persona-components-scrollToBottom-shadow"])!=null?Rr:r["--persona-palette-shadows-sm"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Pn=r["--persona-components-scrollToBottom-padding"])!=null?Pn:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(In=r["--persona-components-scrollToBottom-gap"])!=null?In:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(I=(ue=r["--persona-components-scrollToBottom-fontSize"])!=null?ue:r["--persona-palette-typography-fontSize-sm"])!=null?I:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(ee=r["--persona-components-scrollToBottom-iconSize"])!=null?ee:"14px",r["--persona-tool-bubble-shadow"]=(Se=r["--persona-components-toolBubble-shadow"])!=null?Se:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(nt=r["--persona-components-reasoningBubble-shadow"])!=null?nt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Qt=r["--persona-components-composer-shadow"])!=null?Qt:"none",r["--persona-md-inline-code-bg"]=(Ft=r["--persona-components-markdown-inlineCode-background"])!=null?Ft:r["--persona-container"],r["--persona-md-inline-code-color"]=(tr=r["--persona-components-markdown-inlineCode-foreground"])!=null?tr:r["--persona-text"],r["--persona-md-link-color"]=(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"]=($t=r["--persona-components-markdown-codeBlock-textColor"])!=null?$t:"inherit",r["--persona-md-table-header-bg"]=(Ir=r["--persona-components-markdown-table-headerBackground"])!=null?Ir:r["--persona-container"],r["--persona-md-table-border-color"]=(vn=r["--persona-components-markdown-table-borderColor"])!=null?vn:r["--persona-border"],r["--persona-md-hr-color"]=(bo=r["--persona-components-markdown-hr-color"])!=null?bo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(eo=r["--persona-components-markdown-blockquote-borderColor"])!=null?eo:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(wo=r["--persona-components-markdown-blockquote-background"])!=null?wo:"transparent",r["--persona-md-blockquote-text-color"]=(qn=r["--persona-components-markdown-blockquote-textColor"])!=null?qn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(ln=r["--persona-components-collapsibleWidget-container"])!=null?ln:r["--persona-surface"],r["--cw-surface"]=(Rn=r["--persona-components-collapsibleWidget-surface"])!=null?Rn:r["--persona-surface"],r["--cw-border"]=(Pt=r["--persona-components-collapsibleWidget-border"])!=null?Pt:r["--persona-border"],r["--persona-message-border"]=(gr=r["--persona-components-message-border"])!=null?gr:r["--persona-border"];let p=t.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(r["--persona-icon-btn-bg"]=m.background),m.border&&(r["--persona-icon-btn-border"]=m.border),m.color&&(r["--persona-icon-btn-color"]=m.color),m.padding&&(r["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(r["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(r["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(r["--persona-icon-btn-active-border"]=m.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let W=x.toolbar;W.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=W.iconHoverColor),W.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=W.iconHoverBackground),W.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=W.iconPadding),W.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=W.iconBorderRadius),W.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=W.iconBorder),W.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=W.toggleGroupGap),W.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=W.toggleBorderRadius),W.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=W.copyBackground),W.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=W.copyBorder),W.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=W.copyColor),W.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=W.copyBorderRadius),W.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=W.copyPadding),W.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=W.copyMenuBackground,r["--persona-dropdown-bg"]=(hr=r["--persona-dropdown-bg"])!=null?hr:W.copyMenuBackground),W.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=W.copyMenuBorder,r["--persona-dropdown-border"]=(dn=r["--persona-dropdown-border"])!=null?dn:W.copyMenuBorder),W.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=W.copyMenuShadow,r["--persona-dropdown-shadow"]=(vo=r["--persona-dropdown-shadow"])!=null?vo:W.copyMenuShadow),W.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=W.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Cn=r["--persona-dropdown-radius"])!=null?Cn:W.copyMenuBorderRadius),W.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=W.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Wn=r["--persona-dropdown-item-hover-bg"])!=null?Wn:W.copyMenuItemHoverBackground),W.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=W.iconBackground),W.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=W.toolbarBorder)}if(x!=null&&x.tab){let W=x.tab;W.background&&(r["--persona-artifact-tab-bg"]=W.background),W.activeBackground&&(r["--persona-artifact-tab-active-bg"]=W.activeBackground),W.activeBorder&&(r["--persona-artifact-tab-active-border"]=W.activeBorder),W.borderRadius&&(r["--persona-artifact-tab-radius"]=W.borderRadius),W.textColor&&(r["--persona-artifact-tab-color"]=W.textColor),W.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=W.hoverBackground),W.listBackground&&(r["--persona-artifact-tab-list-bg"]=W.listBackground),W.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=W.listBorderColor),W.listPadding&&(r["--persona-artifact-tab-list-padding"]=W.listPadding)}if(x!=null&&x.pane){let W=x.pane;if(W.toolbarBackground){let pn=(cn=Ha(t,W.toolbarBackground))!=null?cn:W.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pn}}return r}var Zh={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 Aw={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"}}},ex=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Os=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Sw=t=>{var r;let e=(r=t==null?void 0:t.colorScheme)!=null?r:"light";return e==="light"?"light":e==="dark"?"dark":Os()},Bp=t=>Sw(t),Tw=t=>Da(t),Mw=t=>{var r;let e=Da(void 0,{validate:!1});return Da({...t,palette:{...e.palette,colors:{...Aw.colors,...(r=t==null?void 0:t.palette)==null?void 0:r.colors}}},{validate:!1})},Oa=t=>{let e=Bp(t),r=ex(t==null?void 0:t.theme),n=ex(t==null?void 0:t.darkTheme);return e==="dark"?Mw(Ds(r!=null?r:{},n!=null?n:{})):Tw(r)},kw=t=>bl(t),Ro=(t,e)=>{var s;let r=Oa(e),n=kw(r);for(let[a,i]of Object.entries(n))t.style.setProperty(a,i);let o=(s=e==null?void 0:e.toolCall)==null?void 0:s.shadow;o!==void 0&&t.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},wl=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Os())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>t(Os());r.addEventListener?(r.addEventListener("change",n),e.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),e.push(()=>r.removeListener(n)))}return()=>{e.forEach(r=>r())}};var tx=(function(){"use strict";let t=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:t,afterNodeAdded:t,beforeNodeMorphed:t,afterNodeMorphed:t,beforeNodeRemoved:t,afterNodeRemoved:t,beforeAttributeUpdated:t},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:t,afterHeadMorphed:t},restoreFocus:!0};function r(u,f,x={}){u=p(u);let C=m(f),S=l(u,C,x),k=o(S,()=>i(S,u,C,T=>T.morphStyle==="innerHTML"?(s(T,u,C),Array.from(u.childNodes)):n(T,u,C)));return S.pantry.remove(),k}function n(u,f,x){let C=m(f);return s(u,C,x,f,f.nextSibling),Array.from(C.childNodes)}function o(u,f){var M;if(!u.config.restoreFocus)return f();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return f();let{id:C,selectionStart:S,selectionEnd:k}=x,T=f();return C&&C!==((M=document.activeElement)==null?void 0:M.getAttribute("id"))&&(x=u.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&k&&x.setSelectionRange(S,k),T}let s=(function(){function u(h,w,y,E=null,B=null){w instanceof HTMLTemplateElement&&y instanceof HTMLTemplateElement&&(w=w.content,y=y.content),E||(E=w.firstChild);for(let P of y.childNodes){if(E&&E!=B){let O=x(h,P,E,B);if(O){O!==E&&S(h,E,O),a(O,P,h),E=O.nextSibling;continue}}if(P instanceof Element){let O=P.getAttribute("id");if(h.persistentIds.has(O)){let V=k(w,O,E,h);a(V,P,h),E=V.nextSibling;continue}}let R=f(w,P,E,h);R&&(E=R.nextSibling)}for(;E&&E!=B;){let P=E;E=E.nextSibling,C(h,P)}}function f(h,w,y,E){if(E.callbacks.beforeNodeAdded(w)===!1)return null;if(E.idMap.has(w)){let B=document.createElement(w.tagName);return h.insertBefore(B,y),a(B,w,E),E.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(w,!0);return h.insertBefore(B,y),E.callbacks.afterNodeAdded(B),B}}let x=(function(){function h(E,B,P,R){let O=null,V=B.nextSibling,ne=0,be=P;for(;be&&be!=R;){if(y(be,B)){if(w(E,be,B))return be;O===null&&(E.idMap.has(be)||(O=be))}if(O===null&&V&&y(be,V)&&(ne++,V=V.nextSibling,ne>=2&&(O=void 0)),E.activeElementAndParents.includes(be))break;be=be.nextSibling}return O||null}function w(E,B,P){let R=E.idMap.get(B),O=E.idMap.get(P);if(!O||!R)return!1;for(let V of R)if(O.has(V))return!0;return!1}function y(E,B){var O,V,ne;let P=E,R=B;return P.nodeType===R.nodeType&&P.tagName===R.tagName&&(!((O=P.getAttribute)!=null&&O.call(P,"id"))||((V=P.getAttribute)==null?void 0:V.call(P,"id"))===((ne=R.getAttribute)==null?void 0:ne.call(R,"id")))}return h})();function C(h,w){var y;if(h.idMap.has(w))M(h.pantry,w,null);else{if(h.callbacks.beforeNodeRemoved(w)===!1)return;(y=w.parentNode)==null||y.removeChild(w),h.callbacks.afterNodeRemoved(w)}}function S(h,w,y){let E=w;for(;E&&E!==y;){let B=E;E=E.nextSibling,C(h,B)}return E}function k(h,w,y,E){var P,R;let B=((R=(P=E.target).getAttribute)==null?void 0:R.call(P,"id"))===w&&E.target||E.target.querySelector(`[id="${w}"]`)||E.pantry.querySelector(`[id="${w}"]`);return T(B,E),M(h,B,y),B}function T(h,w){let y=h.getAttribute("id");for(;h=h.parentNode;){let E=w.idMap.get(h);E&&(E.delete(y),E.size||w.idMap.delete(h))}}function M(h,w,y){if(h.moveBefore)try{h.moveBefore(w,y)}catch{h.insertBefore(w,y)}else h.insertBefore(w,y)}return u})(),a=(function(){function u(T,M,h){return h.ignoreActive&&T===document.activeElement?null:(h.callbacks.beforeNodeMorphed(T,M)===!1||(T instanceof HTMLHeadElement&&h.head.ignore||(T instanceof HTMLHeadElement&&h.head.style!=="morph"?d(T,M,h):(f(T,M,h),k(T,h)||s(h,T,M))),h.callbacks.afterNodeMorphed(T,M)),T)}function f(T,M,h){let w=M.nodeType;if(w===1){let y=T,E=M,B=y.attributes,P=E.attributes;for(let R of P)S(R.name,y,"update",h)||y.getAttribute(R.name)!==R.value&&y.setAttribute(R.name,R.value);for(let R=B.length-1;0<=R;R--){let O=B[R];if(O&&!E.hasAttribute(O.name)){if(S(O.name,y,"remove",h))continue;y.removeAttribute(O.name)}}k(y,h)||x(y,E,h)}(w===8||w===3)&&T.nodeValue!==M.nodeValue&&(T.nodeValue=M.nodeValue)}function x(T,M,h){if(T instanceof HTMLInputElement&&M instanceof HTMLInputElement&&M.type!=="file"){let w=M.value,y=T.value;C(T,M,"checked",h),C(T,M,"disabled",h),M.hasAttribute("value")?y!==w&&(S("value",T,"update",h)||(T.setAttribute("value",w),T.value=w)):S("value",T,"remove",h)||(T.value="",T.removeAttribute("value"))}else if(T instanceof HTMLOptionElement&&M instanceof HTMLOptionElement)C(T,M,"selected",h);else if(T instanceof HTMLTextAreaElement&&M instanceof HTMLTextAreaElement){let w=M.value,y=T.value;if(S("value",T,"update",h))return;w!==y&&(T.value=w),T.firstChild&&T.firstChild.nodeValue!==w&&(T.firstChild.nodeValue=w)}}function C(T,M,h,w){let y=M[h],E=T[h];if(y!==E){let B=S(h,T,"update",w);B||(T[h]=M[h]),y?B||T.setAttribute(h,""):S(h,T,"remove",w)||T.removeAttribute(h)}}function S(T,M,h,w){return T==="value"&&w.ignoreActiveValue&&M===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(T,M,h)===!1}function k(T,M){return!!M.ignoreActiveValue&&T===document.activeElement&&T!==document.body}return u})();function i(u,f,x,C){if(u.head.block){let S=f.querySelector("head"),k=x.querySelector("head");if(S&&k){let T=d(S,k,u);return Promise.all(T).then(()=>{let M=Object.assign(u,{head:{block:!1,ignore:!0}});return C(M)})}}return C(u)}function d(u,f,x){let C=[],S=[],k=[],T=[],M=new Map;for(let w of f.children)M.set(w.outerHTML,w);for(let w of u.children){let y=M.has(w.outerHTML),E=x.head.shouldReAppend(w),B=x.head.shouldPreserve(w);y||B?E?S.push(w):(M.delete(w.outerHTML),k.push(w)):x.head.style==="append"?E&&(S.push(w),T.push(w)):x.head.shouldRemove(w)!==!1&&S.push(w)}T.push(...M.values());let h=[];for(let w of T){let y=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(y)!==!1){if("href"in y&&y.href||"src"in y&&y.src){let E,B=new Promise(function(P){E=P});y.addEventListener("load",function(){E()}),h.push(B)}u.appendChild(y),x.callbacks.afterNodeAdded(y),C.push(y)}}for(let w of S)x.callbacks.beforeNodeRemoved(w)!==!1&&(u.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(u,{added:C,kept:k,removed:S}),h}let l=(function(){function u(h,w,y){let{persistentIds:E,idMap:B}=T(h,w),P=f(y),R=P.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:h,newContent:w,config:P,morphStyle:R,ignoreActive:P.ignoreActive,ignoreActiveValue:P.ignoreActiveValue,restoreFocus:P.restoreFocus,idMap:B,persistentIds:E,pantry:x(),activeElementAndParents:C(h),callbacks:P.callbacks,head:P.head}}function f(h){let w=Object.assign({},e);return Object.assign(w,h),w.callbacks=Object.assign({},e.callbacks,h.callbacks),w.head=Object.assign({},e.head,h.head),w}function x(){let h=document.createElement("div");return h.hidden=!0,document.body.insertAdjacentElement("afterend",h),h}function C(h){let w=[],y=document.activeElement;if((y==null?void 0:y.tagName)!=="BODY"&&h.contains(y))for(;y&&(w.push(y),y!==h);)y=y.parentElement;return w}function S(h){var y;let w=Array.from(h.querySelectorAll("[id]"));return(y=h.getAttribute)!=null&&y.call(h,"id")&&w.push(h),w}function k(h,w,y,E){for(let B of E){let P=B.getAttribute("id");if(w.has(P)){let R=B;for(;R;){let O=h.get(R);if(O==null&&(O=new Set,h.set(R,O)),O.add(P),R===y)break;R=R.parentElement}}}}function T(h,w){let y=S(h),E=S(w),B=M(y,E),P=new Map;k(P,B,h,y);let R=w.__idiomorphRoot||w;return k(P,B,R,E),{persistentIds:B,idMap:P}}function M(h,w){let y=new Set,E=new Map;for(let{id:P,tagName:R}of h)E.has(P)?y.add(P):E.set(P,R);let B=new Set;for(let{id:P,tagName:R}of w)B.has(P)?y.add(P):E.get(P)===R&&B.add(P);for(let P of y)B.delete(P);return B}return u})(),{normalizeElement:p,normalizeParent:m}=(function(){let u=new WeakSet;function f(k){return k instanceof Document?k.documentElement:k}function x(k){if(k==null)return document.createElement("div");if(typeof k=="string")return x(S(k));if(u.has(k))return k;if(k instanceof Node){if(k.parentNode)return new C(k);{let T=document.createElement("div");return T.append(k),T}}else{let T=document.createElement("div");for(let M of[...k])T.append(M);return T}}class C{constructor(T){this.originalNode=T,this.realParentNode=T.parentNode,this.previousSibling=T.previousSibling,this.nextSibling=T.nextSibling}get childNodes(){let T=[],M=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;M&&M!=this.nextSibling;)T.push(M),M=M.nextSibling;return T}querySelectorAll(T){return this.childNodes.reduce((M,h)=>{if(h instanceof Element){h.matches(T)&&M.push(h);let w=h.querySelectorAll(T);for(let y=0;y<w.length;y++)M.push(w[y])}return M},[])}insertBefore(T,M){return this.realParentNode.insertBefore(T,M)}moveBefore(T,M){return this.realParentNode.moveBefore(T,M)}get __idiomorphRoot(){return this.originalNode}}function S(k){let T=new DOMParser,M=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(M.match(/<\/html>/)||M.match(/<\/head>/)||M.match(/<\/body>/)){let h=T.parseFromString(k,"text/html");if(M.match(/<\/html>/))return u.add(h),h;{let w=h.firstChild;return w&&u.add(w),w}}else{let w=T.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return u.add(w),w}}return{normalizeElement:f,normalizeParent:x}})();return{morph:r,defaults:e}})();var vl=(t,e,r={})=>{let{preserveTypingAnimation:n=!0}=r;tx.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Cl={index:-1,draft:""};function rx(t){let{direction:e,history:r,currentValue:n,atStart:o,state:s}=t,a=s.index!==-1;if(r.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:n}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<r.length-1){let i=s.index+1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Cl}}}function nx(t,e){var r,n,o,s,a,i,d,l,p,m,u,f,x,C,S,k,T,M,h,w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve,Ee,Ke,Ne,X,Ue,K;return[t.id,t.role,(n=(r=t.content)==null?void 0:r.length)!=null?n:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=t.llmContent)==null?void 0:l.length)!=null?p:0,(u=(m=t.approval)==null?void 0:m.status)!=null?u:"",(x=(f=t.toolCall)==null?void 0:f.status)!=null?x:"",(S=(C=t.toolCall)==null?void 0:C.name)!=null?S:"",(M=(T=(k=t.toolCall)==null?void 0:k.chunks)==null?void 0:T.length)!=null?M:0,(E=(y=(w=(h=t.toolCall)==null?void 0:h.chunks)==null?void 0:w[t.toolCall.chunks.length-1])==null?void 0:y.slice(-32))!=null?E:"",typeof((B=t.toolCall)==null?void 0:B.args)=="string"?t.toolCall.args.length:(P=t.toolCall)!=null&&P.args?JSON.stringify(t.toolCall.args).length:0,(V=(O=(R=t.reasoning)==null?void 0:R.chunks)==null?void 0:O.length)!=null?V:0,(Ge=(Ye=(be=(ne=t.reasoning)==null?void 0:ne.chunks)==null?void 0:be[t.reasoning.chunks.length-1])==null?void 0:Ye.length)!=null?Ge:0,(Ne=(Ke=(Ee=(ve=t.reasoning)==null?void 0:ve.chunks)==null?void 0:Ee[t.reasoning.chunks.length-1])==null?void 0:Ke.slice(-32))!=null?Ne:"",(Ue=(X=t.contentParts)==null?void 0:X.length)!=null?Ue:0,(K=t.stopReason)!=null?K:"",e].join("\0")}function ox(){return new Map}function ax(t,e,r){let n=t.get(e);return n&&n.fingerprint===r?n.wrapper:null}function sx(t,e,r,n){t.set(e,{fingerprint:r,wrapper:n})}function ix(t,e){for(let r of t.keys())e.has(r)||t.delete(r)}function Al(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ns(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function _s(t,e){return Ns(t)-t.scrollTop<=e}function Sl(t){let{following:e,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=t,p=r-n;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:r}:!e&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Tl(t){let{following:e,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=t;return e&&r<0?"pause":!e&&o&&r>0&&n?"resume":"none"}var Ur={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},qr=1e5,Wo=qr+1;var Fs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ew=["pre","code","a","script","style"],Ml=t=>{var e,r,n,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Fs.type,placeholder:(r=t==null?void 0:t.placeholder)!=null?r:Fs.placeholder,speed:(n=t==null?void 0:t.speed)!=null?n:Fs.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Fs.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Fs.buffer}},dx=[{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 t of dx)$s.set(t.name,t);var pa=t=>{$s.set(t.name,t)},Op=t=>{dx.some(e=>e.name===t)||$s.delete(t)},Np=()=>Array.from($s.keys()),Us=(t,e)=>{var r,n;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(r=e[t])!=null?r:null:(n=$s.get(t))!=null?n:null},kl=(t,e,r,n,o)=>{if(!o)return t;if(r!=null&&r.bufferContent)return r.bufferContent(t,n);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
65
|
+
`);return s<0?"":t.slice(0,s)}return t},Lw=(t,e,r,n)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=e,o},Pw=(t,e,r,n)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=e,o},Hp=/\s/,Iw=(t,e)=>{let r=t.parentNode;for(;r;){if(r.nodeType===1){let n=r;if(e.has(n.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Rw=(t,e,r)=>{var d;let n=t.ownerDocument,o=t.parentNode;if(!n||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=0;for(;i<s.length;)if(Hp.test(s[i])){let l=i;for(;l<s.length&&Hp.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&&!Hp.test(s[p]);)l.appendChild(Lw(n,s[p],e,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,t)},Ww=(t,e,r)=>{var d;let n=t.ownerDocument,o=t.parentNode;if(!n||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(n.createTextNode(l)):(a.appendChild(Pw(n,l,e,r.value)),r.value+=1));o.replaceChild(a,t)},qs=(t,e,r,n)=>{var m,u;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((m=n==null?void 0:n.skipTags)!=null?m:Ew).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Iw(d,s)||i.push(d),d=a.nextNode();let l={value:(u=n==null?void 0:n.startIndex)!=null?u:0},p=e==="char"?Rw:Ww;for(let f of i)p(f,r,l);return o.innerHTML},El=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},zs=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let r=t.createElement("div");return r.className="persona-stream-skeleton-line",e.appendChild(r),e},lx=new WeakMap,Bw=(t,e)=>{var s;if(!t.styles)return;let r=lx.get(e);if(r||(r=new Set,lx.set(e,r)),r.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;r.delete(t.name)}r.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Dp=new WeakMap,Hw=(t,e)=>{if(!t.onAttach)return;let r=Dp.get(e);if(r||(r=new Map,Dp.set(e,r)),r.has(t.name))return;let n=t.onAttach(e);r.set(t.name,n)},cx=t=>{let e=Dp.get(t);if(e){for(let r of e.values())typeof r=="function"&&r();e.clear()}},_p=(t,e)=>{Bw(t,e),Hw(t,e)};function Fp(t,e=qr){let r=t.style.position,n=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=r),t.style.zIndex=n,t.style.isolation=o}}var Vs=0,Bo=null;function $p(t=document){var r;if(Vs++,Vs===1){let n=t.body,s=((r=t.defaultView)!=null?r:window).scrollY||t.documentElement.scrollTop;Bo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{var n;if(!e&&(e=!0,Vs=Math.max(0,Vs-1),Vs===0&&Bo)){let o=t.body,s=(n=t.defaultView)!=null?n:window;o.style.overflow=Bo.originalOverflow,o.style.position=Bo.originalPosition,o.style.top=Bo.originalTop,o.style.width=Bo.originalWidth,s.scrollTo(0,Bo.scrollY),Bo=null}}}var Ll={side:"right",width:"420px",animate:!0,reveal:"resize"},Ar=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="docked"},Ho=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="composer-bar"},kn=t=>{var r,n,o,s,a;let e=(r=t==null?void 0:t.launcher)==null?void 0:r.dock;return{side:(n=e==null?void 0:e.side)!=null?n:Ll.side,width:(o=e==null?void 0:e.width)!=null?o:Ll.width,animate:(s=e==null?void 0:e.animate)!=null?s:Ll.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Ll.reveal}};var $n={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var js=(t,e)=>{let r=v("button");r.type="button",r.innerHTML=`
|
|
66
66
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
67
67
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
68
68
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -70,14 +70,14 @@ _Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;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",e);let n=s=>{var E,h,w,x,T,W,R,B,_,V,oe,be,Qe,je;let a=(E=s.launcher)!=null?E:{},i=Ar(s),d=r.querySelector("[data-role='launcher-title']");if(d){let ve=(h=a.title)!=null?h:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let ve=(w=a.subtitle)!=null?w:"Get answers fast";l.textContent=ve,l.setAttribute("title",ve)}let p=r.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=r.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ve=(x=a.agentIconSize)!=null?x:"40px";if(m.style.height=ve,m.style.width=ve,m.innerHTML="",a.agentIconName){let Ee=parseFloat(ve)||24,Ge=Ie(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);Ge?(m.appendChild(Ge),m.style.display=""):(m.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let ve=(R=a.agentIconSize)!=null?R:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ve=(B=a.callToActionIconSize)!=null?B:"32px";f.style.height=ve,f.style.width=ve,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ge=parseFloat(ve)||24,_e=Math.max(Ge-Ee,8),X=Ie(a.callToActionIconName,_e,"currentColor",2);X?f.appendChild(X):f.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else f.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let y=a.position&&$n[a.position]?$n[a.position]:$n["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="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?S:`${A} ${y}`,i||(r.style.zIndex=String((oe=a.zIndex)!=null?oe:qr));let M="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(be=a.border)!=null?be:M,r.style.boxShadow=(Qe=a.shadow)!=null?Qe:k,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(je=a.collapsedMaxWidth)!=null?je:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},o=()=>{r.removeEventListener("click",e),r.remove()};return t&&n(t),{element:r,update:n,destroy:o}};var Bw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ll=(t,e={})=>{var A,S,M,k,E,h;let{showClose:r=!0,wrapperClassName:n=Bw,buttonSize:o,iconSize:s="28px"}=e,a=(A=t==null?void 0:t.launcher)!=null?A:{},i=(S=o!=null?o:a.closeButtonSize)!=null?S:"32px",d=v("div",n),l=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(M=a.closeButtonTooltipText)!=null?M:"Close chat",m=(k=a.closeButtonShowTooltip)!=null?k:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let u=(E=a.closeButtonIconName)!=null?E:"x",f=(h=a.closeButtonIconText)!=null?h:"\xD7";l.style.color=a.closeButtonColor||en.actionIconColor;let y=Ie(u,s,"currentColor",1);if(y?(y.style.display="block",l.appendChild(y)):l.textContent=f,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let w=a.closeButtonBorderWidth||"0px",x=a.closeButtonBorderColor||"transparent";l.style.border=`${w} 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),m&&p){let w=null,x=()=>{if(w)return;let W=l.ownerDocument,R=W.body;if(!R)return;w=Qn(W,"div","persona-clear-chat-tooltip"),w.textContent=p;let B=Qn(W,"div");B.className="persona-clear-chat-tooltip-arrow",w.appendChild(B);let _=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(Ro),w.style.left=`${_.left+_.width/2}px`,w.style.top=`${_.top-8}px`,w.style.transform="translate(-50%, -100%)",R.appendChild(w)},T=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};d.addEventListener("mouseenter",x),d.addEventListener("mouseleave",T),l.addEventListener("focus",x),l.addEventListener("blur",T),d._cleanupTooltip=()=>{T(),d.removeEventListener("mouseenter",x),d.removeEventListener("mouseleave",T),l.removeEventListener("focus",x),l.removeEventListener("blur",T)}}return{button:l,wrapper:d}},Hw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pl=(t,e={})=>{var w,x,T,W,R,B,_,V,oe,be,Qe,je,ve;let{wrapperClassName:r=Hw,buttonSize:n,iconSize:o="20px"}=e,a=(x=((w=t==null?void 0:t.launcher)!=null?w:{}).clearChat)!=null?x:{},i=(T=n!=null?n:a.size)!=null?T:"32px",d=(W=a.iconName)!=null?W:"refresh-cw",l=(R=a.iconColor)!=null?R:"",p=(B=a.backgroundColor)!=null?B:"",m=(_=a.borderWidth)!=null?_:"",u=(V=a.borderColor)!=null?V:"",f=(oe=a.borderRadius)!=null?oe:"",y=(be=a.paddingX)!=null?be:"",A=(Qe=a.paddingY)!=null?Qe:"",S=(je=a.tooltipText)!=null?je:"Clear chat",M=(ve=a.showTooltip)!=null?ve:!0,k=v("div",r),E=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");E.style.height=i,E.style.width=i,E.type="button",E.setAttribute("aria-label",S),E.style.color=l||en.actionIconColor;let h=Ie(d,o,"currentColor",1);if(h&&(h.style.display="block",E.appendChild(h)),p&&(E.style.backgroundColor=p,E.classList.remove("hover:persona-bg-gray-100")),m||u){let Ee=m||"0px",Ge=u||"transparent";E.style.border=`${Ee} solid ${Ge}`,E.classList.remove("persona-border-none")}if(f&&(E.style.borderRadius=f,E.classList.remove("persona-rounded-full")),y&&(E.style.paddingLeft=y,E.style.paddingRight=y),A&&(E.style.paddingTop=A,E.style.paddingBottom=A),k.appendChild(E),M&&S){let Ee=null,Ge=()=>{if(Ee)return;let X=E.ownerDocument,Ue=X.body;if(!Ue)return;Ee=Qn(X,"div","persona-clear-chat-tooltip"),Ee.textContent=S;let K=Qn(X,"div");K.className="persona-clear-chat-tooltip-arrow",Ee.appendChild(K);let Te=E.getBoundingClientRect();Ee.style.position="fixed",Ee.style.zIndex=String(Ro),Ee.style.left=`${Te.left+Te.width/2}px`,Ee.style.top=`${Te.top-8}px`,Ee.style.transform="translate(-50%, -100%)",Ue.appendChild(Ee)},_e=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};k.addEventListener("mouseenter",Ge),k.addEventListener("mouseleave",_e),E.addEventListener("focus",Ge),E.addEventListener("blur",_e),k._cleanupTooltip=()=>{_e(),k.removeEventListener("mouseenter",Ge),k.removeEventListener("mouseleave",_e),E.removeEventListener("focus",Ge),E.removeEventListener("blur",_e)}}return{button:E,wrapper:k}};var en={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},go=t=>{var w,x,T,W,R,B,_,V,oe,be,Qe,je,ve,Ee,Ge,_e;let{config:e,showClose:r=!0}=t,n=v("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(w=e==null?void 0:e.launcher)!=null?w:{},s=(x=o.headerIconSize)!=null?x:"48px",a=(T=o.closeButtonPlacement)!=null?T:"inline",i=(W=o.headerIconHidden)!=null?W:!1,d=o.headerIconName,l=v("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let X=parseFloat(s)||24,Ue=Ie(d,X*.6,"currentColor",1);Ue?l.replaceChildren(Ue):l.textContent=(B=(R=e==null?void 0:e.launcher)==null?void 0:R.agentIconText)!=null?B:"\u{1F4AC}"}else if((_=e==null?void 0:e.launcher)!=null&&_.iconUrl){let X=v("img");X.src=e.launcher.iconUrl,X.alt="",X.className="persona-rounded-xl persona-object-cover",X.style.height=s,X.style.width=s,l.replaceChildren(X)}else l.textContent=(oe=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=v("span","persona-text-base persona-font-semibold");m.style.color=en.titleColor,m.textContent=(Qe=(be=e==null?void 0:e.launcher)==null?void 0:be.title)!=null?Qe:"Chat Assistant";let u=v("span","persona-text-xs");u.style.color=en.subtitleColor,u.textContent=(ve=(je=e==null?void 0:e.launcher)==null?void 0:je.subtitle)!=null?ve:"Here to help you get answers fast",p.append(m,u),i?n.append(p):n.append(l,p);let f=(Ee=o.clearChat)!=null?Ee:{},y=(Ge=f.enabled)!=null?Ge:!0,A=(_e=f.placement)!=null?_e:"inline",S=null,M=null;if(y){let Ue=Pl(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=Ue.button,M=Ue.wrapper,A==="top-right"&&(M.style.right="48px"),A==="inline"&&n.appendChild(M)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:h}=Ll(e,{showClose:r,wrapperClassName:k});return a!=="top-right"&&n.appendChild(h),{header:n,iconHolder:l,headerTitle:m,headerSubtitle:u,closeButton:E,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:M}},pa=(t,e,r)=>{var a,i,d,l;let n=(a=r==null?void 0:r.launcher)!=null?a:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",s=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function Ho(t){let{items:e,onSelect:r,anchor:n,position:o="bottom-left",portal:s}=t,a=v("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ro)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}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 S=Ie(f.icon,16,"currentColor",1.5);S&&y.appendChild(S)}let A=document.createElement("span");A.textContent=f.label,y.appendChild(A),y.addEventListener("click",S=>{S.stopPropagation(),p(),r(f.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let f=n.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=y=>{!a.contains(y.target)&&!n.contains(y.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function u(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:u}}function Er(t){let{icon:e,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",r),d.title=r;let l=Ie(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function js(t){let{icon:e,label:r,variant:n="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=v("button",l);if(p.type="button",p.setAttribute("aria-label",r),e){let u=Ie(e,s!=null?s:14,"currentColor",2);u&&p.appendChild(u)}let m=v("span");if(m.textContent=r,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[u,f]of Object.entries(d))p.setAttribute(u,f);return p}function dx(t){let{items:e,selectedId:r,onSelect:n,className:o}=t,s=v("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=r,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of e){let m;p.icon?m=Er({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(m=v("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),s.appendChild(m)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Il(t){var f,y;let{label:e,icon:r="chevron-down",menuItems:n,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,l=v("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",e);let p=v("span","persona-combo-btn-label");p.textContent=e,l.appendChild(p);let m=Ie(r,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var A,S;l.style.backgroundColor=(A=d.background)!=null?A:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Ho({items:n,onSelect:A=>{l.setAttribute("aria-expanded","false"),o(A)},anchor:l,position:s,portal:a});return a||l.appendChild(u.element),l.addEventListener("click",A=>{A.stopPropagation();let S=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),u.toggle()}),l.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),l.click())}),{element:l,setLabel:A=>{p.textContent=A,l.setAttribute("aria-label",A)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let A=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",A?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var $p=t=>{var n;let e=go({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),r=(n=t.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(r){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>r()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())}))}return e};function Dw(t,e,r){var n,o,s;if(e!=null&&e.length)for(let a of e){let i=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=a.ariaLabel)!=null?n:a.label)!=null?o:a.id),a.icon){let d=Ie(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(i);let l=Ho({items:a.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>r==null?void 0:r(a.id)),t.appendChild(i)}}var Up=t=>{var k,E,h,w,x,T,W,R,B;let{config:e,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(k=e==null?void 0:e.launcher)!=null?k:{},i=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Il({label:(E=a.title)!=null?E:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=en.titleColor,p=(h=l.querySelector(".persona-combo-btn-label"))!=null?h:l;else{if(l=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=en.titleColor,p.textContent=(w=a.title)!=null?w:"Chat Assistant",l.appendChild(p),Dw(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 V=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let _=o==null?void 0:o.titleRowHover;_&&(l.style.borderRadius=(T=_.borderRadius)!=null?T:"10px",l.style.padding=(W=_.padding)!=null?W:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,oe;l.style.backgroundColor=(V=_.background)!=null?V:"",l.style.borderColor=(oe=_.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(R=a.closeButtonSize)!=null?R:"32px",u=v("div",""),f=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=a.closeButtonColor||en.actionIconColor;let y=(B=a.closeButtonIconName)!=null?B:"x",A=Ie(y,"28px","currentColor",1);A?f.appendChild(A):f.textContent="\xD7",n&&f.addEventListener("click",n),u.appendChild(f),i.appendChild(u);let S=v("div");S.style.display="none";let M=v("span");return M.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:M,closeButton:f,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Rl={default:$p,minimal:Up},qp=t=>{var e;return(e=Rl[t])!=null?e:Rl.default},Oa=(t,e,r)=>{var a,i,d;if(e!=null&&e.render){let l=e.render({config:t,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=v("div");p.style.display="none";let m=v("span"),u=v("span"),f=v("button");f.style.display="none";let y=v("div");return y.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:u,closeButton:f,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=e==null?void 0:e.layout)!=null?a:"default",s=qp(n)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Wl=t=>{var a,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,n=20;e.style.maxHeight=`${r*n}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:r*n},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Bl=t=>{var w,x,T,W,R,B,_,V,oe,be,Qe,je;let e=(w=t==null?void 0:t.sendButton)!=null?w:{},r=(x=e.useIcon)!=null?x:!1,n=(T=e.iconText)!=null?T:"\u2191",o=e.iconName,s=(W=e.stopIconName)!=null?W:"square",a=(R=e.tooltipText)!=null?R:"Send message",i=(B=e.stopTooltipText)!=null?B:"Stop generating",d=(V=(_=t==null?void 0:t.copy)==null?void 0:_.sendButtonLabel)!=null?V:"Send",l=(be=(oe=t==null?void 0:t.copy)==null?void 0:oe.stopButtonLabel)!=null?be:"Stop",p=(Qe=e.showTooltip)!=null?Qe:!1,m=(je=e.size)!=null?je:"40px",u=e.backgroundColor,f=e.textColor,y=v("div","persona-send-button-wrapper"),A=v("button",r?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");A.type="submit",A.setAttribute("data-persona-composer-submit","");let S=null,M=null;if(r){A.style.width=m,A.style.height=m,A.style.minWidth=m,A.style.minHeight=m,A.style.fontSize="18px",A.style.lineHeight="1",A.innerHTML="",f?A.style.color=f:A.style.color="var(--persona-button-primary-fg, #ffffff)";let ve=parseFloat(m)||24,Ee=(f==null?void 0:f.trim())||"currentColor";o?(S=Ie(o,ve,Ee,2),S?A.appendChild(S):A.textContent=n):A.textContent=n,M=Ie(s,ve,Ee,2),u?A.style.backgroundColor=u:A.classList.add("persona-bg-persona-primary")}else A.textContent=d,f?A.style.color=f:A.classList.add("persona-text-white");e.borderWidth&&(A.style.borderWidth=e.borderWidth,A.style.borderStyle="solid"),e.borderColor&&(A.style.borderColor=e.borderColor),e.paddingX?(A.style.paddingLeft=e.paddingX,A.style.paddingRight=e.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),e.paddingY?(A.style.paddingTop=e.paddingY,A.style.paddingBottom=e.paddingY):(A.style.paddingTop="",A.style.paddingBottom="");let k=null;p&&a&&(k=v("div","persona-send-button-tooltip"),k.textContent=a,y.appendChild(k)),A.setAttribute("aria-label",a),y.appendChild(A);let E="send";return{button:A,wrapper:y,setMode:ve=>{if(ve===E)return;E=ve;let Ee=ve==="stop"?i:a;if(A.setAttribute("aria-label",Ee),k&&(k.textContent=Ee),r){if(S&&M){let Ge=ve==="stop"?M:S;A.replaceChildren(Ge)}}else A.textContent=ve==="stop"?l:d}}},Hl=t=>{var k,E,h,w,x,T,W,R,B,_,V,oe;let e=(k=t==null?void 0:t.voiceRecognition)!=null?k:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((E=e.provider)==null?void 0:E.type)==="runtype";if(!(n||o))return null;let a=(w=(h=t==null?void 0:t.sendButton)==null?void 0:h.size)!=null?w:"40px",i=v("div","persona-send-button-wrapper"),d=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(x=e.iconName)!=null?x:"mic",p=(T=e.iconSize)!=null?T:a,m=parseFloat(p)||24,u=(R=e.backgroundColor)!=null?R:(W=t==null?void 0:t.sendButton)==null?void 0:W.backgroundColor,f=(_=e.iconColor)!=null?_:(B=t==null?void 0:t.sendButton)==null?void 0:B.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",f?d.style.color=f:d.style.color="var(--persona-text, #111827)";let A=Ie(l,m,f||"currentColor",1.5);A?d.appendChild(A):d.textContent="\u{1F3A4}",u&&(d.style.backgroundColor=u),e.borderWidth&&(d.style.borderWidth=e.borderWidth,d.style.borderStyle="solid"),e.borderColor&&(d.style.borderColor=e.borderColor),e.paddingX&&(d.style.paddingLeft=e.paddingX,d.style.paddingRight=e.paddingX),e.paddingY&&(d.style.paddingTop=e.paddingY,d.style.paddingBottom=e.paddingY),i.appendChild(d);let S=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((oe=e.showTooltip)!=null?oe:!1)&&S){let be=v("div","persona-send-button-tooltip");be.textContent=S,i.appendChild(be)}return{button:d,wrapper:i}},Dl=t=>{var y,A,S,M,k,E,h,w;let e=(y=t==null?void 0:t.attachments)!=null?y:{};if(e.enabled!==!0)return null;let r=(S=(A=t==null?void 0:t.sendButton)==null?void 0:A.size)!=null?S:"40px",n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=v("input");o.type="file",o.accept=((M=e.allowedTypes)!=null?M:mo).join(","),o.multiple=((k=e.maxFiles)!=null?k:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=v("div","persona-send-button-wrapper"),a=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(E=e.buttonTooltipText)!=null?E:"Attach file");let i=(h=e.buttonIconName)!=null?h:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Ie(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",x=>{x.preventDefault(),o.click()}),s.appendChild(a);let u=(w=e.buttonTooltipText)!=null?w:"Attach file",f=v("div","persona-send-button-tooltip");return f.textContent=u,s.appendChild(f),{button:a,wrapper:s,input:o,previewsContainer:n}},Ol=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},r=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",n=v("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;n.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=v("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=s;return n},_l=()=>v("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var _a=t=>{var y,A,S,M,k,E;let{config:e}=t,r=v("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");r.setAttribute("data-persona-theme-zone","composer");let n=_l(),o=v("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Wl(e);a();let i=Bl(e),d=Hl(e),l=Dl(e),p=Ol(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let m=v("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),u=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(u,f),o.append(m),o.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==(d==null?void 0:d.button)&&h.target!==(d==null?void 0:d.wrapper)&&h.target!==(l==null?void 0:l.button)&&h.target!==(l==null?void 0:l.wrapper)&&s.focus()}),r.append(n,o,p),{footer:r,suggestions:n,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(A=d==null?void 0:d.wrapper)!=null?A:null,statusText:p,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(M=l==null?void 0:l.wrapper)!=null?M:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var cx=()=>{let t=v("button","persona-pill-peek");t.type="button",t.setAttribute("data-persona-pill-peek",""),t.setAttribute("aria-label","Show conversation"),t.setAttribute("tabindex","-1");let e=v("span","persona-pill-peek__icon"),r=Ie("message-square",16,"currentColor",1.5);r&&e.appendChild(r);let n=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=Ie("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,n,o),{root:t,textNode:n}},px=t=>{var y,A,S,M,k,E;let{config:e}=t,r=v("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=_l();n.style.display="none";let o=Ol(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Wl(e);s.style.maxHeight="100px",a();let i=Bl(e),d=Hl(e),l=Dl(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=v("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=v("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let u=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),p.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==(d==null?void 0:d.button)&&h.target!==(d==null?void 0:d.wrapper)&&h.target!==(l==null?void 0:l.button)&&h.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,u),l&&r.append(l.previewsContainer),r.append(p,n,o);let f=p;return{footer:r,suggestions:n,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(A=d==null?void 0:d.wrapper)!=null?A:null,statusText:o,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(M=l==null?void 0:l.wrapper)!=null?M:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:f,leftActions:m,rightActions:u,setSendButtonMode:i.setMode}};var ux=t=>{var p,m,u,f,y,A,S,M,k,E,h,w,x,T,W,R,B;let e=(m=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)!=null?m:!0,r=Ar(t);if(Bo(t)){let _=(f=(u=t==null?void 0:t.launcher)==null?void 0:u.composerBar)!=null?f:{},V=v("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(y=_.expandedSize)!=null?y:"anchored",V.style.zIndex=String((S=(A=t==null?void 0:t.launcher)==null?void 0:A.zIndex)!=null?S:qr);let oe=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let be=v("div","persona-widget-pill-root");return be.setAttribute("data-persona-composer-bar",""),be.dataset.state="collapsed",be.dataset.expandedSize=(M=_.expandedSize)!=null?M:"anchored",be.style.zIndex=String((E=(k=t==null?void 0:t.launcher)==null?void 0:k.zIndex)!=null?E:qr),{wrapper:V,panel:oe,pillRoot:be}}if(r){let _=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(V),{wrapper:_,panel:V}}if(!e){let _=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(w=(h=t==null?void 0:t.launcher)==null?void 0:h.width)!=null?w:"100%";return _.style.width=oe,V.style.width="100%",_.appendChild(V),{wrapper:_,panel:V}}let o=(x=t==null?void 0:t.launcher)!=null?x:{},s=o.position&&$n[o.position]?$n[o.position]:$n["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((W=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?W:qr);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(B=(R=t==null?void 0:t.launcher)==null?void 0:R.width)!=null?B:t==null?void 0:t.launcherWidth,l=d!=null?d:yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ow=(t,e)=>{var h,w,x,T,W,R,B,_,V;let r=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Ll(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(x=(w=(h=t==null?void 0:t.launcher)==null?void 0:h.clearChat)==null?void 0:w.enabled)!=null?x:!0,a=null,i=null;if(s){let oe=Pl(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=v("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(W=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?W:"Hello \u{1F44B}";let u=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(B=(R=t==null?void 0:t.copy)==null?void 0:R.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",p.append(m,u);let f=v("div","persona-flex persona-flex-col persona-gap-3"),y=(_=t==null?void 0:t.layout)==null?void 0:_.contentMaxWidth;y&&(f.style.maxWidth=y,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((V=t==null?void 0:t.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,f);let S=v("div","persona-composer-overlay persona-pointer-events-none");S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20";let M=px({config:t}),{root:k,textNode:E}=cx();return r.append(d,o,l,S),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:f,composerOverlay:S,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,introTitle:m,introSubtitle:u,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:k,peekTextNode:E}},fx=(t,e=!0)=>{var S,M,k,E,h,w,x,T,W;if(Bo(t))return Ow(t,e);let r=v("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");r.setAttribute("data-persona-theme-zone","container");let n=(S=t==null?void 0:t.layout)==null?void 0:S.header,o=((M=t==null?void 0:t.layout)==null?void 0:M.showHeader)!==!1,s=n?Oa(t,n,{showClose:e}):go({config:t,showClose:e}),a=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Ar(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(E=(k=t==null?void 0:t.copy)==null?void 0:k.welcomeTitle)!=null?E:"Hello \u{1F44B}";let l=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(h=t==null?void 0:t.copy)==null?void 0:h.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let p=v("div","persona-flex persona-flex-col persona-gap-3"),m=(x=t==null?void 0:t.layout)==null?void 0:x.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((T=t==null?void 0:t.copy)==null?void 0:T.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let f=_a({config:t}),y=((W=t==null?void 0:t.layout)==null?void 0:W.showFooter)!==!1;o?pa(r,s,t):(s.header.style.display="none",pa(r,s,t)),r.append(a);let A=v("div","persona-composer-overlay persona-pointer-events-none");return A.setAttribute("data-persona-composer-overlay",""),A.style.position="absolute",A.style.left="0",A.style.right="0",A.style.bottom="0",A.style.zIndex="20",y||(f.footer.style.display="none"),r.append(f.footer),r.append(A),{container:r,body:a,messagesWrapper:p,composerOverlay:A,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var _w=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Nw=(t,e)=>{if(!t)return null;let r=_w(t);if(r===null)return null;let n=e==null?void 0:e[t],o=n!==void 0?n:r;return o||null},Fw=(t,e)=>{let r=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",t),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=e,r},$w=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},zp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Vp=320,gx=320,Uw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),qw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),zw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Vw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),jw=(t,e,r)=>{if(t.length===0)return null;try{let n=v("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),e&&(n.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,n.remove(),r==null||r())};return t.forEach((i,d)=>{var m;let l=v("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Vp}px`,l.style.maxHeight=`${gx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),$w(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}},Gw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let r=0;return t.forEach(n=>{if(!zp(n.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vp}px`,e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Kw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let r=0;return t.forEach(n=>{if(!zp(n.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vp}px`,o.style.maxHeight=`${gx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Xw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let r=0;return t.forEach(n=>{if(!zp(n.data))return;let o=v("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},ua=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(r),t.appendChild(n),t.appendChild(o),t},jp=(t,e,r)=>{let n={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:ua};if(e){let o=e(n);if(o!==null)return o}return ua()},Jw=(t,e)=>{let r=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=e==="user"?t.userAvatar:t.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=v("img");o.src=n,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(o)}else r.textContent=n,r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},mx=(t,e)=>{let r=v("div","persona-text-xs persona-text-persona-muted"),n=new Date(t.createdAt);return e.format?r.textContent=e.format(n):r.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Qw=(t,e="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},Gp=(t,e,r)=>{var f,y,A,S,M,k;let n=(f=e.showCopy)!=null?f:!0,o=(y=e.showUpvote)!=null?y:!0,s=(A=e.showDownvote)!=null?A:!0;if(!n&&!o&&!s){let E=v("div");return E.style.display="none",E.id=`actions-${t.id}`,E.setAttribute("data-actions-for",t.id),E}let a=(S=e.visibility)!=null?S:"hover",i=(M=e.align)!=null?M:"right",d=(k=e.layout)!=null?k:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id);let u=(E,h,w)=>{let x=Er({icon:E,label:h,size:14,className:"persona-message-action-btn"});return x.setAttribute("data-action",w),x};return n&&m.appendChild(u("copy","Copy message","copy")),o&&m.appendChild(u("thumbs-up","Upvote","upvote")),s&&m.appendChild(u("thumbs-down","Downvote","downvote")),m},Na=(t,e,r,n,o,s)=>{var X,Ue,K,Te,ae,xe,ke,Ke,ce,re,le,ut,Ce,he,tt,Ne,me;let a=r!=null?r:{},i=(X=a.layout)!=null?X:"bubble",d=a.avatar,l=a.timestamp,p=(Ue=d==null?void 0:d.show)!=null?Ue:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,u=(Te=d==null?void 0:d.position)!=null?Te:"left",f=(ae=l==null?void 0:l.position)!=null?ae:"below",y=Qw(t.role,i),A=v("div",y.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Uw(t),M=(ke=(xe=t.content)==null?void 0:xe.trim())!=null?ke:"",E=S.length>0&&M===Zi,h=Tl((ce=(Ke=s==null?void 0:s.widgetConfig)==null?void 0:Ke.features)==null?void 0:ce.streamAnimation),w=(ut=(le=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:le.streamAnimation)==null?void 0:ut.plugins,x=t.role==="assistant"&&h.type!=="none"?$s(h.type,w):null,T=t.role==="assistant"&&((Ce=x==null?void 0:x.isAnimating)==null?void 0:Ce.call(x,t))===!0,W=t.role==="assistant"&&x!==null&&(!!t.streaming||T);W&&(x!=null&&x.bubbleClass)&&A.classList.add(x.bubbleClass);let R=document.createElement("div");R.classList.add("persona-message-content"),W&&x&&(x.containerClass&&R.classList.add(x.containerClass),R.style.setProperty("--persona-stream-step",`${h.speed}ms`),R.style.setProperty("--persona-stream-duration",`${h.duration}ms`));let B=W?kl((he=t.content)!=null?he:"",h.buffer,x,t,!!t.streaming):(tt=t.content)!=null?tt:"",_=e({text:B,message:t,streaming:!!t.streaming,raw:t.rawContent}),V=_;W&&(x==null?void 0:x.wrap)==="char"?V=Us(_,"char",t.id,{skipTags:x.skipTags}):W&&(x==null?void 0:x.wrap)==="word"&&(V=Us(_,"word",t.id,{skipTags:x.skipTags}));let oe=null;if(E?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",R.appendChild(oe)):R.innerHTML=V,W&&(x!=null&&x.useCaret)&&!E&&M){let J=Ml(),ze=R.querySelectorAll(".persona-stream-char, .persona-stream-word"),Z=ze[ze.length-1];if(Z!=null&&Z.parentNode)Z.parentNode.insertBefore(J,Z.nextSibling);else{let ge=R.lastElementChild;ge?ge.appendChild(J):R.appendChild(J)}}if(m&&f==="inline"&&t.createdAt){let J=mx(t,l);J.classList.add("persona-ml-2","persona-inline"),R.appendChild(J)}if(S.length>0){let J=jw(S,!E&&!!M,()=>{E&&oe&&(oe.style.display="")});J?A.appendChild(J):E&&oe&&(oe.style.display="")}let be=qw(t);if(be.length>0){let J=Gw(be);J&&A.appendChild(J)}let Qe=zw(t);if(Qe.length>0){let J=Kw(Qe);J&&A.appendChild(J)}let je=Vw(t);if(je.length>0){let J=Xw(je);J&&A.appendChild(J)}if(A.appendChild(R),m&&f==="below"&&t.createdAt){let J=mx(t,l);J.classList.add("persona-mt-1"),A.appendChild(J)}let ve=t.role==="assistant"?Nw(t.stopReason,(me=(Ne=s==null?void 0:s.widgetConfig)==null?void 0:Ne.copy)==null?void 0:me.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let J=!!(B&&B.trim()),ze=h.placeholder==="skeleton",Z=ze&&h.buffer==="line"&&J;if(J)Z&&A.appendChild(qs());else if(ze)A.appendChild(qs());else{let ge=jp("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ge&&A.appendChild(ge)}}if(ve&&t.stopReason&&!t.streaming&&(M||(R.style.display="none"),A.appendChild(Fw(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let J=Gp(t,n,o);A.appendChild(J)}if(!p||t.role==="system")return A;let Ge=v("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),_e=Jw(d,t.role);return u==="right"||u==="left"&&t.role==="user"?Ge.append(A,_e):Ge.append(_e,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ge},hx=(t,e,r,n,o,s)=>{let a=r!=null?r:{};return t.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:t,config:{},streaming:!!t.streaming}):t.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:t,config:{},streaming:!!t.streaming}):Na(t,e,r,n,o,s)};var Fa=new Set,Yw=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Zw=(t,e)=>{var n,o;let r=(o=(n=t.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
74
|
-
`):""},
|
|
75
|
-
`);let o=
|
|
76
|
-
`):""},rv=(t,e)=>{var p,m,u,f,y;let r=t.toolCall,n=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(m=n==null?void 0:n.collapsedMode)!=null?m:"tool-call",s=tv(t,(u=n==null?void 0:n.previewMaxLines)!=null?u:3),a=r?Rh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((y=r.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Rd(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Rd(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},yx=(t,e,r)=>{var p;let n=$a.has(t),o=(p=r==null?void 0:r.toolCall)!=null?p:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",n?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=o.toggleTextColor||o.headerTextColor||"currentColor",u=Ie(n?"chevron-up":"chevron-down",16,m,2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Xp=(t,e)=>{var V,oe,be,Qe,je,ve,Ee,Ge,_e;let r=t.toolCall,n=(V=e==null?void 0:e.toolCall)!=null?V:{},o=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!r)return o;let s=(be=(oe=e==null?void 0:e.features)==null?void 0:oe.toolCallDisplay)!=null?be:{},a=s.expandable!==!1,i=a&&$a.has(t.id),{summary:d,previewText:l,isActive:p}=rv(t,e),m=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let u=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let y=String((Qe=r.startedAt)!=null?Qe:Date.now()),A=()=>{let X=v("span","");return X.setAttribute("data-tool-elapsed",y),X.textContent=Is(r),X},S=(ve=n.renderCollapsedSummary)==null?void 0:ve.call(n,{message:t,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(je=s.collapsedMode)!=null?je:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Is(r),createElapsedElement:A});typeof S=="string"&&S.trim()?(f.textContent=S,u.appendChild(f)):S instanceof HTMLElement?u.appendChild(S):(f.textContent=d,u.appendChild(f));let M=(Ee=s.loadingAnimation)!=null?Ee:"none",k=n.activeTextTemplate,E=n.completeTextTemplate,h=p?k:E,w=S instanceof HTMLElement,x=(X,Ue,K)=>{let Te=K;for(let ae of Ue){let xe=v("span","persona-tool-char");xe.style.setProperty("--char-index",String(Te)),xe.textContent=ae===" "?"\xA0":ae,X.appendChild(xe),Te++}return Te},T=(X,Ue)=>{var xe;f.textContent="";let K=((xe=r.name)==null?void 0:xe.trim())||"tool",Te=ji(X,K),ae=0;for(let ke of Te){let Ke=ke.styles.length>0?(()=>{let ce=v("span",ke.styles.map(re=>`persona-tool-text-${re}`).join(" "));return f.appendChild(ce),ce})():f;if(ke.isDuration&&p)Ke.appendChild(A());else{let ce=ke.isDuration?Is(r):ke.text;Ue?ae=x(Ke,ce,ae):Ke.appendChild(document.createTextNode(ce))}}};if(!w)if(p&&M!=="none"){let X=(Ge=n.loadingAnimationDuration)!=null?Ge:2e3;if(f.setAttribute("data-preserve-animation","true"),M==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),h&&T(h,!1);else if(f.classList.add(`persona-tool-loading-${M}`),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),M==="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)),h)T(h,!0);else{let Ue=f.textContent||d;f.textContent="",x(f,Ue,0)}}else h&&T(h,!1);let W=null;if(a){W=v("div","persona-flex persona-items-center");let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?W.appendChild(Ue):W.textContent=i?"Hide":"Show";let K=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(W),m.append(u,K)}else m.append(u);let R=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","tool"),R.style.display="none",R.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let X=(_e=n.renderCollapsedPreview)==null?void 0:_e.call(n,{message:t,toolCall:r,defaultPreview:l,isActive:p,config:e!=null?e:{}});ev(R,X)||(R.textContent=l),R.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(m,R),o;let B=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=i?"":"none",n.contentBackgroundColor&&(B.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(B.style.color=n.contentTextColor),n.contentPaddingX&&(B.style.paddingLeft=n.contentPaddingX,B.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(B.style.paddingTop=n.contentPaddingY,B.style.paddingBottom=n.contentPaddingY),r.name){let X=v("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?X.style.color=n.contentTextColor:n.headerTextColor&&(X.style.color=n.headerTextColor),X.textContent=r.name,B.appendChild(X)}if(r.args!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Arguments";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ia(r.args),X.append(Ue,K),B.appendChild(X)}if(r.chunks&&r.chunks.length){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Activity";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=r.chunks.join(""),X.append(Ue,K),B.appendChild(X)}if(r.status==="complete"&&r.result!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Result";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ia(r.result),X.append(Ue,K),B.appendChild(X)}if(r.status==="complete"&&typeof r.duration=="number"){let X=v("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(X.style.color=n.contentTextColor),X.textContent=`Duration: ${r.duration}ms`,B.appendChild(X)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?W.appendChild(Ue):W.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",R.style.display=i?"none":R.textContent||R.childNodes.length?"":"none"})(),o.append(m,R,B),o};var Do=od(Ui(),1);var Qp="ask_user_question",Jp=8,Ua="data-persona-ask-sheet-for",nv="Other",ov="Other\u2026",wx="Type your own answer here",vx="Send",av="Next",sv="Back",iv="Submit all",lv="Skip",dv=3,Yp="data-ask-current-index",Zp="data-ask-question-count",Cx="data-ask-answers",eu="data-ask-grouped",Ax="data-ask-layout",cv=t=>t.layout==="pills"?"pills":"rows",pv=t=>t.getAttribute(Ax)==="pills"?"pills":"rows",bx=!1,Sx=t=>t.replace(/["\\]/g,"\\$&"),ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Qp,Nl=t=>{var e,r;return(r=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?r:{}},xo=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let r=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:r};let n=e.chunks;if(!n||n.length===0)return{payload:null,complete:r};try{let o=n.join(""),s=(0,Do.parse)(o,Do.STR|Do.OBJ|Do.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},Gs=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Jp&&!bx&&(bx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Jp}.`)),e.slice(0,Jp)},uv=t=>{var e;return(e=Gs(t)[0])!=null?e:null},fv=(t,e)=>{var r;return(r=Gs(t)[e])!=null?r:null},Tx=(t,e)=>{let r=e.styles;r&&(r.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},kx=(t,e,r)=>{if(t!=="rows")return null;let n=v("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");n.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},mv=(t,e,r,n)=>{let s=v("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",n?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),r==="rows"){let a=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let l=v("span","persona-ask-row-description");l.textContent=t.description,a.appendChild(l)}s.appendChild(a);let d=kx(r,n,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},gv=t=>{let r=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},hv=(t,e,r,n)=>{var p,m,u;let s=v("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!r){for(let f=0;f<dv;f++)s.appendChild(gv(n));return s}if(d.forEach((f,y)=>{s.appendChild(mv(f,y,n,a))}),(t==null?void 0:t.allowFreeText)!==!1){let f=n==="rows"?nv:ov;if(n==="rows"){let y=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let A=v("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=e.freeTextPlaceholder)!=null?p:wx,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),A.appendChild(S),y.appendChild(A);let M=kx(n,a,d.length);M&&y.appendChild(M),s.appendChild(y)}else{let y=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(u=e.freeTextLabel)!=null?u:f,s.appendChild(y)}}return s},Mx=(t,e)=>{var s,a;let n=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:wx,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),e!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:vx,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},xv=t=>{var n;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let r=v("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=t.submitLabel)!=null?n:vx,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,e.appendChild(r),e},yv=(t,e,r)=>{var l,p,m,u;let n=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:sv,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,n.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:lv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(m=r.submitAllLabel)!=null?m:iv:(u=r.nextLabel)!=null?u:av,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},fa=t=>{let e=t.getAttribute(Cx);if(!e)return{};try{let r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}},Ex=(t,e)=>{t.setAttribute(Cx,JSON.stringify(e))},En=t=>{var r;let e=Number((r=t.getAttribute(Yp))!=null?r:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},bv=(t,e)=>{t.setAttribute(Yp,String(Math.max(0,Math.floor(e))))},qa=t=>{var r;let e=Number((r=t.getAttribute(Zp))!=null?r:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Oo=t=>t.getAttribute(eu)==="true",wv=(t,e)=>{var o;let r=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let n={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let d=r[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},vv=(t,e)=>{var n;let r=(n=t.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(e-1,Math.floor(r)))},Fl=(t,e)=>{let{payload:r}=xo(e),n=Gs(r),o=fa(t),s={},a=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Lx=t=>{let e=fa(t),r=En(t),n=e[r],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!a.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Px=t=>{if(!Oo(t))return;let e=fa(t),r=En(t),n=e[r],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},tu=(t,e,r)=>{let n=Nl(r),o=pv(t),{payload:s,complete:a}=xo(e),i=Oo(t),d=En(t),l=qa(t),p=i?fv(s,d):uv(s),m=!!(p!=null&&p.multiSelect),u=t.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${l}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let y=t.querySelector('[data-ask-question="true"]');if(y){let k=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=k,y.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let A=t.querySelector('[data-ask-pill-list="true"]');if(A){let k=hv(p,n,a,o);A.replaceWith(k)}if(o!=="rows"){let k=t.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Mx(n,o))}let S=t.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!S?t.appendChild(xv(n)):(!m||i)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let M=t.querySelector('[data-ask-nav-row="true"]');if(i){let k=yv(d,l,n);M?M.replaceWith(k):t.appendChild(k)}else M&&M.remove();Lx(t),Px(t)},Cv=(t,e,r)=>{let n=Nl(e),o=cv(n),s=t.toolCall.id,a=Gs(r),i=Math.max(1,a.length),d=i>1,l=wv(t,a),p=d?vv(t,i):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ua,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Zp,String(i)),m.setAttribute(Yp,String(p)),m.setAttribute(eu,d?"true":"false"),m.setAttribute(Ax,o),Ex(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Tx(m,n);let u=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=v("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",u.appendChild(f);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",u.appendChild(y),m.appendChild(u);let S=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),o!=="rows"&&m.appendChild(Mx(n,o)),tu(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Av=(t,e,r)=>{let{payload:n}=xo(e),o=Math.max(1,Gs(n).length);o>qa(t)&&(t.setAttribute(Zp,String(o)),o>1&&!Oo(t)&&t.setAttribute(eu,"true")),tu(t,e,r)},Ix=(t,e)=>{let r=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Nl(e);Tx(r,n);let o=v("span","persona-ask-stub-label"),{complete:s}=xo(t);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},za=(t,e,r)=>{if(!r||!ho(t)||Nl(e).enabled===!1)return;let o=t.toolCall.id;r.querySelectorAll(`[${Ua}]`).forEach(l=>{l.getAttribute(Ua)!==o&&l.remove()});let a=r.querySelector(`[${Ua}="${Sx(o)}"]`);if(a){Av(a,t,e);return}let{payload:i}=xo(t),d=Cv(t,e,i);r.appendChild(d)},_o=(t,e)=>{if(!t)return;let r=e?`[${Ua}="${Sx(e)}"]`:`[${Ua}]`;t.querySelectorAll(r).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},ru=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),No=(t,e)=>{let r=fa(t),n=En(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete r[n]:r[n]=e,Ex(t,r),Lx(t),Px(t)},$l=(t,e,r,n)=>{let o=qa(t),s=Math.max(0,Math.min(o-1,n));bv(t,s),tu(t,e,r)};var nu=(t,e)=>{var A,S,M,k,E,h,w,x,T,W,R,B;let r=t.approval,n=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(A=n==null?void 0:n.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(S=n==null?void 0:n.borderColor)!=null?S:"var(--persona-approval-border, #fef08a)",!r)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=v("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(M=n==null?void 0:n.titleColor)!=null?M:"currentColor",p=Ie(d,20,l,2);p&&i.appendChild(p);let m=v("div","persona-flex-1 persona-min-w-0"),u=v("div","persona-flex persona-items-center persona-gap-2"),f=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",u.appendChild(f),!o){let _=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",r.status),r.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):r.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):r.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),u.appendChild(_)}m.appendChild(u);let y=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(y.style.color=n.descriptionColor),y.textContent=r.description,m.appendChild(y),r.parameters){let _=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(_.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(_.style.color=n.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=Ia(r.parameters),m.appendChild(_)}if(o){let _=v("div","persona-flex persona-gap-2 persona-mt-2");_.setAttribute("data-approval-buttons","true");let V=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=(E=n==null?void 0:n.approveButtonColor)!=null?E:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(h=n==null?void 0:n.approveButtonTextColor)!=null?h:"#ffffff",V.setAttribute("data-approval-action","approve");let oe=Ie("shield-check",14,(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",2);oe&&(oe.style.marginRight="4px",V.appendChild(oe));let be=document.createTextNode((x=n==null?void 0:n.approveLabel)!=null?x:"Approve");V.appendChild(be);let Qe=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Qe.type="button",Qe.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Qe.style.color=(W=n==null?void 0:n.denyButtonTextColor)!=null?W:"var(--persona-feedback-error, #dc2626)",Qe.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Qe.setAttribute("data-approval-action","deny");let je=Ie("shield-x",14,(R=n==null?void 0:n.denyButtonTextColor)!=null?R:"var(--persona-feedback-error, #dc2626)",2);je&&(je.style.marginRight="4px",Qe.appendChild(je));let ve=document.createTextNode((B=n==null?void 0:n.denyLabel)!=null?B:"Deny");Qe.appendChild(ve),_.append(V,Qe),m.appendChild(_)}return a.append(i,m),s.appendChild(a),s};var Rx=t=>{let e=[];return{buttons:e,render:(n,o,s,a,i)=>{if(t.innerHTML="",e.length=0,!n||!n.length||(a!=null?a:o?o.getMessages():[]).some(f=>f.role==="user"))return;let p=document.createDocumentFragment(),m=o?o.isStreaming():!1,u=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let y=v("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");y.type="button",y.textContent=f,y.disabled=m,i!=null&&i.fontFamily&&(y.style.fontFamily=u(i.fontFamily)),i!=null&&i.fontWeight&&(y.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(y.style.paddingLeft=i.paddingX,y.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(y.style.paddingTop=i.paddingY,y.style.paddingBottom=i.paddingY),y.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),p.appendChild(y),e.push(y)}),t.appendChild(p)}}};var Ks=class{constructor(e=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=r}push(e){var r;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(r=this.store)==null||r.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let r=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let n of r)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=e.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let r=this.getAll();return e>=r.length?r:r.slice(r.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(e="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=r}open(){return new Promise((e,r)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}getAll(){return new Promise((e,r)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{r(a.error)}}catch(n){r(n)}})}getCount(){return new Promise((e,r)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}clear(){return new Promise((e,r)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,r)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}};var Sv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Tv=new Set(["step_start","execution_start"]),kv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Mv=new Set(["step_complete","agent_turn_complete"]),Ev=new Set(["flow_complete","agent_complete"]),Wx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ma=(t,e)=>{let r=t[e];return Hx(r)?r:void 0};function ou(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ul(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Lv(t,e){return typeof e.type=="string"?e.type:t}function Pv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Iv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Bx(t){var n,o,s,a,i;let e=ma(t,"result"),r=[ma(t,"tokens"),ma(t,"totalTokens"),e?ma(e,"tokens"):void 0,ma(t,"usage"),e?ma(e,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=bn(d.output))!=null?n:bn(d.outputTokens))!=null?o:bn(d.completionTokens);if(l!==void 0)return l}return(i=(s=bn(t.outputTokens))!=null?s:bn(t.completionTokens))!=null?i:e?(a=bn(e.outputTokens))!=null?a:bn(e.completionTokens):void 0}function Rv(t){var r,n,o,s,a;let e=ma(t,"result");return(a=(o=(n=(r=bn(t.executionTime))!=null?r:bn(t.executionTimeMs))!=null?n:bn(t.execution_time))!=null?o:bn(t.duration))!=null?a:e?(s=bn(e.executionTime))!=null?s:bn(e.executionTimeMs):void 0}function Wv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Js=class{constructor(e=Wv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Ul(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,r){var s;if(!Hx(r)){Wx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=Lv(e,r),o=this.now();if(Sv.has(n)){this.startRun(o);return}if(Tv.has(n)){this.run||this.startRun(o);return}if(kv.has(n)){if(!Iv(n,r))return;let a=Pv(r);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+ou(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ul(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Mv.has(n)){if(!this.run)return;let a=this.run,i=Bx(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+ou(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:Ul(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Ev.has(n)){if(!this.run)return;let a=this.run,i=Bx(r),d=i!=null?i:a.exactOutputTokens+ou(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:Ul(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Wx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,r,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Rv(r);return s!=null?s:n-e.startedAt}};function Va(t,e){e&&e.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Bv={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)"}},Hv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Dv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ov=100;function _v(t,e){let r={...Bv,...e};if(r[t])return r[t];for(let n of Object.keys(r))if(n.endsWith("_")&&t.startsWith(n))return r[n];return Hv}function Nv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Fv(t){let e=new Date(t),r=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${r}:${n}:${o}.${s}`}function $v(t,e){try{let r=JSON.parse(t);if(typeof r!="object"||r===null)return null;for(let n of e){let o=n.split("."),s=r;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Uv(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(r=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),r()})}function qv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function zv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Vv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function jv(t,e,r){let n,o;try{o=JSON.parse(t.payload),n=JSON.stringify(o,null,2)}catch{o=t.payload,n=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let i=s.renderEventStreamPayload({event:t,config:r,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function au(t,e,r,n,o,s,a,i){var u;let d=o.has(t.id),l=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Va(l,(u=n.classNames)==null?void 0:u.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(f)return l.appendChild(f),l}return l.appendChild(m()),l;function m(){var V,oe;let f=v("div",""),y=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");y.setAttribute("data-event-id",t.id);let A=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=Ie(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&A.appendChild(S);let M=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(V=n.timestampFormat)!=null?V:"relative";M.textContent=k==="relative"?Nv(t.timestamp,r):Fv(t.timestamp);let E=null;n.showSequenceNumbers!==!1&&(E=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(e+1));let h=_v(t.type,n.badgeColors),w=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=h.bg,w.style.color=h.text,w.style.borderColor=h.text+"50",w.textContent=t.type;let x=(oe=n.descriptionFields)!=null?oe:Dv,T=$v(t.payload,x),W=null;T&&(W=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=T);let R=v("div","persona-flex-1 persona-min-w-0"),B=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),_=Ie("clipboard","12px","currentColor",1.5);return _&&B.appendChild(_),B.addEventListener("click",async be=>{be.stopPropagation(),await Uv(qv(t)),B.innerHTML="";let Qe=Ie("check","12px","currentColor",1.5);Qe&&B.appendChild(Qe),setTimeout(()=>{B.innerHTML="";let je=Ie("clipboard","12px","currentColor",1.5);je&&B.appendChild(je)},1500)}),y.appendChild(A),y.appendChild(M),E&&y.appendChild(E),y.appendChild(w),W&&y.appendChild(W),y.appendChild(R),y.appendChild(B),f.appendChild(y),d&&f.appendChild(jv(t,a,i)),f}}function Dx(t){var y,A,S,M,k;let{buffer:e,getFullHistory:r,onClose:n,config:o,plugins:s=[],getThroughput:a}=t,i=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(A=i==null?void 0:i.iconName)!=null?A:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",m=(k=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?k:{},u=s.find(E=>E.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let E=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:n});if(E)return{element:E,update:()=>{},destroy:()=>{}}}return f();function f(){let E=m.classNames,h=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Va(h,E==null?void 0:E.panel);let w=[],x="",T="",W=null,R=[],B={},_=0,V=Cl(),oe=0,be=0,Qe=!1,je=null,ve=!1,Ee=0,Ge=new Set,_e=new Map,X="",Ue="",K=null,Te,ae,xe,ke,Ke,ce=null,re=null,le=null;function ut(){let de=v("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ye=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Va(ye,E==null?void 0:E.headerBar);let Rt=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Rt.textContent="Events",Te=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Te.textContent="0",a){re=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),re.style.cursor="help";let dr=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");dr.textContent="Throughput",ce=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ce.textContent="-- tok/s",le=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let wr=re,Lr=le,Or=()=>{if(!Lr.textContent)return;let sn=wr.getBoundingClientRect(),fr=de.getBoundingClientRect();Lr.style.left=`${sn.left-fr.left}px`,Lr.style.top=`${sn.bottom-fr.top+4}px`,Lr.style.display="block"},xt=()=>{Lr.style.display="none"};re.addEventListener("mouseenter",Or),re.addEventListener("mouseleave",xt),re.appendChild(dr),re.appendChild(ce)}let ar=v("div","persona-flex-1");ae=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Mt=v("option","");Mt.value="",Mt.textContent="All events",ae.appendChild(Mt),xe=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),xe.type="button",xe.title="Copy All";let Ot=Ie("clipboard-copy","12px","currentColor",1.5);Ot&&xe.appendChild(Ot);let Wt=v("span","persona-text-xs");Wt.textContent="Copy All",xe.appendChild(Wt),ye.appendChild(Rt),ye.appendChild(Te),re&&ye.appendChild(re),ye.appendChild(ar),ye.appendChild(ae),ye.appendChild(xe);let St=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Va(St,E==null?void 0:E.searchBar);let Et=Ie("search","14px","var(--persona-muted, #9ca3af)",1.5),sr=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Et&&sr.appendChild(Et),ke=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Va(ke,E==null?void 0:E.searchInput),ke.type="text",ke.placeholder="Search event payloads...",Ke=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ke.type="button",Ke.style.display="none";let ft=Ie("x","12px","currentColor",2);return ft&&Ke.appendChild(ft),St.appendChild(sr),St.appendChild(ke),St.appendChild(Ke),de.appendChild(ye),de.appendChild(St),le&&de.appendChild(le),de}let Ce,he=s.find(de=>de.renderEventStreamToolbar);if(he!=null&&he.renderEventStreamToolbar&&o){let de=he.renderEventStreamToolbar({config:o,defaultRenderer:()=>ut(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ye=>{x=ye,pe(),N()},onSearchChange:ye=>{T=ye,pe(),N()}});Ce=de!=null?de:ut()}else Ce=ut();let tt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");tt.style.display="none";function Ne(){if(!a||!ce||!re)return;let de=a();ce.textContent=zv(de);let ye=Vv(de);le&&(le.textContent=ye,ye||(le.style.display="none")),ye?re.setAttribute("aria-label",ye):re.removeAttribute("aria-label")}let me=v("div","persona-flex-1 persona-min-h-0 persona-relative"),J=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ze=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Va(ze,E==null?void 0:E.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Z=Ie(l,"14px","currentColor",2);Z&&ze.appendChild(Z);let ge=v("span","");ge.textContent=p,ze.appendChild(ge);let z=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");z.style.display="none",me.appendChild(J),me.appendChild(z),me.appendChild(ze),h.setAttribute("tabindex","0"),h.appendChild(Ce),h.appendChild(tt),h.appendChild(me);function Re(){let de=e.getAll(),ye={};for(let Wt of de)ye[Wt.type]=(ye[Wt.type]||0)+1;let Rt=Object.keys(ye).sort(),ar=Rt.length!==R.length||!Rt.every((Wt,St)=>Wt===R[St]),Mt=!ar&&Rt.some(Wt=>ye[Wt]!==B[Wt]),mr=de.length!==Object.values(B).reduce((Wt,St)=>Wt+St,0);if(!ar&&!Mt&&!mr||(R=Rt,B=ye,!ae))return;let Ot=ae.value;if(ae.options[0].textContent="All events",ar){for(;ae.options.length>1;)ae.remove(1);for(let Wt of Rt){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${ye[Wt]||0})`,ae.appendChild(St)}Ot&&Rt.includes(Ot)?ae.value=Ot:Ot&&(ae.value="",x="")}else for(let Wt=1;Wt<ae.options.length;Wt++){let St=ae.options[Wt];St.textContent=`${St.value} (${ye[St.value]||0})`}}function Ae(){let de=e.getAll();if(x&&(de=de.filter(ye=>ye.type===x)),T){let ye=T.toLowerCase();de=de.filter(Rt=>Rt.type.toLowerCase().includes(ye)||Rt.payload.toLowerCase().includes(ye))}return de}function fe(){return x!==""||T!==""}function pe(){_=0,oe=0,V.resume(),ze.style.display="none"}function Be(de){Ge.has(de)?Ge.delete(de):Ge.add(de),K=de;let ye=J.scrollTop,Rt=V.isFollowing();ve=!0,V.pause(),N(),J.scrollTop=ye,Rt&&V.resume(),ve=!1}function Q(){return _s(J,50)}function N(){be=Date.now(),Qe=!1,Ne(),Re();let de=e.getEvictedCount();de>0?(tt.textContent=`${de.toLocaleString()} older events truncated`,tt.style.display=""):tt.style.display="none",w=Ae();let ye=w.length,Rt=e.getSize()>0;Te&&(Te.textContent=String(e.getSize())),ye===0&&Rt&&fe()?(z.textContent=T?`No events matching '${T}'`:"No events matching filter",z.style.display="",J.style.display="none"):(z.style.display="none",J.style.display=""),xe&&(xe.title=fe()?`Copy Filtered (${ye})`:"Copy All"),d&&!V.isFollowing()&&ye>_&&(oe+=ye-_,ge.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",ze.style.display=""),_=ye;let ar=e.getAll(),Mt=ar.length>0?ar[0].timestamp:0,mr=new Set(w.map(St=>St.id));for(let St of Ge)mr.has(St)||Ge.delete(St);let Ot=x!==X||T!==Ue,Wt=_e.size===0&&w.length>0;if(Ot||Wt||w.length===0){J.innerHTML="",_e.clear();let St=document.createDocumentFragment();for(let Et=0;Et<w.length;Et++){let sr=au(w[Et],Et,Mt,m,Ge,Be,s,o);_e.set(w[Et].id,sr),St.appendChild(sr)}J.appendChild(St),X=x,Ue=T,K=null}else{if(K!==null){let Et=_e.get(K);if(Et&&Et.parentNode===J){let sr=w.findIndex(ft=>ft.id===K);if(sr>=0){let ft=au(w[sr],sr,Mt,m,Ge,Be,s,o);J.insertBefore(ft,Et),Et.remove(),_e.set(K,ft)}}K=null}let St=new Set(w.map(Et=>Et.id));for(let[Et,sr]of _e)St.has(Et)||(sr.remove(),_e.delete(Et));for(let Et=0;Et<w.length;Et++){let sr=w[Et];if(!_e.has(sr.id)){let ft=au(sr,Et,Mt,m,Ge,Be,s,o);_e.set(sr.id,ft),J.appendChild(ft)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Me(){if(Date.now()-be>=Ov){je!==null&&(cancelAnimationFrame(je),je=null),N();return}Qe||(Qe=!0,je=requestAnimationFrame(()=>{je=null,N()}))}let He=(de,ye)=>{if(!xe)return;xe.innerHTML="";let Rt=Ie(de,"12px","currentColor",1.5);Rt&&xe.appendChild(Rt);let ar=v("span","persona-text-xs");ar.textContent="Copy All",xe.appendChild(ar),setTimeout(()=>{xe.innerHTML="";let Mt=Ie("clipboard-copy","12px","currentColor",1.5);Mt&&xe.appendChild(Mt);let mr=v("span","persona-text-xs");mr.textContent="Copy All",xe.appendChild(mr),xe.disabled=!1},ye)},Ve=async()=>{if(xe){xe.disabled=!0;try{let de;fe()?de=w:r?(de=await r(),de.length===0&&(de=e.getAll())):de=e.getAll();let ye=de.map(Rt=>{try{return JSON.parse(Rt.payload)}catch{return Rt.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),He("check",1500)}catch{He("x",1500)}}},Xe=()=>{ae&&(x=ae.value,pe(),N())},gt=()=>{!ke||!Ke||(Ke.style.display=ke.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{T=ke.value,pe(),N()},150))},ot=()=>{!ke||!Ke||(ke.value="",T="",Ke.style.display="none",W&&clearTimeout(W),pe(),N())},kt=()=>{if(ve)return;let de=J.scrollTop,{action:ye,nextLastScrollTop:Rt}=Al({following:V.isFollowing(),currentScrollTop:de,lastScrollTop:Ee,nearBottom:Q(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ee=Rt,ye==="resume"?(V.resume(),oe=0,ze.style.display="none"):ye==="pause"&&(V.pause(),d&&(ge.textContent=p,ze.style.display=""))},Xt=de=>{let ye=Sl({following:V.isFollowing(),deltaY:de.deltaY,nearBottom:Q(),resumeWhenNearBottom:!0});ye==="pause"?(V.pause(),d&&(ge.textContent=p,ze.style.display="")):ye==="resume"&&(V.resume(),oe=0,ze.style.display="none")},G=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),oe=0,ze.style.display="none")},Jt=de=>{let ye=de.target;if(!ye||ye.closest("button"))return;let Rt=ye.closest("[data-event-id]");if(!Rt)return;let ar=Rt.getAttribute("data-event-id");ar&&Be(ar)},at=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),ke==null||ke.focus(),ke==null||ke.select();return}de.key==="Escape"&&(ke&&document.activeElement===ke?(ot(),ke.blur(),h.focus()):n&&n())};xe&&xe.addEventListener("click",Ve),ae&&ae.addEventListener("change",Xe),ke&&ke.addEventListener("input",gt),Ke&&Ke.addEventListener("click",ot),J.addEventListener("scroll",kt),J.addEventListener("wheel",Xt,{passive:!0}),J.addEventListener("click",Jt),ze.addEventListener("click",G),h.addEventListener("keydown",at);function Nt(){W&&clearTimeout(W),je!==null&&(cancelAnimationFrame(je),je=null),Qe=!1,_e.clear(),xe&&xe.removeEventListener("click",Ve),ae&&ae.removeEventListener("change",Xe),ke&&ke.removeEventListener("input",gt),Ke&&Ke.removeEventListener("click",ot),J.removeEventListener("scroll",kt),J.removeEventListener("wheel",Xt),J.removeEventListener("click",Jt),ze.removeEventListener("click",G),h.removeEventListener("keydown",at)}return{element:h,update:Me,destroy:Nt}}}function Ox(t,e){let r=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",n=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(u);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(l.append(p,m),i.append(d,l),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",n),i.append(u)}return i}var _x=(t,e)=>{var n,o,s;let r=(s=(o=(n=e==null?void 0:e.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(r){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=r({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:e.config,defaultRenderer:()=>Ox(t,e)});if(p)return p}return Ox(t,e)};var su=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,n])=>{this.register(r,n)})}},yo=new su;yo.register("PersonaArtifactCard",_x);function Gv(t){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=v("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=t.component?`Component: ${t.component}`:"Component";let n=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(r),e.appendChild(n),e}function Nx(t,e){var ae,xe,ke,Ke;let r=(xe=(ae=t.features)==null?void 0:ae.artifacts)==null?void 0:xe.layout,o=((ke=r==null?void 0:r.toolbarPreset)!=null?ke:"default")==="document",s=(Ke=r==null?void 0:r.panePadding)==null?void 0:Ke.trim(),a=t.markdown?ra(t.markdown):null,i=Ma(t.sanitize),d=ce=>{let re=a?a(ce):na(ce);return i?i(re):re},l=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let m=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),o&&m.classList.add("persona-artifact-pane-document");let u=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let f=v("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let y=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let A="rendered",S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Er({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Er({icon:"eye",label:"Rendered view"}),k=o?Er({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Er({icon:"code-2",label:"Source"}),E=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),h=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,x=r==null?void 0:r.documentToolbarCopyMenuItems,T=!!(w&&x&&x.length>0),W=null,R,B=null,_=null;if(o&&(h||w)&&!T){if(R=h?js({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ce=Ie("chevron-down",14,"currentColor",2);ce&&R.appendChild(ce)}}else o&&T?(W=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),R=h?js({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=Er({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),W.append(R,B)):o?R=Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):R=Er({icon:"copy",label:"Copy"});let V=o?Er({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Er({icon:"refresh-cw",label:"Refresh"}),oe=o?Er({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Er({icon:"x",label:"Close"}),be=()=>{var Ce,he,tt;let ce=(Ce=_e.find(Ne=>Ne.id===X))!=null?Ce:_e[_e.length-1],re=(he=ce==null?void 0:ce.id)!=null?he:null,le=(ce==null?void 0:ce.artifactType)==="markdown"&&(tt=ce.markdown)!=null?tt:"",ut=ce?JSON.stringify({component:ce.component,props:ce.props},null,2):"";return{markdown:le,jsonPayload:ut,id:re}},Qe=async()=>{var Ce;let{markdown:ce,jsonPayload:re}=be(),le=(Ce=_e.find(he=>he.id===X))!=null?Ce:_e[_e.length-1],ut=(le==null?void 0:le.artifactType)==="markdown"?ce:le?re:"";try{await navigator.clipboard.writeText(ut)}catch{}};if(R.addEventListener("click",async()=>{let ce=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ce&&T){let{markdown:re,jsonPayload:le,id:ut}=be();try{await ce({actionId:"primary",artifactId:ut,markdown:re,jsonPayload:le})}catch{}return}await Qe()}),B&&(x!=null&&x.length)){let ce=()=>{var le;return(le=m.closest("[data-persona-root]"))!=null?le:document.body},re=()=>{_=Ho({items:x.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:ut,jsonPayload:Ce,id:he}=be(),tt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{tt?await tt({actionId:le,artifactId:he,markdown:ut,jsonPayload:Ce}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(ut):le==="json"||le==="source"?await navigator.clipboard.writeText(Ce):await navigator.clipboard.writeText(ut||Ce)}catch{}},anchor:W!=null?W:B,position:"bottom-right",portal:ce()})};m.isConnected?re():requestAnimationFrame(re),B.addEventListener("click",le=>{le.stopPropagation(),_==null||_.toggle()})}V.addEventListener("click",async()=>{var ce;try{await((ce=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ce.call(r))}catch{}K()}),oe.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let je=()=>{o&&(M.setAttribute("aria-pressed",A==="rendered"?"true":"false"),k.setAttribute("aria-pressed",A==="source"?"true":"false"))};M.addEventListener("click",()=>{A="rendered",je(),K()}),k.addEventListener("click",()=>{A="source",je(),K()});let ve=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),S.append(M,k),W?E.append(W,V,oe):E.append(R,V,oe),u.append(S,ve,E),je()):(u.appendChild(f),u.appendChild(y)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Ee=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Ge=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ee.style.paddingLeft=s,Ee.style.paddingRight=s,Ge.style.padding=s),m.appendChild(u),m.appendChild(Ee),m.appendChild(Ge);let _e=[],X=null,Ue=!1,K=()=>{var ut,Ce,he,tt;let ce=o&&_e.length<=1;Ee.classList.toggle("persona-hidden",ce),Ee.replaceChildren();for(let Ne of _e){let me=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");me.type="button",me.textContent=Ne.title||Ne.id.slice(0,8),Ne.id===X&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>e.onSelect(Ne.id)),Ee.appendChild(me)}Ge.replaceChildren();let re=X&&_e.find(Ne=>Ne.id===X)||_e[_e.length-1];if(!re)return;if(o){let Ne=re.artifactType==="markdown"?"MD":(ut=re.component)!=null?ut:"Component",J=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${J} \xB7 ${Ne}`}else f.textContent="Artifacts";if(re.artifactType==="markdown"){if(o&&A==="source"){let me=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(Ce=re.markdown)!=null?Ce:"",Ge.appendChild(me);return}let Ne=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ne.innerHTML=d((he=re.markdown)!=null?he:""),Ge.appendChild(Ne);return}let le=re.component?yo.get(re.component):void 0;if(le){let me={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let J=le((tt=re.props)!=null?tt:{},me);if(J){Ge.appendChild(J);return}}catch{}}Ge.appendChild(Gv(re))},Te=()=>{var re;let ce=_e.length>0;if(m.classList.toggle("persona-hidden",!ce),l){let le=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ce=((re=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ce&&Ce&&Ue?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(ce){var re,le,ut;_e=ce.artifacts,X=(ut=(le=ce.selectedId)!=null?le:(re=ce.artifacts[ce.artifacts.length-1])==null?void 0:re.id)!=null?ut:null,_e.length>0&&(Ue=!0),K(),Te()},setMobileOpen(ce){Ue=ce,!ce&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Te()}}}function Ln(t){var e,r;return((r=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:r.enabled)===!0}function Fx(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Ln(e))return;let r=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,n=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),o=(d=r==null?void 0:r.paneBorderLeft)==null?void 0:d.trim();n?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",n)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function Kv(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ql(t,e){var d,l,p,m,u,f,y,A,S,M;if(!Ln(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Kv(t),Fx(t,e);return}let r=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;t.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(m=r==null?void 0:r.paneWidth)!=null?m:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=r==null?void 0:r.paneBackground)==null?void 0:f.trim();n?t.style.setProperty("--persona-artifact-pane-bg",n):t.style.removeProperty("--persona-artifact-pane-bg");let o=(y=r==null?void 0:r.panePadding)==null?void 0:y.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(A=r==null?void 0:r.documentToolbarIconColor)==null?void 0:A.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Fx(t,e)}var $x=["panel","seamless"];function zl(t,e){var i,d,l,p,m,u;for(let f of $x)t.classList.remove(`persona-artifact-appearance-${f}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!Ln(e))return;let r=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",o=$x.includes(n)?n:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=r==null?void 0:r.paneShadow)==null?void 0:m.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(r==null?void 0:r.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let f=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;f&&t.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Ux(t,e){var r,n,o;return!e||!Ln(t)?!1:((o=(n=(r=t.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Xv(t,e){if(!(t!=null&&t.trim()))return e;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return r?Math.max(0,Number(r[1])):e}function Jv(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Qv(t,e,r){return r<e?e:Math.min(r,Math.max(e,t))}function Yv(t,e,r,n){let o=t-n-2*e-r;return Math.max(0,o)}function qx(t,e){var a;let n=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(n);return s?Number(s[1]):8}function zx(t,e,r,n,o,s){let a=Xv(o,200),i=Yv(e,r,n,200);i=Math.max(a,i);let d=Jv(s);return d!==null&&(i=Math.min(i,d)),Qv(t,a,i)}var Vx={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},iu=(t,e,r,n)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,A,S;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(A=Vx[a])!=null?A:Vx.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),l=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let M=v("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var x,T;let k=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${e.id}-${a}-${M.name}`;let E=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=M.label,k.appendChild(E);let h=(x=M.type)!=null?x:"text",w;h==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=h),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=`${e.id}-${a}-${M.name}`,w.name=M.name,w.placeholder=(T=M.placeholder)!=null?T:"",M.required&&(w.required=!0),k.appendChild(w),p.appendChild(k)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(S=i.submitLabel)!=null?S:"Submit",m.appendChild(u),m.appendChild(f),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async M=>{var w,x;M.preventDefault();let k=(w=r.formEndpoint)!=null?w:"/form",E=new FormData(p),h={};E.forEach((T,W)=>{h[W]=T}),h.type=a,f.disabled=!0,u.textContent="Submitting\u2026";try{let T=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let W=await T.json();u.textContent=(x=W.message)!=null?x:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await n.sendMessage(String(W.nextPrompt))}catch(T){u.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var lu=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var n;let r=this.plugins.get(e);r&&((n=r.onUnregister)==null||n.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var n,o;return((n=r.priority)!=null?n:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let n=new Set(e.map(s=>s.id));return[...r.filter(s=>!n.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},Qs=new lu;var jx=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Zv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},eC=t=>{let e=t.trim(),r=e.indexOf("{");if(r===-1)return null;let n=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(n+=1),s==="}"&&(n-=1,n===0))return e.slice(r,o+1)}return null},Ys=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Zv(t),r=eC(e);if(!r)return null;let n=JSON.parse(r);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...s}=n;return{type:String(o),payload:s,raw:n}}catch{return null}},du=t=>typeof t=="string"?t:t==null?"":String(t),ga={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:du(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,n=du(r.element);if(n&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(n);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:du(r.text)}}},Gx=t=>Array.isArray(t)?t.map(e=>String(e)):[],Zs=t=>{let e=new Set(Gx(t.getSessionMetadata().processedActionMessageIds)),r=()=>{e=new Set(Gx(t.getSessionMetadata().processedActionMessageIds))},n=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),n();let d={action:i,message:s.message};t.emit("action:detected",d);for(let l of t.handlers)if(l)try{let p=()=>{t.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let u=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:u,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var tC=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},rC=t=>t.map(e=>({...e,streaming:!1})),nC=t=>t.map(e=>({...e,status:"complete"})),Vl=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?tC(r.getItem(t)):null},save:r=>{let n=e();if(n)try{let o={...r,messages:r.messages?rC(r.messages):void 0,artifacts:r.artifacts?nC(r.artifacts):void 0};n.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(t)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var ja=od(Ui(),1);function oC(t){if(!t||typeof t!="object"||!("component"in t))return!1;let e=t.component;return typeof e=="string"&&e.length>0}function aC(t,e){if(!oC(t))return null;let r=t.props&&typeof t.props=="object"&&t.props!==null?t.props:{};return{component:t.component,props:r,raw:e}}function jl(){let t=null,e=0;return{getExtractedDirective:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t;try{let o=(0,ja.parse)(r,ja.STR|ja.OBJ),s=aC(o,r);s&&(t=s)}catch{}return e=r.length,t},reset:()=>{t=null,e=0}}}function Kx(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function Gl(t,e){let{config:r,message:n,onPropsUpdate:o}=e,s=yo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:r,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Xx(){let t=jl();return{processChunk:e=>t.processChunk(e),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function Jx(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Kl(t){let e=Jx(t);if(!e)return!1;try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Xl(t){let e=Jx(t);if(!e)return null;try{let r=JSON.parse(e);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let n=r;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e}}}catch{}return null}var sC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Jl(t){let{onSubmit:e,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=sC}=t,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,u=document.createElement("div");u.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=n,f.appendChild(y);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=o,f.appendChild(A),u.appendChild(f);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let x=1;x<=5;x++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${l[x-1]}`),T.title=l[x-1],T.dataset.rating=String(x),T.innerHTML=`
|
|
73
|
+
`,r.addEventListener("click",e);let n=s=>{var M,h,w,y,E,B,P,R,O,V,ne,be,Ye,Ge;let a=(M=s.launcher)!=null?M:{},i=Ar(s),d=r.querySelector("[data-role='launcher-title']");if(d){let ve=(h=a.title)!=null?h:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let ve=(w=a.subtitle)!=null?w:"Get answers fast";l.textContent=ve,l.setAttribute("title",ve)}let p=r.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=r.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ve=(y=a.agentIconSize)!=null?y:"40px";if(m.style.height=ve,m.style.width=ve,m.innerHTML="",a.agentIconName){let Ee=parseFloat(ve)||24,Ke=Ie(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);Ke?(m.appendChild(Ke),m.style.display=""):(m.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",m.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let ve=(P=a.agentIconSize)!=null?P:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ve=(R=a.callToActionIconSize)!=null?R:"32px";f.style.height=ve,f.style.width=ve,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ke=parseFloat(ve)||24,Ne=Math.max(Ke-Ee,8),X=Ie(a.callToActionIconName,Ne,"currentColor",2);X?f.appendChild(X):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let x=a.position&&$n[a.position]?$n[a.position]:$n["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",S="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?S:`${C} ${x}`,i||(r.style.zIndex=String((ne=a.zIndex)!=null?ne:qr));let k="1px solid var(--persona-border, #e5e7eb)",T="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(be=a.border)!=null?be:k,r.style.boxShadow=(Ye=a.shadow)!=null?Ye:T,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=(Ge=a.collapsedMaxWidth)!=null?Ge:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},o=()=>{r.removeEventListener("click",e),r.remove()};return t&&n(t),{element:r,update:n,destroy:o}};var Dw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Pl=(t,e={})=>{var C,S,k,T,M,h;let{showClose:r=!0,wrapperClassName:n=Dw,buttonSize:o,iconSize:s="28px"}=e,a=(C=t==null?void 0:t.launcher)!=null?C:{},i=(S=o!=null?o:a.closeButtonSize)!=null?S:"32px",d=v("div",n),l=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(k=a.closeButtonTooltipText)!=null?k:"Close chat",m=(T=a.closeButtonShowTooltip)!=null?T:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let u=(M=a.closeButtonIconName)!=null?M:"x",f=(h=a.closeButtonIconText)!=null?h:"\xD7";l.style.color=a.closeButtonColor||en.actionIconColor;let x=Ie(u,s,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):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 w=a.closeButtonBorderWidth||"0px",y=a.closeButtonBorderColor||"transparent";l.style.border=`${w} solid ${y}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let w=null,y=()=>{if(w)return;let B=l.ownerDocument,P=B.body;if(!P)return;w=Qn(B,"div","persona-clear-chat-tooltip"),w.textContent=p;let R=Qn(B,"div");R.className="persona-clear-chat-tooltip-arrow",w.appendChild(R);let O=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(Wo),w.style.left=`${O.left+O.width/2}px`,w.style.top=`${O.top-8}px`,w.style.transform="translate(-50%, -100%)",P.appendChild(w)},E=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};d.addEventListener("mouseenter",y),d.addEventListener("mouseleave",E),l.addEventListener("focus",y),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",y),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",y),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},Ow="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Il=(t,e={})=>{var w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve;let{wrapperClassName:r=Ow,buttonSize:n,iconSize:o="20px"}=e,a=(y=((w=t==null?void 0:t.launcher)!=null?w:{}).clearChat)!=null?y:{},i=(E=n!=null?n:a.size)!=null?E:"32px",d=(B=a.iconName)!=null?B:"refresh-cw",l=(P=a.iconColor)!=null?P:"",p=(R=a.backgroundColor)!=null?R:"",m=(O=a.borderWidth)!=null?O:"",u=(V=a.borderColor)!=null?V:"",f=(ne=a.borderRadius)!=null?ne:"",x=(be=a.paddingX)!=null?be:"",C=(Ye=a.paddingY)!=null?Ye:"",S=(Ge=a.tooltipText)!=null?Ge:"Clear chat",k=(ve=a.showTooltip)!=null?ve:!0,T=v("div",r),M=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",S),M.style.color=l||en.actionIconColor;let h=Ie(d,o,"currentColor",1);if(h&&(h.style.display="block",M.appendChild(h)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),m||u){let Ee=m||"0px",Ke=u||"transparent";M.style.border=`${Ee} solid ${Ke}`,M.classList.remove("persona-border-none")}if(f&&(M.style.borderRadius=f,M.classList.remove("persona-rounded-full")),x&&(M.style.paddingLeft=x,M.style.paddingRight=x),C&&(M.style.paddingTop=C,M.style.paddingBottom=C),T.appendChild(M),k&&S){let Ee=null,Ke=()=>{if(Ee)return;let X=M.ownerDocument,Ue=X.body;if(!Ue)return;Ee=Qn(X,"div","persona-clear-chat-tooltip"),Ee.textContent=S;let K=Qn(X,"div");K.className="persona-clear-chat-tooltip-arrow",Ee.appendChild(K);let Te=M.getBoundingClientRect();Ee.style.position="fixed",Ee.style.zIndex=String(Wo),Ee.style.left=`${Te.left+Te.width/2}px`,Ee.style.top=`${Te.top-8}px`,Ee.style.transform="translate(-50%, -100%)",Ue.appendChild(Ee)},Ne=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};T.addEventListener("mouseenter",Ke),T.addEventListener("mouseleave",Ne),M.addEventListener("focus",Ke),M.addEventListener("blur",Ne),T._cleanupTooltip=()=>{Ne(),T.removeEventListener("mouseenter",Ke),T.removeEventListener("mouseleave",Ne),M.removeEventListener("focus",Ke),M.removeEventListener("blur",Ne)}}return{button:M,wrapper:T}};var en={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},go=t=>{var w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve,Ee,Ke,Ne;let{config:e,showClose:r=!0}=t,n=v("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(w=e==null?void 0:e.launcher)!=null?w:{},s=(y=o.headerIconSize)!=null?y:"48px",a=(E=o.closeButtonPlacement)!=null?E:"inline",i=(B=o.headerIconHidden)!=null?B:!1,d=o.headerIconName,l=v("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let X=parseFloat(s)||24,Ue=Ie(d,X*.6,"currentColor",1);Ue?l.replaceChildren(Ue):l.textContent=(R=(P=e==null?void 0:e.launcher)==null?void 0:P.agentIconText)!=null?R:"\u{1F4AC}"}else if((O=e==null?void 0:e.launcher)!=null&&O.iconUrl){let X=v("img");X.src=e.launcher.iconUrl,X.alt="",X.className="persona-rounded-xl persona-object-cover",X.style.height=s,X.style.width=s,l.replaceChildren(X)}else l.textContent=(ne=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=v("span","persona-text-base persona-font-semibold");m.style.color=en.titleColor,m.textContent=(Ye=(be=e==null?void 0:e.launcher)==null?void 0:be.title)!=null?Ye:"Chat Assistant";let u=v("span","persona-text-xs");u.style.color=en.subtitleColor,u.textContent=(ve=(Ge=e==null?void 0:e.launcher)==null?void 0:Ge.subtitle)!=null?ve:"Here to help you get answers fast",p.append(m,u),i?n.append(p):n.append(l,p);let f=(Ee=o.clearChat)!=null?Ee:{},x=(Ke=f.enabled)!=null?Ke:!0,C=(Ne=f.placement)!=null?Ne:"inline",S=null,k=null;if(x){let Ue=Il(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=Ue.button,k=Ue.wrapper,C==="top-right"&&(k.style.right="48px"),C==="inline"&&n.appendChild(k)}let T=a==="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:M,wrapper:h}=Pl(e,{showClose:r,wrapperClassName:T});return a!=="top-right"&&n.appendChild(h),{header:n,iconHolder:l,headerTitle:m,headerSubtitle:u,closeButton:M,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:k}},ua=(t,e,r)=>{var a,i,d,l;let n=(a=r==null?void 0:r.launcher)!=null?a:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",s=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function Do(t){let{items:e,onSelect:r,anchor:n,position:o="bottom-left",portal:s}=t,a=v("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Wo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}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 S=Ie(f.icon,16,"currentColor",1.5);S&&x.appendChild(S)}let C=document.createElement("span");C.textContent=f.label,x.appendChild(C),x.addEventListener("click",S=>{S.stopPropagation(),p(),r(f.id)}),a.appendChild(x)}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=x=>{!a.contains(x.target)&&!n.contains(x.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function u(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:u}}function Er(t){let{icon:e,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",r),d.title=r;let l=Ie(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Gs(t){let{icon:e,label:r,variant:n="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=v("button",l);if(p.type="button",p.setAttribute("aria-label",r),e){let u=Ie(e,s!=null?s:14,"currentColor",2);u&&p.appendChild(u)}let m=v("span");if(m.textContent=r,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[u,f]of Object.entries(d))p.setAttribute(u,f);return p}function px(t){let{items:e,selectedId:r,onSelect:n,className:o}=t,s=v("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=r,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of e){let m;p.icon?m=Er({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(m=v("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),s.appendChild(m)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Rl(t){var f,x;let{label:e,icon:r="chevron-down",menuItems:n,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,l=v("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",e);let p=v("span","persona-combo-btn-label");p.textContent=e,l.appendChild(p);let m=Ie(r,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(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,S;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Do({items:n,onSelect:C=>{l.setAttribute("aria-expanded","false"),o(C)},anchor:l,position:s,portal:a});return a||l.appendChild(u.element),l.addEventListener("click",C=>{C.stopPropagation();let S=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),u.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"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let C=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Up=t=>{var n;let e=go({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),r=(n=t.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(r){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>r()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())}))}return e};function Nw(t,e,r){var n,o,s;if(e!=null&&e.length)for(let a of e){let i=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=a.ariaLabel)!=null?n:a.label)!=null?o:a.id),a.icon){let d=Ie(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(i);let l=Do({items:a.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>r==null?void 0:r(a.id)),t.appendChild(i)}}var qp=t=>{var T,M,h,w,y,E,B,P,R;let{config:e,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Rl({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=(h=l.querySelector(".persona-combo-btn-label"))!=null?h:l;else{if(l=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=en.titleColor,p.textContent=(w=a.title)!=null?w:"Chat Assistant",l.appendChild(p),Nw(l,o==null?void 0:o.trailingActions,(y=o==null?void 0:o.onAction)!=null?y:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=o.onTitleClick;l.addEventListener("click",ne=>{ne.target.closest("button")||V()}),l.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",l.style.padding=(B=O.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 V,ne;l.style.backgroundColor=(V=O.background)!=null?V:"",l.style.borderColor=(ne=O.border)!=null?ne:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(P=a.closeButtonSize)!=null?P:"32px",u=v("div",""),f=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=a.closeButtonColor||en.actionIconColor;let x=(R=a.closeButtonIconName)!=null?R:"x",C=Ie(x,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",n&&f.addEventListener("click",n),u.appendChild(f),i.appendChild(u);let S=v("div");S.style.display="none";let k=v("span");return k.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:k,closeButton:f,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Wl={default:Up,minimal:qp},zp=t=>{var e;return(e=Wl[t])!=null?e:Wl.default},Na=(t,e,r)=>{var a,i,d;if(e!=null&&e.render){let l=e.render({config:t,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=v("div");p.style.display="none";let m=v("span"),u=v("span"),f=v("button");f.style.display="none";let x=v("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:u,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=e==null?void 0:e.layout)!=null?a:"default",s=zp(n)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Bl=t=>{var a,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,n=20;e.style.maxHeight=`${r*n}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:r*n},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Hl=t=>{var w,y,E,B,P,R,O,V,ne,be,Ye,Ge;let e=(w=t==null?void 0:t.sendButton)!=null?w:{},r=(y=e.useIcon)!=null?y:!1,n=(E=e.iconText)!=null?E:"\u2191",o=e.iconName,s=(B=e.stopIconName)!=null?B:"square",a=(P=e.tooltipText)!=null?P:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(V=(O=t==null?void 0:t.copy)==null?void 0:O.sendButtonLabel)!=null?V:"Send",l=(be=(ne=t==null?void 0:t.copy)==null?void 0:ne.stopButtonLabel)!=null?be:"Stop",p=(Ye=e.showTooltip)!=null?Ye:!1,m=(Ge=e.size)!=null?Ge:"40px",u=e.backgroundColor,f=e.textColor,x=v("div","persona-send-button-wrapper"),C=v("button",r?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");C.type="submit",C.setAttribute("data-persona-composer-submit","");let S=null,k=null;if(r){C.style.width=m,C.style.height=m,C.style.minWidth=m,C.style.minHeight=m,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 ve=parseFloat(m)||24,Ee=(f==null?void 0:f.trim())||"currentColor";o?(S=Ie(o,ve,Ee,2),S?C.appendChild(S):C.textContent=n):C.textContent=n,k=Ie(s,ve,Ee,2),u?C.style.backgroundColor=u:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,f?C.style.color=f:C.classList.add("persona-text-white");e.borderWidth&&(C.style.borderWidth=e.borderWidth,C.style.borderStyle="solid"),e.borderColor&&(C.style.borderColor=e.borderColor),e.paddingX?(C.style.paddingLeft=e.paddingX,C.style.paddingRight=e.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),e.paddingY?(C.style.paddingTop=e.paddingY,C.style.paddingBottom=e.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let T=null;p&&a&&(T=v("div","persona-send-button-tooltip"),T.textContent=a,x.appendChild(T)),C.setAttribute("aria-label",a),x.appendChild(C);let M="send";return{button:C,wrapper:x,setMode:ve=>{if(ve===M)return;M=ve;let Ee=ve==="stop"?i:a;if(C.setAttribute("aria-label",Ee),T&&(T.textContent=Ee),r){if(S&&k){let Ke=ve==="stop"?k:S;C.replaceChildren(Ke)}}else C.textContent=ve==="stop"?l:d}}},Dl=t=>{var T,M,h,w,y,E,B,P,R,O,V,ne;let e=(T=t==null?void 0:t.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=e.provider)==null?void 0:M.type)==="runtype";if(!(n||o))return null;let a=(w=(h=t==null?void 0:t.sendButton)==null?void 0:h.size)!=null?w:"40px",i=v("div","persona-send-button-wrapper"),d=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(y=e.iconName)!=null?y:"mic",p=(E=e.iconSize)!=null?E:a,m=parseFloat(p)||24,u=(P=e.backgroundColor)!=null?P:(B=t==null?void 0:t.sendButton)==null?void 0:B.backgroundColor,f=(O=e.iconColor)!=null?O:(R=t==null?void 0:t.sendButton)==null?void 0:R.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=Ie(l,m,f||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",u&&(d.style.backgroundColor=u),e.borderWidth&&(d.style.borderWidth=e.borderWidth,d.style.borderStyle="solid"),e.borderColor&&(d.style.borderColor=e.borderColor),e.paddingX&&(d.style.paddingLeft=e.paddingX,d.style.paddingRight=e.paddingX),e.paddingY&&(d.style.paddingTop=e.paddingY,d.style.paddingBottom=e.paddingY),i.appendChild(d);let S=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((ne=e.showTooltip)!=null?ne:!1)&&S){let be=v("div","persona-send-button-tooltip");be.textContent=S,i.appendChild(be)}return{button:d,wrapper:i}},Ol=t=>{var x,C,S,k,T,M,h,w;let e=(x=t==null?void 0:t.attachments)!=null?x:{};if(e.enabled!==!0)return null;let r=(S=(C=t==null?void 0:t.sendButton)==null?void 0:C.size)!=null?S:"40px",n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=v("input");o.type="file",o.accept=((k=e.allowedTypes)!=null?k:mo).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=v("div","persona-send-button-wrapper"),a=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(M=e.buttonTooltipText)!=null?M:"Attach file");let i=(h=e.buttonIconName)!=null?h:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Ie(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",y=>{y.preventDefault(),o.click()}),s.appendChild(a);let u=(w=e.buttonTooltipText)!=null?w:"Attach file",f=v("div","persona-send-button-tooltip");return f.textContent=u,s.appendChild(f),{button:a,wrapper:s,input:o,previewsContainer:n}},Nl=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},r=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",n=v("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;n.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=v("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=s;return n},_l=()=>v("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var _a=t=>{var x,C,S,k,T,M;let{config:e}=t,r=v("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");r.setAttribute("data-persona-theme-zone","composer");let n=_l(),o=v("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Bl(e);a();let i=Hl(e),d=Dl(e),l=Ol(e),p=Nl(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let m=v("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),u=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(u,f),o.append(m),o.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==(d==null?void 0:d.button)&&h.target!==(d==null?void 0:d.wrapper)&&h.target!==(l==null?void 0:l.button)&&h.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:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(k=l==null?void 0:l.wrapper)!=null?k:null,attachmentInput:(T=l==null?void 0:l.input)!=null?T:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var ux=()=>{let t=v("button","persona-pill-peek");t.type="button",t.setAttribute("data-persona-pill-peek",""),t.setAttribute("aria-label","Show conversation"),t.setAttribute("tabindex","-1");let e=v("span","persona-pill-peek__icon"),r=Ie("message-square",16,"currentColor",1.5);r&&e.appendChild(r);let n=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=Ie("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,n,o),{root:t,textNode:n}},fx=t=>{var x,C,S,k,T,M;let{config:e}=t,r=v("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=_l();n.style.display="none";let o=Nl(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Bl(e);s.style.maxHeight="100px",a();let i=Hl(e),d=Dl(e),l=Ol(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=v("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=v("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let u=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),p.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==(d==null?void 0:d.button)&&h.target!==(d==null?void 0:d.wrapper)&&h.target!==(l==null?void 0:l.button)&&h.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,u),l&&r.append(l.previewsContainer),r.append(p,n,o);let f=p;return{footer:r,suggestions:n,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:o,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(k=l==null?void 0:l.wrapper)!=null?k:null,attachmentInput:(T=l==null?void 0:l.input)!=null?T:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:f,leftActions:m,rightActions:u,setSendButtonMode:i.setMode}};var mx=t=>{var p,m,u,f,x,C,S,k,T,M,h,w,y,E,B,P,R;let e=(m=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)!=null?m:!0,r=Ar(t);if(Ho(t)){let O=(f=(u=t==null?void 0:t.launcher)==null?void 0:u.composerBar)!=null?f:{},V=v("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(x=O.expandedSize)!=null?x:"anchored",V.style.zIndex=String((S=(C=t==null?void 0:t.launcher)==null?void 0:C.zIndex)!=null?S:qr);let ne=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let be=v("div","persona-widget-pill-root");return be.setAttribute("data-persona-composer-bar",""),be.dataset.state="collapsed",be.dataset.expandedSize=(k=O.expandedSize)!=null?k:"anchored",be.style.zIndex=String((M=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?M:qr),{wrapper:V,panel:ne,pillRoot:be}}if(r){let O=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(V),{wrapper:O,panel:V}}if(!e){let O=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(w=(h=t==null?void 0:t.launcher)==null?void 0:h.width)!=null?w:"100%";return O.style.width=ne,V.style.width="100%",O.appendChild(V),{wrapper:O,panel:V}}let o=(y=t==null?void 0:t.launcher)!=null?y:{},s=o.position&&$n[o.position]?$n[o.position]:$n["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((B=(E=t==null?void 0:t.launcher)==null?void 0:E.zIndex)!=null?B:qr);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(P=t==null?void 0:t.launcher)==null?void 0:P.width)!=null?R:t==null?void 0:t.launcherWidth,l=d!=null?d:yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},_w=(t,e)=>{var h,w,y,E,B,P,R,O,V;let r=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Pl(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(y=(w=(h=t==null?void 0:t.launcher)==null?void 0:h.clearChat)==null?void 0:w.enabled)!=null?y:!0,a=null,i=null;if(s){let ne=Il(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=v("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(B=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeTitle)!=null?B:"Hello \u{1F44B}";let u=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(R=(P=t==null?void 0:t.copy)==null?void 0:P.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(m,u);let f=v("div","persona-flex persona-flex-col persona-gap-3"),x=(O=t==null?void 0:t.layout)==null?void 0:O.contentMaxWidth;x&&(f.style.maxWidth=x,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((V=t==null?void 0:t.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,f);let S=v("div","persona-composer-overlay persona-pointer-events-none");S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20";let k=fx({config:t}),{root:T,textNode:M}=ux();return r.append(d,o,l,S),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:f,composerOverlay:S,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:m,introSubtitle:u,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:T,peekTextNode:M}},gx=(t,e=!0)=>{var S,k,T,M,h,w,y,E,B;if(Ho(t))return _w(t,e);let r=v("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");r.setAttribute("data-persona-theme-zone","container");let n=(S=t==null?void 0:t.layout)==null?void 0:S.header,o=((k=t==null?void 0:t.layout)==null?void 0:k.showHeader)!==!1,s=n?Na(t,n,{showClose:e}):go({config:t,showClose:e}),a=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Ar(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(M=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(h=t==null?void 0:t.copy)==null?void 0:h.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let p=v("div","persona-flex persona-flex-col persona-gap-3"),m=(y=t==null?void 0:t.layout)==null?void 0:y.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((E=t==null?void 0:t.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=_a({config:t}),x=((B=t==null?void 0:t.layout)==null?void 0:B.showFooter)!==!1;o?ua(r,s,t):(s.header.style.display="none",ua(r,s,t)),r.append(a);let C=v("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: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 Fw=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},$w=(t,e)=>{if(!t)return null;let r=Fw(t);if(r===null)return null;let n=e==null?void 0:e[t],o=n!==void 0?n:r;return o||null},Uw=(t,e)=>{let r=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",t),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=e,r},qw=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Vp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},jp=320,xx=320,zw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Vw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),jw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Gw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Kw=(t,e,r)=>{if(t.length===0)return null;try{let n=v("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),e&&(n.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,n.remove(),r==null||r())};return t.forEach((i,d)=>{var m;let l=v("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${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&&a())}),l.addEventListener("load",()=>{p=!0}),qw(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}},Xw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let r=0;return t.forEach(n=>{if(!Vp(n.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${jp}px`,e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Jw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let r=0;return t.forEach(n=>{if(!Vp(n.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${jp}px`,o.style.maxHeight=`${xx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Qw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let r=0;return t.forEach(n=>{if(!Vp(n.data))return;let o=v("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},fa=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(r),t.appendChild(n),t.appendChild(o),t},Gp=(t,e,r)=>{let n={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:fa};if(e){let o=e(n);if(o!==null)return o}return fa()},Yw=(t,e)=>{let r=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=e==="user"?t.userAvatar:t.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=v("img");o.src=n,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(o)}else r.textContent=n,r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},hx=(t,e)=>{let r=v("div","persona-text-xs persona-text-persona-muted"),n=new Date(t.createdAt);return e.format?r.textContent=e.format(n):r.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Zw=(t,e="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},Kp=(t,e,r)=>{var f,x,C,S,k,T;let n=(f=e.showCopy)!=null?f:!0,o=(x=e.showUpvote)!=null?x:!0,s=(C=e.showDownvote)!=null?C:!0;if(!n&&!o&&!s){let M=v("div");return M.style.display="none",M.id=`actions-${t.id}`,M.setAttribute("data-actions-for",t.id),M}let a=(S=e.visibility)!=null?S:"hover",i=(k=e.align)!=null?k:"right",d=(T=e.layout)!=null?T:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id);let u=(M,h,w)=>{let y=Er({icon:M,label:h,size:14,className:"persona-message-action-btn"});return y.setAttribute("data-action",w),y};return n&&m.appendChild(u("copy","Copy message","copy")),o&&m.appendChild(u("thumbs-up","Upvote","upvote")),s&&m.appendChild(u("thumbs-down","Downvote","downvote")),m},Fa=(t,e,r,n,o,s)=>{var X,Ue,K,Te,oe,xe,Me,Xe,ce,te,le,ut,Ce,he,rt,_e,me;let a=r!=null?r:{},i=(X=a.layout)!=null?X:"bubble",d=a.avatar,l=a.timestamp,p=(Ue=d==null?void 0:d.show)!=null?Ue:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,u=(Te=d==null?void 0:d.position)!=null?Te:"left",f=(oe=l==null?void 0:l.position)!=null?oe:"below",x=Zw(t.role,i),C=v("div",x.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.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 S=zw(t),k=(Me=(xe=t.content)==null?void 0:xe.trim())!=null?Me:"",M=S.length>0&&k===el,h=Ml((ce=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.features)==null?void 0:ce.streamAnimation),w=(ut=(le=(te=s==null?void 0:s.widgetConfig)==null?void 0:te.features)==null?void 0:le.streamAnimation)==null?void 0:ut.plugins,y=t.role==="assistant"&&h.type!=="none"?Us(h.type,w):null,E=t.role==="assistant"&&((Ce=y==null?void 0:y.isAnimating)==null?void 0:Ce.call(y,t))===!0,B=t.role==="assistant"&&y!==null&&(!!t.streaming||E);B&&(y!=null&&y.bubbleClass)&&C.classList.add(y.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),B&&y&&(y.containerClass&&P.classList.add(y.containerClass),P.style.setProperty("--persona-stream-step",`${h.speed}ms`),P.style.setProperty("--persona-stream-duration",`${h.duration}ms`));let R=B?kl((he=t.content)!=null?he:"",h.buffer,y,t,!!t.streaming):(rt=t.content)!=null?rt:"",O=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),V=O;B&&(y==null?void 0:y.wrap)==="char"?V=qs(O,"char",t.id,{skipTags:y.skipTags}):B&&(y==null?void 0:y.wrap)==="word"&&(V=qs(O,"word",t.id,{skipTags:y.skipTags}));let ne=null;if(M?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",P.appendChild(ne)):P.innerHTML=V,B&&(y!=null&&y.useCaret)&&!M&&k){let J=El(),ze=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),Z=ze[ze.length-1];if(Z!=null&&Z.parentNode)Z.parentNode.insertBefore(J,Z.nextSibling);else{let ge=P.lastElementChild;ge?ge.appendChild(J):P.appendChild(J)}}if(m&&f==="inline"&&t.createdAt){let J=hx(t,l);J.classList.add("persona-ml-2","persona-inline"),P.appendChild(J)}if(S.length>0){let J=Kw(S,!M&&!!k,()=>{M&&ne&&(ne.style.display="")});J?C.appendChild(J):M&&ne&&(ne.style.display="")}let be=Vw(t);if(be.length>0){let J=Xw(be);J&&C.appendChild(J)}let Ye=jw(t);if(Ye.length>0){let J=Jw(Ye);J&&C.appendChild(J)}let Ge=Gw(t);if(Ge.length>0){let J=Qw(Ge);J&&C.appendChild(J)}if(C.appendChild(P),m&&f==="below"&&t.createdAt){let J=hx(t,l);J.classList.add("persona-mt-1"),C.appendChild(J)}let ve=t.role==="assistant"?$w(t.stopReason,(me=(_e=s==null?void 0:s.widgetConfig)==null?void 0:_e.copy)==null?void 0:me.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let J=!!(R&&R.trim()),ze=h.placeholder==="skeleton",Z=ze&&h.buffer==="line"&&J;if(J)Z&&C.appendChild(zs());else if(ze)C.appendChild(zs());else{let ge=Gp("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ge&&C.appendChild(ge)}}if(ve&&t.stopReason&&!t.streaming&&(k||(P.style.display="none"),C.appendChild(Uw(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let J=Kp(t,n,o);C.appendChild(J)}if(!p||t.role==="system")return C;let Ke=v("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Ne=Yw(d,t.role);return u==="right"||u==="left"&&t.role==="user"?Ke.append(C,Ne):Ke.append(Ne,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ke},yx=(t,e,r,n,o,s)=>{let a=r!=null?r:{};return t.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:t,config:{},streaming:!!t.streaming}):t.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:t,config:{},streaming:!!t.streaming}):Fa(t,e,r,n,o,s)};var $a=new Set,ev=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),tv=(t,e)=>{var n,o;let r=(o=(n=t.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
74
|
+
`):""},bx=(t,e)=>{let r=$a.has(t),n=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",r?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ie(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none",s&&(s.style.display=r?"none":s.textContent||s.childNodes.length?"":"none")},Xp=(t,e)=>{var Ye,Ge,ve,Ee,Ke,Ne,X,Ue,K,Te,oe;let r=t.reasoning,n=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${t.id}`,n.setAttribute("data-message-id",t.id),!r)return n;let o=(Ge=(Ye=e==null?void 0:e.features)==null?void 0:Ye.reasoningDisplay)!=null?Ge:{},s=o.expandable!==!1,a=s&&$a.has(t.id),i=r.status!=="complete",d=tv(t,(ve=o.previewMaxLines)!=null?ve:3),l=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",f=(Ee=e==null?void 0:e.reasoning)!=null?Ee:{},x=String((Ke=r.startedAt)!=null?Ke:Date.now()),C=()=>{let xe=v("span","");return xe.setAttribute("data-tool-elapsed",x),xe.textContent=ji(r),xe},S=(Ne=f.renderCollapsedSummary)==null?void 0:Ne.call(f,{message:t,reasoning:r,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:ji(r),createElapsedElement:C});typeof S=="string"&&S.trim()?(m.textContent=S,p.appendChild(m)):S instanceof HTMLElement?p.appendChild(S):(m.textContent=u,p.appendChild(m));let k=v("span","persona-text-xs persona-text-persona-primary");k.textContent=Rh(r),p.appendChild(k);let T=(X=o.loadingAnimation)!=null?X:"none",M=f.activeTextTemplate,h=f.completeTextTemplate,w=i?M:h,y=S instanceof HTMLElement,E=(xe,Me,Xe)=>{let ce=Xe;for(let te of Me){let le=v("span","persona-tool-char");le.style.setProperty("--char-index",String(ce)),le.textContent=te===" "?"\xA0":te,xe.appendChild(le),ce++}return ce},B=(xe,Me)=>{m.textContent="";let Xe=Gi(xe,""),ce=0;for(let te of Xe){let le=te.styles.length>0?(()=>{let ut=v("span",te.styles.map(Ce=>`persona-tool-text-${Ce}`).join(" "));return m.appendChild(ut),ut})():m;if(te.isDuration&&i)le.appendChild(C());else{let ut=te.isDuration?ji(r):te.text;Me?ce=E(le,ut,ce):le.appendChild(document.createTextNode(ut))}}};if(!y&&w)if(k.style.display="none",m.style.display="",i&&T!=="none"){let xe=(Ue=f.loadingAnimationDuration)!=null?Ue:2e3;m.setAttribute("data-preserve-animation","true"),T==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),B(w,!1)):(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),B(w,!0))}else B(w,!1);else if(!y&&i&&T!=="none"){m.style.display="";let xe=(K=f.loadingAnimationDuration)!=null?K:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`);else{m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Me=m.textContent||u;m.textContent="",E(m,Me,0)}r.status==="complete"&&(m.style.display="none")}else y||(r.status==="complete"?m.style.display="none":m.style.display="");let P=null;if(s){P=v("div","persona-flex persona-items-center");let Me=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?P.appendChild(Me):P.textContent=a?"Hide":"Show";let Xe=v("div","persona-flex persona-items-center persona-ml-auto");Xe.append(P),l.append(p,Xe)}else l.append(p);let R=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let xe=(oe=(Te=e==null?void 0:e.reasoning)==null?void 0:Te.renderCollapsedPreview)==null?void 0:oe.call(Te,{message:t,reasoning:r,defaultPreview:d,isActive:i,config:e!=null?e:{}});ev(R,xe)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!s)return n.append(l,R),n;let O=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let V=r.chunks.join(""),ne=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(ne),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),P){P.innerHTML="";let Me=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?P.appendChild(Me):P.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),n.append(l,R,O),n};var Ua=new Set,rv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),nv=(t,e)=>{var s;let r=t.toolCall;if(!r)return"";let n=((s=r.chunks)!=null?s:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
|
|
75
|
+
`);let o=Ra(r.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
|
|
76
|
+
`):""},ov=(t,e)=>{var p,m,u,f,x;let r=t.toolCall,n=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(m=n==null?void 0:n.collapsedMode)!=null?m:"tool-call",s=nv(t,(u=n==null?void 0:n.previewMaxLines)!=null?u:3),a=r?Wh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Wd(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Wd(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},wx=(t,e,r)=>{var p;let n=Ua.has(t),o=(p=r==null?void 0:r.toolCall)!=null?p:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",n?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=o.toggleTextColor||o.headerTextColor||"currentColor",u=Ie(n?"chevron-up":"chevron-down",16,m,2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Jp=(t,e)=>{var V,ne,be,Ye,Ge,ve,Ee,Ke,Ne;let r=t.toolCall,n=(V=e==null?void 0:e.toolCall)!=null?V:{},o=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!r)return o;let s=(be=(ne=e==null?void 0:e.features)==null?void 0:ne.toolCallDisplay)!=null?be:{},a=s.expandable!==!1,i=a&&Ua.has(t.id),{summary:d,previewText:l,isActive:p}=ov(t,e),m=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let u=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let x=String((Ye=r.startedAt)!=null?Ye:Date.now()),C=()=>{let X=v("span","");return X.setAttribute("data-tool-elapsed",x),X.textContent=Is(r),X},S=(ve=n.renderCollapsedSummary)==null?void 0:ve.call(n,{message:t,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(Ge=s.collapsedMode)!=null?Ge:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Is(r),createElapsedElement:C});typeof S=="string"&&S.trim()?(f.textContent=S,u.appendChild(f)):S instanceof HTMLElement?u.appendChild(S):(f.textContent=d,u.appendChild(f));let k=(Ee=s.loadingAnimation)!=null?Ee:"none",T=n.activeTextTemplate,M=n.completeTextTemplate,h=p?T:M,w=S instanceof HTMLElement,y=(X,Ue,K)=>{let Te=K;for(let oe of Ue){let xe=v("span","persona-tool-char");xe.style.setProperty("--char-index",String(Te)),xe.textContent=oe===" "?"\xA0":oe,X.appendChild(xe),Te++}return Te},E=(X,Ue)=>{var xe;f.textContent="";let K=((xe=r.name)==null?void 0:xe.trim())||"tool",Te=Gi(X,K),oe=0;for(let Me of Te){let Xe=Me.styles.length>0?(()=>{let ce=v("span",Me.styles.map(te=>`persona-tool-text-${te}`).join(" "));return f.appendChild(ce),ce})():f;if(Me.isDuration&&p)Xe.appendChild(C());else{let ce=Me.isDuration?Is(r):Me.text;Ue?oe=y(Xe,ce,oe):Xe.appendChild(document.createTextNode(ce))}}};if(!w)if(p&&k!=="none"){let X=(Ke=n.loadingAnimationDuration)!=null?Ke:2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),h&&E(h,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),k==="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)),h)E(h,!0);else{let Ue=f.textContent||d;f.textContent="",y(f,Ue,0)}}else h&&E(h,!1);let B=null;if(a){B=v("div","persona-flex persona-items-center");let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?B.appendChild(Ue):B.textContent=i?"Hide":"Show";let K=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(B),m.append(u,K)}else m.append(u);let P=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(P.setAttribute("data-persona-collapsed-preview","tool"),P.style.display="none",P.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let X=(Ne=n.renderCollapsedPreview)==null?void 0:Ne.call(n,{message:t,toolCall:r,defaultPreview:l,isActive:p,config:e!=null?e:{}});rv(P,X)||(P.textContent=l),P.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(m,P),o;let R=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",n.contentBackgroundColor&&(R.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(R.style.color=n.contentTextColor),n.contentPaddingX&&(R.style.paddingLeft=n.contentPaddingX,R.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(R.style.paddingTop=n.contentPaddingY,R.style.paddingBottom=n.contentPaddingY),r.name){let X=v("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?X.style.color=n.contentTextColor:n.headerTextColor&&(X.style.color=n.headerTextColor),X.textContent=r.name,R.appendChild(X)}if(r.args!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Arguments";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ra(r.args),X.append(Ue,K),R.appendChild(X)}if(r.chunks&&r.chunks.length){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Activity";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=r.chunks.join(""),X.append(Ue,K),R.appendChild(X)}if(r.status==="complete"&&r.result!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Result";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ra(r.result),X.append(Ue,K),R.appendChild(X)}if(r.status==="complete"&&typeof r.duration=="number"){let X=v("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(X.style.color=n.contentTextColor),X.textContent=`Duration: ${r.duration}ms`,R.appendChild(X)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),B){B.innerHTML="";let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?B.appendChild(Ue):B.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",P.style.display=i?"none":P.textContent||P.childNodes.length?"":"none"})(),o.append(m,P,R),o};var Oo=ad(qi(),1);var Yp="ask_user_question",Qp=8,qa="data-persona-ask-sheet-for",av="Other",sv="Other\u2026",Cx="Type your own answer here",Ax="Send",iv="Next",lv="Back",dv="Submit all",cv="Skip",pv=3,Zp="data-ask-current-index",eu="data-ask-question-count",Sx="data-ask-answers",tu="data-ask-grouped",Tx="data-ask-layout",uv=t=>t.layout==="pills"?"pills":"rows",fv=t=>t.getAttribute(Tx)==="pills"?"pills":"rows",vx=!1,Mx=t=>t.replace(/["\\]/g,"\\$&"),ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Yp,Fl=t=>{var e,r;return(r=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?r:{}},xo=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let r=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:r};let n=e.chunks;if(!n||n.length===0)return{payload:null,complete:r};try{let o=n.join(""),s=(0,Oo.parse)(o,Oo.STR|Oo.OBJ|Oo.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},Ks=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Qp&&!vx&&(vx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Qp}.`)),e.slice(0,Qp)},mv=t=>{var e;return(e=Ks(t)[0])!=null?e:null},gv=(t,e)=>{var r;return(r=Ks(t)[e])!=null?r:null},kx=(t,e)=>{let r=e.styles;r&&(r.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Ex=(t,e,r)=>{if(t!=="rows")return null;let n=v("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");n.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},hv=(t,e,r,n)=>{let s=v("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",n?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),r==="rows"){let a=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let l=v("span","persona-ask-row-description");l.textContent=t.description,a.appendChild(l)}s.appendChild(a);let d=Ex(r,n,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},xv=t=>{let r=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},yv=(t,e,r,n)=>{var p,m,u;let s=v("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!r){for(let f=0;f<pv;f++)s.appendChild(xv(n));return s}if(d.forEach((f,x)=>{s.appendChild(hv(f,x,n,a))}),(t==null?void 0:t.allowFreeText)!==!1){let f=n==="rows"?av:sv;if(n==="rows"){let x=v("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=v("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=e.freeTextPlaceholder)!=null?p:Cx,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),C.appendChild(S),x.appendChild(C);let k=Ex(n,a,d.length);k&&x.appendChild(k),s.appendChild(x)}else{let x=v("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=(u=e.freeTextLabel)!=null?u:f,s.appendChild(x)}}return s},Lx=(t,e)=>{var s,a;let n=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:Cx,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),e!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:Ax,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},bv=t=>{var n;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let r=v("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=t.submitLabel)!=null?n:Ax,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,e.appendChild(r),e},wv=(t,e,r)=>{var l,p,m,u;let n=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:lv,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,n.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:cv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(m=r.submitAllLabel)!=null?m:dv:(u=r.nextLabel)!=null?u:iv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},ma=t=>{let e=t.getAttribute(Sx);if(!e)return{};try{let r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}},Px=(t,e)=>{t.setAttribute(Sx,JSON.stringify(e))},En=t=>{var r;let e=Number((r=t.getAttribute(Zp))!=null?r:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},vv=(t,e)=>{t.setAttribute(Zp,String(Math.max(0,Math.floor(e))))},za=t=>{var r;let e=Number((r=t.getAttribute(eu))!=null?r:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},No=t=>t.getAttribute(tu)==="true",Cv=(t,e)=>{var o;let r=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let n={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let d=r[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},Av=(t,e)=>{var n;let r=(n=t.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(e-1,Math.floor(r)))},$l=(t,e)=>{let{payload:r}=xo(e),n=Ks(r),o=ma(t),s={},a=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Ix=t=>{let e=ma(t),r=En(t),n=e[r],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!a.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Rx=t=>{if(!No(t))return;let e=ma(t),r=En(t),n=e[r],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},ru=(t,e,r)=>{let n=Fl(r),o=fv(t),{payload:s,complete:a}=xo(e),i=No(t),d=En(t),l=za(t),p=i?gv(s,d):mv(s),m=!!(p!=null&&p.multiSelect),u=t.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${l}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let T=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=T,x.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let T=yv(p,n,a,o);C.replaceWith(T)}if(o!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(Lx(n,o))}let S=t.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!S?t.appendChild(bv(n)):(!m||i)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let k=t.querySelector('[data-ask-nav-row="true"]');if(i){let T=wv(d,l,n);k?k.replaceWith(T):t.appendChild(T)}else k&&k.remove();Ix(t),Rx(t)},Sv=(t,e,r)=>{let n=Fl(e),o=uv(n),s=t.toolCall.id,a=Ks(r),i=Math.max(1,a.length),d=i>1,l=Cv(t,a),p=d?Av(t,i):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(qa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(eu,String(i)),m.setAttribute(Zp,String(p)),m.setAttribute(tu,d?"true":"false"),m.setAttribute(Tx,o),Px(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),kx(m,n);let u=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=v("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",u.appendChild(f);let x=v("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),m.appendChild(u);let S=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),o!=="rows"&&m.appendChild(Lx(n,o)),ru(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Tv=(t,e,r)=>{let{payload:n}=xo(e),o=Math.max(1,Ks(n).length);o>za(t)&&(t.setAttribute(eu,String(o)),o>1&&!No(t)&&t.setAttribute(tu,"true")),ru(t,e,r)},Wx=(t,e)=>{let r=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Fl(e);kx(r,n);let o=v("span","persona-ask-stub-label"),{complete:s}=xo(t);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},Va=(t,e,r)=>{if(!r||!ho(t)||Fl(e).enabled===!1)return;let o=t.toolCall.id;r.querySelectorAll(`[${qa}]`).forEach(l=>{l.getAttribute(qa)!==o&&l.remove()});let a=r.querySelector(`[${qa}="${Mx(o)}"]`);if(a){Tv(a,t,e);return}let{payload:i}=xo(t),d=Sv(t,e,i);r.appendChild(d)},_o=(t,e)=>{if(!t)return;let r=e?`[${qa}="${Mx(e)}"]`:`[${qa}]`;t.querySelectorAll(r).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},nu=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Fo=(t,e)=>{let r=ma(t),n=En(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete r[n]:r[n]=e,Px(t,r),Ix(t),Rx(t)},Ul=(t,e,r,n)=>{let o=za(t),s=Math.max(0,Math.min(o-1,n));vv(t,s),ru(t,e,r)};var ou=(t,e)=>{var C,S,k,T,M,h,w,y,E,B,P,R;let r=t.approval,n=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(C=n==null?void 0:n.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(S=n==null?void 0:n.borderColor)!=null?S:"var(--persona-approval-border, #fef08a)",!r)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=v("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(k=n==null?void 0:n.titleColor)!=null?k:"currentColor",p=Ie(d,20,l,2);p&&i.appendChild(p);let m=v("div","persona-flex-1 persona-min-w-0"),u=v("div","persona-flex persona-items-center persona-gap-2"),f=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(T=n==null?void 0:n.title)!=null?T:"Approval Required",u.appendChild(f),!o){let O=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",r.status),r.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):r.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):r.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),u.appendChild(O)}m.appendChild(u);let x=v("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,m.appendChild(x),r.parameters){let O=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Ra(r.parameters),m.appendChild(O)}if(o){let O=v("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let V=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=(M=n==null?void 0:n.approveButtonColor)!=null?M:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(h=n==null?void 0:n.approveButtonTextColor)!=null?h:"#ffffff",V.setAttribute("data-approval-action","approve");let ne=Ie("shield-check",14,(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",2);ne&&(ne.style.marginRight="4px",V.appendChild(ne));let be=document.createTextNode((y=n==null?void 0:n.approveLabel)!=null?y:"Approve");V.appendChild(be);let Ye=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Ye.type="button",Ye.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",Ye.style.color=(B=n==null?void 0:n.denyButtonTextColor)!=null?B:"var(--persona-feedback-error, #dc2626)",Ye.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ye.setAttribute("data-approval-action","deny");let Ge=Ie("shield-x",14,(P=n==null?void 0:n.denyButtonTextColor)!=null?P:"var(--persona-feedback-error, #dc2626)",2);Ge&&(Ge.style.marginRight="4px",Ye.appendChild(Ge));let ve=document.createTextNode((R=n==null?void 0:n.denyLabel)!=null?R:"Deny");Ye.appendChild(ve),O.append(V,Ye),m.appendChild(O)}return a.append(i,m),s.appendChild(a),s};var Bx=t=>{let e=[];return{buttons:e,render:(n,o,s,a,i)=>{if(t.innerHTML="",e.length=0,!n||!n.length||(a!=null?a:o?o.getMessages():[]).some(f=>f.role==="user"))return;let p=document.createDocumentFragment(),m=o?o.isStreaming():!1,u=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let x=v("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=f,x.disabled=m,i!=null&&i.fontFamily&&(x.style.fontFamily=u(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()||(s.value="",o.sendMessage(f))}),p.appendChild(x),e.push(x)}),t.appendChild(p)}}};var Xs=class{constructor(e=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=r}push(e){var r;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(r=this.store)==null||r.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let r=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let n of r)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=e.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let r=this.getAll();return e>=r.length?r:r.slice(r.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(e="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=r}open(){return new Promise((e,r)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}getAll(){return new Promise((e,r)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{r(a.error)}}catch(n){r(n)}})}getCount(){return new Promise((e,r)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}clear(){return new Promise((e,r)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,r)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}};var Mv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),kv=new Set(["step_start","execution_start"]),Ev=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Lv=new Set(["step_complete","agent_turn_complete"]),Pv=new Set(["flow_complete","agent_complete"]),Hx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ox=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ga=(t,e)=>{let r=t[e];return Ox(r)?r:void 0};function au(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ql(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Iv(t,e){return typeof e.type=="string"?e.type:t}function Rv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Wv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Dx(t){var n,o,s,a,i;let e=ga(t,"result"),r=[ga(t,"tokens"),ga(t,"totalTokens"),e?ga(e,"tokens"):void 0,ga(t,"usage"),e?ga(e,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=bn(d.output))!=null?n:bn(d.outputTokens))!=null?o:bn(d.completionTokens);if(l!==void 0)return l}return(i=(s=bn(t.outputTokens))!=null?s:bn(t.completionTokens))!=null?i:e?(a=bn(e.outputTokens))!=null?a:bn(e.completionTokens):void 0}function Bv(t){var r,n,o,s,a;let e=ga(t,"result");return(a=(o=(n=(r=bn(t.executionTime))!=null?r:bn(t.executionTimeMs))!=null?n:bn(t.execution_time))!=null?o:bn(t.duration))!=null?a:e?(s=bn(e.executionTime))!=null?s:bn(e.executionTimeMs):void 0}function Hv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(e=Hv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:ql(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,r){var s;if(!Ox(r)){Hx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=Iv(e,r),o=this.now();if(Mv.has(n)){this.startRun(o);return}if(kv.has(n)){this.run||this.startRun(o);return}if(Ev.has(n)){if(!Wv(n,r))return;let a=Rv(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+au(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ql(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Lv.has(n)){if(!this.run)return;let a=this.run,i=Dx(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+au(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:ql(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Pv.has(n)){if(!this.run)return;let a=this.run,i=Dx(r),d=i!=null?i:a.exactOutputTokens+au(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:ql(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Hx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,r,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Bv(r);return s!=null?s:n-e.startedAt}};function ja(t,e){e&&e.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Dv={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)"}},Ov={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Nv=["flowName","stepName","reasoningText","text","name","tool","toolName"],_v=100;function Fv(t,e){let r={...Dv,...e};if(r[t])return r[t];for(let n of Object.keys(r))if(n.endsWith("_")&&t.startsWith(n))return r[n];return Ov}function $v(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Uv(t){let e=new Date(t),r=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${r}:${n}:${o}.${s}`}function qv(t,e){try{let r=JSON.parse(t);if(typeof r!="object"||r===null)return null;for(let n of e){let o=n.split("."),s=r;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function zv(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(r=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),r()})}function Vv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function jv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Gv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Kv(t,e,r){let n,o;try{o=JSON.parse(t.payload),n=JSON.stringify(o,null,2)}catch{o=t.payload,n=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let i=s.renderEventStreamPayload({event:t,config:r,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function su(t,e,r,n,o,s,a,i){var u;let d=o.has(t.id),l=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ja(l,(u=n.classNames)==null?void 0:u.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(f)return l.appendChild(f),l}return l.appendChild(m()),l;function m(){var V,ne;let f=v("div",""),x=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",t.id);let C=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=Ie(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&C.appendChild(S);let k=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(V=n.timestampFormat)!=null?V:"relative";k.textContent=T==="relative"?$v(t.timestamp,r):Uv(t.timestamp);let M=null;n.showSequenceNumbers!==!1&&(M=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let h=Fv(t.type,n.badgeColors),w=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=h.bg,w.style.color=h.text,w.style.borderColor=h.text+"50",w.textContent=t.type;let y=(ne=n.descriptionFields)!=null?ne:Nv,E=qv(t.payload,y),B=null;E&&(B=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=E);let P=v("div","persona-flex-1 persona-min-w-0"),R=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=Ie("clipboard","12px","currentColor",1.5);return O&&R.appendChild(O),R.addEventListener("click",async be=>{be.stopPropagation(),await zv(Vv(t)),R.innerHTML="";let Ye=Ie("check","12px","currentColor",1.5);Ye&&R.appendChild(Ye),setTimeout(()=>{R.innerHTML="";let Ge=Ie("clipboard","12px","currentColor",1.5);Ge&&R.appendChild(Ge)},1500)}),x.appendChild(C),x.appendChild(k),M&&x.appendChild(M),x.appendChild(w),B&&x.appendChild(B),x.appendChild(P),x.appendChild(R),f.appendChild(x),d&&f.appendChild(Kv(t,a,i)),f}}function Nx(t){var x,C,S,k,T;let{buffer:e,getFullHistory:r,onClose:n,config:o,plugins:s=[],getThroughput:a}=t,i=(x=o==null?void 0:o.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",m=(T=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?T:{},u=s.find(M=>M.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let M=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=m.classNames,h=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ja(h,M==null?void 0:M.panel);let w=[],y="",E="",B=null,P=[],R={},O=0,V=Al(),ne=0,be=0,Ye=!1,Ge=null,ve=!1,Ee=0,Ke=new Set,Ne=new Map,X="",Ue="",K=null,Te,oe,xe,Me,Xe,ce=null,te=null,le=null;function ut(){let de=v("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ye=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");ja(ye,M==null?void 0:M.headerBar);let Rt=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Rt.textContent="Events",Te=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Te.textContent="0",a){te=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let dr=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");dr.textContent="Throughput",ce=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ce.textContent="-- tok/s",le=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let wr=te,Lr=le,Or=()=>{if(!Lr.textContent)return;let sn=wr.getBoundingClientRect(),fr=de.getBoundingClientRect();Lr.style.left=`${sn.left-fr.left}px`,Lr.style.top=`${sn.bottom-fr.top+4}px`,Lr.style.display="block"},xt=()=>{Lr.style.display="none"};te.addEventListener("mouseenter",Or),te.addEventListener("mouseleave",xt),te.appendChild(dr),te.appendChild(ce)}let ar=v("div","persona-flex-1");oe=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let kt=v("option","");kt.value="",kt.textContent="All events",oe.appendChild(kt),xe=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),xe.type="button",xe.title="Copy All";let Ot=Ie("clipboard-copy","12px","currentColor",1.5);Ot&&xe.appendChild(Ot);let Wt=v("span","persona-text-xs");Wt.textContent="Copy All",xe.appendChild(Wt),ye.appendChild(Rt),ye.appendChild(Te),te&&ye.appendChild(te),ye.appendChild(ar),ye.appendChild(oe),ye.appendChild(xe);let St=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ja(St,M==null?void 0:M.searchBar);let Et=Ie("search","14px","var(--persona-muted, #9ca3af)",1.5),sr=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Et&&sr.appendChild(Et),Me=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ja(Me,M==null?void 0:M.searchInput),Me.type="text",Me.placeholder="Search event payloads...",Xe=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Xe.type="button",Xe.style.display="none";let ft=Ie("x","12px","currentColor",2);return ft&&Xe.appendChild(ft),St.appendChild(sr),St.appendChild(Me),St.appendChild(Xe),de.appendChild(ye),de.appendChild(St),le&&de.appendChild(le),de}let Ce,he=s.find(de=>de.renderEventStreamToolbar);if(he!=null&&he.renderEventStreamToolbar&&o){let de=he.renderEventStreamToolbar({config:o,defaultRenderer:()=>ut(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ye=>{y=ye,pe(),_()},onSearchChange:ye=>{E=ye,pe(),_()}});Ce=de!=null?de:ut()}else Ce=ut();let rt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");rt.style.display="none";function _e(){if(!a||!ce||!te)return;let de=a();ce.textContent=jv(de);let ye=Gv(de);le&&(le.textContent=ye,ye||(le.style.display="none")),ye?te.setAttribute("aria-label",ye):te.removeAttribute("aria-label")}let me=v("div","persona-flex-1 persona-min-h-0 persona-relative"),J=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ze=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ja(ze,M==null?void 0:M.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Z=Ie(l,"14px","currentColor",2);Z&&ze.appendChild(Z);let ge=v("span","");ge.textContent=p,ze.appendChild(ge);let z=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");z.style.display="none",me.appendChild(J),me.appendChild(z),me.appendChild(ze),h.setAttribute("tabindex","0"),h.appendChild(Ce),h.appendChild(rt),h.appendChild(me);function Re(){let de=e.getAll(),ye={};for(let Wt of de)ye[Wt.type]=(ye[Wt.type]||0)+1;let Rt=Object.keys(ye).sort(),ar=Rt.length!==P.length||!Rt.every((Wt,St)=>Wt===P[St]),kt=!ar&&Rt.some(Wt=>ye[Wt]!==R[Wt]),mr=de.length!==Object.values(R).reduce((Wt,St)=>Wt+St,0);if(!ar&&!kt&&!mr||(P=Rt,R=ye,!oe))return;let Ot=oe.value;if(oe.options[0].textContent="All events",ar){for(;oe.options.length>1;)oe.remove(1);for(let Wt of Rt){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${ye[Wt]||0})`,oe.appendChild(St)}Ot&&Rt.includes(Ot)?oe.value=Ot:Ot&&(oe.value="",y="")}else for(let Wt=1;Wt<oe.options.length;Wt++){let St=oe.options[Wt];St.textContent=`${St.value} (${ye[St.value]||0})`}}function Ae(){let de=e.getAll();if(y&&(de=de.filter(ye=>ye.type===y)),E){let ye=E.toLowerCase();de=de.filter(Rt=>Rt.type.toLowerCase().includes(ye)||Rt.payload.toLowerCase().includes(ye))}return de}function fe(){return y!==""||E!==""}function pe(){O=0,ne=0,V.resume(),ze.style.display="none"}function Be(de){Ke.has(de)?Ke.delete(de):Ke.add(de),K=de;let ye=J.scrollTop,Rt=V.isFollowing();ve=!0,V.pause(),_(),J.scrollTop=ye,Rt&&V.resume(),ve=!1}function Q(){return _s(J,50)}function _(){be=Date.now(),Ye=!1,_e(),Re();let de=e.getEvictedCount();de>0?(rt.textContent=`${de.toLocaleString()} older events truncated`,rt.style.display=""):rt.style.display="none",w=Ae();let ye=w.length,Rt=e.getSize()>0;Te&&(Te.textContent=String(e.getSize())),ye===0&&Rt&&fe()?(z.textContent=E?`No events matching '${E}'`:"No events matching filter",z.style.display="",J.style.display="none"):(z.style.display="none",J.style.display=""),xe&&(xe.title=fe()?`Copy Filtered (${ye})`:"Copy All"),d&&!V.isFollowing()&&ye>O&&(ne+=ye-O,ge.textContent=p?`${p}${ne>0?` (${ne})`:""}`:"",ze.style.display=""),O=ye;let ar=e.getAll(),kt=ar.length>0?ar[0].timestamp:0,mr=new Set(w.map(St=>St.id));for(let St of Ke)mr.has(St)||Ke.delete(St);let Ot=y!==X||E!==Ue,Wt=Ne.size===0&&w.length>0;if(Ot||Wt||w.length===0){J.innerHTML="",Ne.clear();let St=document.createDocumentFragment();for(let Et=0;Et<w.length;Et++){let sr=su(w[Et],Et,kt,m,Ke,Be,s,o);Ne.set(w[Et].id,sr),St.appendChild(sr)}J.appendChild(St),X=y,Ue=E,K=null}else{if(K!==null){let Et=Ne.get(K);if(Et&&Et.parentNode===J){let sr=w.findIndex(ft=>ft.id===K);if(sr>=0){let ft=su(w[sr],sr,kt,m,Ke,Be,s,o);J.insertBefore(ft,Et),Et.remove(),Ne.set(K,ft)}}K=null}let St=new Set(w.map(Et=>Et.id));for(let[Et,sr]of Ne)St.has(Et)||(sr.remove(),Ne.delete(Et));for(let Et=0;Et<w.length;Et++){let sr=w[Et];if(!Ne.has(sr.id)){let ft=su(sr,Et,kt,m,Ke,Be,s,o);Ne.set(sr.id,ft),J.appendChild(ft)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function ke(){if(Date.now()-be>=_v){Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),_();return}Ye||(Ye=!0,Ge=requestAnimationFrame(()=>{Ge=null,_()}))}let He=(de,ye)=>{if(!xe)return;xe.innerHTML="";let Rt=Ie(de,"12px","currentColor",1.5);Rt&&xe.appendChild(Rt);let ar=v("span","persona-text-xs");ar.textContent="Copy All",xe.appendChild(ar),setTimeout(()=>{xe.innerHTML="";let kt=Ie("clipboard-copy","12px","currentColor",1.5);kt&&xe.appendChild(kt);let mr=v("span","persona-text-xs");mr.textContent="Copy All",xe.appendChild(mr),xe.disabled=!1},ye)},Ve=async()=>{if(xe){xe.disabled=!0;try{let de;fe()?de=w:r?(de=await r(),de.length===0&&(de=e.getAll())):de=e.getAll();let ye=de.map(Rt=>{try{return JSON.parse(Rt.payload)}catch{return Rt.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),He("check",1500)}catch{He("x",1500)}}},Je=()=>{oe&&(y=oe.value,pe(),_())},gt=()=>{!Me||!Xe||(Xe.style.display=Me.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{E=Me.value,pe(),_()},150))},at=()=>{!Me||!Xe||(Me.value="",E="",Xe.style.display="none",B&&clearTimeout(B),pe(),_())},Mt=()=>{if(ve)return;let de=J.scrollTop,{action:ye,nextLastScrollTop:Rt}=Sl({following:V.isFollowing(),currentScrollTop:de,lastScrollTop:Ee,nearBottom:Q(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ee=Rt,ye==="resume"?(V.resume(),ne=0,ze.style.display="none"):ye==="pause"&&(V.pause(),d&&(ge.textContent=p,ze.style.display=""))},Xt=de=>{let ye=Tl({following:V.isFollowing(),deltaY:de.deltaY,nearBottom:Q(),resumeWhenNearBottom:!0});ye==="pause"?(V.pause(),d&&(ge.textContent=p,ze.style.display="")):ye==="resume"&&(V.resume(),ne=0,ze.style.display="none")},G=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),ne=0,ze.style.display="none")},Jt=de=>{let ye=de.target;if(!ye||ye.closest("button"))return;let Rt=ye.closest("[data-event-id]");if(!Rt)return;let ar=Rt.getAttribute("data-event-id");ar&&Be(ar)},st=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),Me==null||Me.focus(),Me==null||Me.select();return}de.key==="Escape"&&(Me&&document.activeElement===Me?(at(),Me.blur(),h.focus()):n&&n())};xe&&xe.addEventListener("click",Ve),oe&&oe.addEventListener("change",Je),Me&&Me.addEventListener("input",gt),Xe&&Xe.addEventListener("click",at),J.addEventListener("scroll",Mt),J.addEventListener("wheel",Xt,{passive:!0}),J.addEventListener("click",Jt),ze.addEventListener("click",G),h.addEventListener("keydown",st);function _t(){B&&clearTimeout(B),Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),Ye=!1,Ne.clear(),xe&&xe.removeEventListener("click",Ve),oe&&oe.removeEventListener("change",Je),Me&&Me.removeEventListener("input",gt),Xe&&Xe.removeEventListener("click",at),J.removeEventListener("scroll",Mt),J.removeEventListener("wheel",Xt),J.removeEventListener("click",Jt),ze.removeEventListener("click",G),h.removeEventListener("keydown",st)}return{element:h,update:ke,destroy:_t}}}function _x(t,e){let r=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",n=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(u);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(l.append(p,m),i.append(d,l),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",n),i.append(u)}return i}var Fx=(t,e)=>{var n,o,s;let r=(s=(o=(n=e==null?void 0:e.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(r){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=r({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:e.config,defaultRenderer:()=>_x(t,e)});if(p)return p}return _x(t,e)};var iu=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,n])=>{this.register(r,n)})}},yo=new iu;yo.register("PersonaArtifactCard",Fx);function Xv(t){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=v("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=t.component?`Component: ${t.component}`:"Component";let n=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(r),e.appendChild(n),e}function $x(t,e){var oe,xe,Me,Xe;let r=(xe=(oe=t.features)==null?void 0:oe.artifacts)==null?void 0:xe.layout,o=((Me=r==null?void 0:r.toolbarPreset)!=null?Me:"default")==="document",s=(Xe=r==null?void 0:r.panePadding)==null?void 0:Xe.trim(),a=t.markdown?na(t.markdown):null,i=Ea(t.sanitize),d=ce=>{let te=a?a(ce):oa(ce);return i?i(te):te},l=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let m=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),o&&m.classList.add("persona-artifact-pane-document");let u=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let f=v("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let x=v("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 ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let C="rendered",S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),k=o?Er({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Er({icon:"eye",label:"Rendered view"}),T=o?Er({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Er({icon:"code-2",label:"Source"}),M=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),h=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,y=r==null?void 0:r.documentToolbarCopyMenuItems,E=!!(w&&y&&y.length>0),B=null,P,R=null,O=null;if(o&&(h||w)&&!E){if(P=h?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ce=Ie("chevron-down",14,"currentColor",2);ce&&P.appendChild(ce)}}else o&&E?(B=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),P=h?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Er({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),B.append(P,R)):o?P=Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):P=Er({icon:"copy",label:"Copy"});let V=o?Er({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Er({icon:"refresh-cw",label:"Refresh"}),ne=o?Er({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Er({icon:"x",label:"Close"}),be=()=>{var Ce,he,rt;let ce=(Ce=Ne.find(_e=>_e.id===X))!=null?Ce:Ne[Ne.length-1],te=(he=ce==null?void 0:ce.id)!=null?he:null,le=(ce==null?void 0:ce.artifactType)==="markdown"&&(rt=ce.markdown)!=null?rt:"",ut=ce?JSON.stringify({component:ce.component,props:ce.props},null,2):"";return{markdown:le,jsonPayload:ut,id:te}},Ye=async()=>{var Ce;let{markdown:ce,jsonPayload:te}=be(),le=(Ce=Ne.find(he=>he.id===X))!=null?Ce:Ne[Ne.length-1],ut=(le==null?void 0:le.artifactType)==="markdown"?ce:le?te:"";try{await navigator.clipboard.writeText(ut)}catch{}};if(P.addEventListener("click",async()=>{let ce=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ce&&E){let{markdown:te,jsonPayload:le,id:ut}=be();try{await ce({actionId:"primary",artifactId:ut,markdown:te,jsonPayload:le})}catch{}return}await Ye()}),R&&(y!=null&&y.length)){let ce=()=>{var le;return(le=m.closest("[data-persona-root]"))!=null?le:document.body},te=()=>{O=Do({items:y.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:ut,jsonPayload:Ce,id:he}=be(),rt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{rt?await rt({actionId:le,artifactId:he,markdown:ut,jsonPayload:Ce}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(ut):le==="json"||le==="source"?await navigator.clipboard.writeText(Ce):await navigator.clipboard.writeText(ut||Ce)}catch{}},anchor:B!=null?B:R,position:"bottom-right",portal:ce()})};m.isConnected?te():requestAnimationFrame(te),R.addEventListener("click",le=>{le.stopPropagation(),O==null||O.toggle()})}V.addEventListener("click",async()=>{var ce;try{await((ce=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ce.call(r))}catch{}K()}),ne.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let Ge=()=>{o&&(k.setAttribute("aria-pressed",C==="rendered"?"true":"false"),T.setAttribute("aria-pressed",C==="source"?"true":"false"))};k.addEventListener("click",()=>{C="rendered",Ge(),K()}),T.addEventListener("click",()=>{C="source",Ge(),K()});let ve=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),S.append(k,T),B?M.append(B,V,ne):M.append(P,V,ne),u.append(S,ve,M),Ge()):(u.appendChild(f),u.appendChild(x)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Ee=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Ke=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ee.style.paddingLeft=s,Ee.style.paddingRight=s,Ke.style.padding=s),m.appendChild(u),m.appendChild(Ee),m.appendChild(Ke);let Ne=[],X=null,Ue=!1,K=()=>{var ut,Ce,he,rt;let ce=o&&Ne.length<=1;Ee.classList.toggle("persona-hidden",ce),Ee.replaceChildren();for(let _e of Ne){let me=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");me.type="button",me.textContent=_e.title||_e.id.slice(0,8),_e.id===X&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>e.onSelect(_e.id)),Ee.appendChild(me)}Ke.replaceChildren();let te=X&&Ne.find(_e=>_e.id===X)||Ne[Ne.length-1];if(!te)return;if(o){let _e=te.artifactType==="markdown"?"MD":(ut=te.component)!=null?ut:"Component",J=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${J} \xB7 ${_e}`}else f.textContent="Artifacts";if(te.artifactType==="markdown"){if(o&&C==="source"){let me=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(Ce=te.markdown)!=null?Ce:"",Ke.appendChild(me);return}let _e=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");_e.innerHTML=d((he=te.markdown)!=null?he:""),Ke.appendChild(_e);return}let le=te.component?yo.get(te.component):void 0;if(le){let me={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let J=le((rt=te.props)!=null?rt:{},me);if(J){Ke.appendChild(J);return}}catch{}}Ke.appendChild(Xv(te))},Te=()=>{var te;let ce=Ne.length>0;if(m.classList.toggle("persona-hidden",!ce),l){let le=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ce=((te=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ce&&Ce&&Ue?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(ce){var te,le,ut;Ne=ce.artifacts,X=(ut=(le=ce.selectedId)!=null?le:(te=ce.artifacts[ce.artifacts.length-1])==null?void 0:te.id)!=null?ut:null,Ne.length>0&&(Ue=!0),K(),Te()},setMobileOpen(ce){Ue=ce,!ce&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Te()}}}function Ln(t){var e,r;return((r=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:r.enabled)===!0}function Ux(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Ln(e))return;let r=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,n=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),o=(d=r==null?void 0:r.paneBorderLeft)==null?void 0:d.trim();n?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",n)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function Jv(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function zl(t,e){var d,l,p,m,u,f,x,C,S,k;if(!Ln(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Jv(t),Ux(t,e);return}let r=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;t.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(m=r==null?void 0:r.paneWidth)!=null?m:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=r==null?void 0:r.paneBackground)==null?void 0:f.trim();n?t.style.setProperty("--persona-artifact-pane-bg",n):t.style.removeProperty("--persona-artifact-pane-bg");let o=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(k=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:k.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ux(t,e)}var qx=["panel","seamless"];function Vl(t,e){var i,d,l,p,m,u;for(let f of qx)t.classList.remove(`persona-artifact-appearance-${f}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!Ln(e))return;let r=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",o=qx.includes(n)?n:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=r==null?void 0:r.paneShadow)==null?void 0:m.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(r==null?void 0:r.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let f=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;f&&t.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function zx(t,e){var r,n,o;return!e||!Ln(t)?!1:((o=(n=(r=t.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Qv(t,e){if(!(t!=null&&t.trim()))return e;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return r?Math.max(0,Number(r[1])):e}function Yv(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Zv(t,e,r){return r<e?e:Math.min(r,Math.max(e,t))}function eC(t,e,r,n){let o=t-n-2*e-r;return Math.max(0,o)}function Vx(t,e){var a;let n=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(n);return s?Number(s[1]):8}function jx(t,e,r,n,o,s){let a=Qv(o,200),i=eC(e,r,n,200);i=Math.max(a,i);let d=Yv(s);return d!==null&&(i=Math.min(i,d)),Zv(t,a,i)}var Gx={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"}},lu=(t,e,r,n)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,C,S;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(C=Gx[a])!=null?C:Gx.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),l=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let k=v("p","persona-text-sm persona-text-persona-muted");k.textContent=i.description,d.appendChild(k)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(k=>{var y,E;let T=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${k.name}`;let M=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=k.label,T.appendChild(M);let h=(y=k.type)!=null?y:"text",w;h==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=h),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=`${e.id}-${a}-${k.name}`,w.name=k.name,w.placeholder=(E=k.placeholder)!=null?E:"",k.required&&(w.required=!0),T.appendChild(w),p.appendChild(T)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(S=i.submitLabel)!=null?S:"Submit",m.appendChild(u),m.appendChild(f),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async k=>{var w,y;k.preventDefault();let T=(w=r.formEndpoint)!=null?w:"/form",M=new FormData(p),h={};M.forEach((E,B)=>{h[B]=E}),h.type=a,f.disabled=!0,u.textContent="Submitting\u2026";try{let E=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let B=await E.json();u.textContent=(y=B.message)!=null?y:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await n.sendMessage(String(B.nextPrompt))}catch(E){u.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var du=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var n;let r=this.plugins.get(e);r&&((n=r.onUnregister)==null||n.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var n,o;return((n=r.priority)!=null?n:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let n=new Set(e.map(s=>s.id));return[...r.filter(s=>!n.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},Ys=new du;var Kx=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var tC=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},rC=t=>{let e=t.trim(),r=e.indexOf("{");if(r===-1)return null;let n=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(n+=1),s==="}"&&(n-=1,n===0))return e.slice(r,o+1)}return null},Zs=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=tC(t),r=rC(e);if(!r)return null;let n=JSON.parse(r);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...s}=n;return{type:String(o),payload:s,raw:n}}catch{return null}},cu=t=>typeof t=="string"?t:t==null?"":String(t),ha={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:cu(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,n=cu(r.element);if(n&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(n);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:cu(r.text)}}},Xx=t=>Array.isArray(t)?t.map(e=>String(e)):[],ei=t=>{let e=new Set(Xx(t.getSessionMetadata().processedActionMessageIds)),r=()=>{e=new Set(Xx(t.getSessionMetadata().processedActionMessageIds))},n=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),n();let d={action:i,message:s.message};t.emit("action:detected",d);for(let l of t.handlers)if(l)try{let p=()=>{t.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let u=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:u,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var nC=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},oC=t=>t.map(e=>({...e,streaming:!1})),aC=t=>t.map(e=>({...e,status:"complete"})),jl=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?nC(r.getItem(t)):null},save:r=>{let n=e();if(n)try{let o={...r,messages:r.messages?oC(r.messages):void 0,artifacts:r.artifacts?aC(r.artifacts):void 0};n.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(t)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Ga=ad(qi(),1);function sC(t){if(!t||typeof t!="object"||!("component"in t))return!1;let e=t.component;return typeof e=="string"&&e.length>0}function iC(t,e){if(!sC(t))return null;let r=t.props&&typeof t.props=="object"&&t.props!==null?t.props:{};return{component:t.component,props:r,raw:e}}function Gl(){let t=null,e=0;return{getExtractedDirective:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t;try{let o=(0,Ga.parse)(r,Ga.STR|Ga.OBJ),s=iC(o,r);s&&(t=s)}catch{}return e=r.length,t},reset:()=>{t=null,e=0}}}function Jx(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function Kl(t,e){let{config:r,message:n,onPropsUpdate:o}=e,s=yo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:r,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Qx(){let t=Gl();return{processChunk:e=>t.processChunk(e),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function Yx(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Xl(t){let e=Yx(t);if(!e)return!1;try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Jl(t){let e=Yx(t);if(!e)return null;try{let r=JSON.parse(e);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let n=r;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e}}}catch{}return null}var lC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ql(t){let{onSubmit:e,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=lC}=t,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,u=document.createElement("div");u.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let 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),u.appendChild(f);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let y=1;y<=5;y++){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",`${y} star${y>1?"s":""}: ${l[y-1]}`),E.title=l[y-1],E.dataset.rating=String(y),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
|
-
`,T.addEventListener("click",()=>{m=x,M.forEach((W,R)=>{let B=R<x;W.classList.toggle("selected",B),W.setAttribute("aria-checked",R===x-1?"true":"false")})}),M.push(T),S.appendChild(T)}u.appendChild(S);let k=null;if(d){let x=document.createElement("div");x.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),x.appendChild(k),u.appendChild(x)}let E=document.createElement("div");E.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(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=a,w.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let x=(k==null?void 0:k.value.trim())||void 0;await e(m,x),p.remove()}catch(x){w.disabled=!1,w.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),E.appendChild(h),E.appendChild(w),u.appendChild(E),p.appendChild(u),p}function Ql(t){let{onSubmit:e,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,y.appendChild(A);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,y.appendChild(S),f.appendChild(y);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=l;let h=document.createElement("span");h.className="persona-feedback-label-high",h.textContent=p,k.appendChild(E),k.appendChild(h);let w=document.createElement("div");w.className="persona-feedback-numbers";let x=[];for(let _=0;_<=10;_++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${_} out of 10`),V.textContent=String(_),V.dataset.rating=String(_),_<=6?V.classList.add("persona-feedback-detractor"):_<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{u=_,x.forEach((oe,be)=>{oe.classList.toggle("selected",be===_),oe.setAttribute("aria-checked",be===_?"true":"false")})}),x.push(V),w.appendChild(V)}M.appendChild(k),M.appendChild(w),f.appendChild(M);let T=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),_.appendChild(T),f.appendChild(_)}let W=document.createElement("div");W.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=i,R.addEventListener("click",()=>{r==null||r(),m.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let _=(T==null?void 0:T.value.trim())||void 0;await e(u,_),m.remove()}catch(_){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),W.appendChild(R),W.appendChild(B),f.appendChild(W),m.appendChild(f),m}var Ga="persona-chat-history",iC=30*1e3,lC={"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 dC(t){var n,o,s;if(!t)return[];let e=[],r=Array.from((n=t.items)!=null?n:[]);for(let a of r){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=lC[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function Yl(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function cC(t){var e,r,n,o,s,a,i,d,l;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(r=t.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(n=t.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=t.clearOnChatClear)!=null?l:!0}:null}function pC(t){try{let e=t==="local"?localStorage:sessionStorage,r="__persist_test__";return e.setItem(r,"1"),e.removeItem(r),e}catch{return null}}var cu=t=>!t||typeof t!="object"?{}:{...t},Qx=t=>t.map(e=>({...e,streaming:!1})),Yx=(t,e,r)=>{let n=t!=null&&t.markdown?ra(t.markdown):null,o=Ma(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&r&&r())}let d;return t!=null&&t.postprocessMessage?d=t.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):n?d=n(a):d=na(a),o?o(d):d}};function Zx(t){var i,d,l,p;let e=v("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let r=(i=t==null?void 0:t.iconName)!=null?i:"upload",n=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(l=t==null?void 0:t.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=t==null?void 0:t.iconStrokeWidth)!=null?p:.5,a=Ie(r,n,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let m=v("span","persona-drop-overlay-label");m.textContent=t.label,e.appendChild(m)}return e}var Zl=(t,e,r)=>{var Wu,Bu,Hu,Du,Ou,_u,Nu,Fu,$u,Uu,qu,zu,Vu,ju,Gu,Ku,Xu,Ju,Qu,Yu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,wf,vf,Cf,Af,Sf,Tf,kf,Mf;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let n=hl(e),o=Qs.getForInstance(n.plugins);n.components&&yo.registerAll(n.components);let s=jx(),i=n.persistState===!1?null:(Wu=n.storageAdapter)!=null?Wu:Vl(),d={},l=null,p=!1,m=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:C}=g;return C&&(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 m(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=m(g);b.metadata&&(d=cu(b.metadata)),(Bu=b.messages)!=null&&Bu.length&&(n={...n,initialMessages:b.messages}),(Hu=b.artifacts)!=null&&Hu.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Du=b.selectedArtifactId)!=null?Du:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=m({messages:[],metadata:{}});(Ou=c.messages)!=null&&Ou.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let u=()=>d,f=c=>{var b;d=(b=c({...d}))!=null?b:{},xa()},y=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ys],A=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ga.message,ga.messageAndClick],S=Zs({parsers:y,handlers:A,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let M=(Nu=(_u=n.launcher)==null?void 0:_u.enabled)!=null?Nu:!0,k=($u=(Fu=n.launcher)==null?void 0:Fu.autoExpand)!=null?$u:!1,E=(Uu=n.autoFocusInput)!=null?Uu:!1,h=k,w=M,x=(zu=(qu=n.layout)==null?void 0:qu.header)==null?void 0:zu.layout,T=!1,W=()=>Bo(n),R=()=>M||W(),B=W()?!1:M?k:!0,_=!1,V=null,oe=()=>{_=!0,V&&clearTimeout(V),V=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},be=Yx(n,S,oe),Qe=(ju=(Vu=n.features)==null?void 0:Vu.showReasoning)!=null?ju:!0,je=(Ku=(Gu=n.features)==null?void 0:Gu.showToolCalls)!=null?Ku:!0,ve=(Ju=(Xu=n.features)==null?void 0:Xu.showEventStreamToggle)!=null?Ju:!1,Ee=(Yu=(Qu=n.features)==null?void 0:Qu.scrollToBottom)!=null?Yu:{},_e=`${(ef=typeof n.persistState=="object"?(Zu=n.persistState)==null?void 0:Zu.keyPrefix:void 0)!=null?ef:"persona-"}event-stream`,X=ve?new Xs(_e):null,Ue=(nf=(rf=(tf=n.features)==null?void 0:tf.eventStream)==null?void 0:rf.maxEvents)!=null?nf:2e3,K=ve?new Ks(Ue,X):null,Te=ve?new Js:null,ae=null,xe=!1,ke=null,Ke=0;X==null||X.open().then(()=>K==null?void 0:K.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ce={onCopy:c=>{var g,b;s.emit("message:copy",c),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(c.id,"copy").catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(b=(g=n.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;s.emit("message:feedback",c),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(c.messageId,c.type).catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(b=(g=n.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},re=(of=n.statusIndicator)!=null?of:{},le=c=>{var g,b,C,D;return c==="idle"?(g=re.idleText)!=null?g:Ur.idle:c==="connecting"?(b=re.connectingText)!=null?b:Ur.connecting:c==="connected"?(C=re.connectedText)!=null?C:Ur.connected:c==="error"?(D=re.errorText)!=null?D:Ur.error:Ur[c]};function ut(c,g,b,C){if(C==="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:Ce,panel:he,pillRoot:tt}=ux(n),Ne=fx(n,R()),{container:me,body:J,messagesWrapper:ze,suggestions:Z,textarea:ge,sendButton:z,sendButtonWrapper:Re,composerForm:Ae,statusText:fe,introTitle:pe,introSubtitle:Be,closeButton:Q,iconHolder:N,headerTitle:Me,headerSubtitle:He,header:Ve,footer:Xe,actionsRow:gt,leftActions:ot,rightActions:kt}=Ne,Xt=Ne.setSendButtonMode,G=Ne.micButton,Jt=Ne.micButtonWrapper,at=Ne.attachmentButton,Nt=Ne.attachmentButtonWrapper,de=Ne.attachmentInput,ye=Ne.attachmentPreviewsContainer;me.classList.add("persona-relative"),J.classList.add("persona-relative");let Rt=12,ar=()=>{var c;return(c=Ee.label)!=null?c:""},Mt=()=>{var c;return(c=Ee.iconName)!=null?c:"arrow-down"},mr=()=>Ee.enabled!==!1,Ot=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let Wt=v("span","persona-flex persona-items-center"),St=v("span","");Ot.append(Wt,St),me.appendChild(Ot);let Et=()=>{let g=Xe.style.display==="none"?0:Xe.offsetHeight;Ot.style.bottom=`${g+Rt}px`};Et();let sr=()=>{let c=!!ar();Ot.setAttribute("aria-label",ar()||"Jump to latest"),Ot.title=ar(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Wt.innerHTML="";let g=Ie(Mt(),"14px","currentColor",2);g?(Wt.appendChild(g),Wt.style.display=""):Wt.style.display="none",St.textContent=ar(),St.style.display=c?"":"none"};sr();let ft=null,dr=null,wr=o.find(c=>c.renderHeader);if(wr!=null&&wr.renderHeader){let c=wr.renderHeader({config:n,defaultRenderer:()=>{let g=go({config:n,showClose:R()});return pa(me,g,n),g.header},onClose:()=>Kt(!1,"user")});if(c){let g=me.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ve=c)}}let Lr=()=>{var g,b,C,D;if(!K)return;if(xe=!0,!ae&&K&&(ae=Dx({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Or(),config:n,plugins:o,getThroughput:()=>{var $;return($=Te==null?void 0:Te.getMetric())!=null?$:{status:"idle"}}})),ae&&(J.style.display="none",(g=Xe.parentNode)==null||g.insertBefore(ae.element,Xe),ae.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${en.actionIconColor}`;let $=(D=(C=(b=n.features)==null?void 0:b.eventStream)==null?void 0:C.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!xe)return;let $=Date.now();$-Ke>=200&&(ae==null||ae.update(),Ke=$),ke=requestAnimationFrame(c)};Ke=0,ke=requestAnimationFrame(c),oo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Or=()=>{var c,g,b;if(xe){if(xe=!1,ae&&ae.element.remove(),J.style.display="",xt){xt.style.boxShadow="";let C=(b=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;C&&C.split(/\s+/).forEach(D=>D&&xt.classList.remove(D))}ke!==null&&(cancelAnimationFrame(ke),ke=null),oo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(ve){let c=(sf=(af=n.features)==null?void 0:af.eventStream)==null?void 0:sf.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=v("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let b=Ie("activity","18px","currentColor",1.5);b&&xt.appendChild(b);let C=Ne.clearChatButtonWrapper,D=Ne.closeButtonWrapper,$=C||D;$&&$.parentNode===Ve?Ve.insertBefore(xt,$):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}let sn=c=>{var C,D,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(b,U):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=v("input");U.type="file",U.accept=((C=g.allowedTypes)!=null?C:mo).join(","),U.multiple=((D=g.maxFiles)!=null?D:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},fr=o.find(c=>c.renderComposer);if(fr!=null&&fr.renderComposer){let c=n.composer,g=fr.renderComposer({config:n,defaultRenderer:()=>_a({config:n}).footer,onSubmit:b=>{var U;if(!I||I.isStreaming())return;let C=b.trim(),D=(U=ft==null?void 0:ft.hasAttachments())!=null?U:!1;if(!C&&!D)return;os();let $;D&&($=[],$.push(...ft.getContentParts()),C&&$.push(Rs(C))),I.sendMessage(C,{contentParts:$}),D&&ft.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{de==null||de.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((lf=n.voiceRecognition)==null?void 0:lf.enabled)===!0?()=>{dr==null||dr()}:void 0});g&&(Xe.replaceWith(g),Xe=g)}let Un=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),C=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ae=g),b&&(ge=b),C&&(z=C),D&&(G=D,Jt=D.parentElement),$&&(fe=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Z=U);let j=c.querySelector(".persona-attachment-button");j&&(at=j,Nt=j.parentElement),de=c.querySelector('input[type="file"]'),ye=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(gt=F)};sn(Xe),Un(Xe);let Rr=(ff=(df=n.layout)==null?void 0:df.contentMaxWidth)!=null?ff:W()?(uf=(pf=(cf=n.launcher)==null?void 0:cf.composerBar)==null?void 0:pf.contentMaxWidth)!=null?uf:"720px":void 0;if(Rr&&(ze.style.maxWidth=Rr,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%"),Rr&&Ae&&!W()&&(Ae.style.maxWidth=Rr,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Rr&&Z&&!W()&&(Z.style.maxWidth=Rr,Z.style.marginLeft="auto",Z.style.marginRight="auto"),Rr&&ye&&!W()&&(ye.style.maxWidth=Rr,ye.style.marginLeft="auto",ye.style.marginRight="auto"),(mf=n.attachments)!=null&&mf.enabled&&de&&ye){ft=da.fromConfig(n.attachments),ft.setPreviewsContainer(ye),de.addEventListener("change",b=>{let C=b.target;ft==null||ft.handleFileSelect(C.files),C.value=""});let c=n.attachments.dropOverlay,g=Zx(c);me.appendChild(g)}(()=>{var C,D;let c=(D=(C=n.layout)==null?void 0:C.slots)!=null?D:{},g=$=>{switch($){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ze;case"footer-top":return Z;case"composer":return Ae;case"footer-bottom":return fe;default:return null}},b=($,U)=>{var j;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ve.insertBefore(U,Ve.firstChild);else if($==="header-right")Ve.appendChild(U);else{let F=Ve.querySelector(".persona-flex-col");F?(j=F.parentNode)==null||j.insertBefore(U,F.nextSibling):Ve.appendChild(U)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(U):J.insertBefore(U,J.firstChild);break}case"body-bottom":J.appendChild(U);break;case"footer-top":Z.replaceWith(U);break;case"footer-bottom":fe.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let j=U({config:n,defaultContent:()=>g($)});j&&b($,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,j)}})();let Pn=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let C=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?(Fa.has(D)?Fa.delete(D):Fa.add(D),xx(D,C)):$==="tool"&&($a.has(D)?$a.delete(D):$a.add(D),yx(D,C,n)),Bn.delete(D)};ze.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))}),ze.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;ze.addEventListener("click",c=>{var U;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let C=b.closest("[data-actions-for]");if(!C)return;let D=C.getAttribute("data-actions-for");if(!D)return;let $=b.getAttribute("data-action");if($==="copy"){let F=I.getMessages().find(We=>We.id===D);if(F&&ce.onCopy){let We=F.content||"";navigator.clipboard.writeText(We).then(()=>{b.classList.add("persona-message-action-success");let we=Ie("check",14,"currentColor",2);we&&(b.innerHTML="",b.appendChild(we)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ie=Ie("copy",14,"currentColor",2);ie&&(b.innerHTML="",b.appendChild(ie))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),ce.onCopy(F)}}else if($==="upvote"||$==="downvote"){let F=((U=In.get(D))!=null?U:null)===$,We=$==="upvote"?"thumbs-up":"thumbs-down";if(F){In.delete(D),b.classList.remove("persona-message-action-active");let we=Ie(We,14,"currentColor",2);we&&(b.innerHTML="",b.appendChild(we))}else{let we=$==="upvote"?"downvote":"upvote",ie=C.querySelector(`[data-action="${we}"]`);if(ie){ie.classList.remove("persona-message-action-active");let dt=Ie(we==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(ie.innerHTML="",ie.appendChild(dt))}In.set(D,$),b.classList.add("persona-message-action-active");let Le=Ie(We,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=I.getMessages().find(ht=>ht.id===D);Ye&&ce.onFeedback&&ce.onFeedback({type:$,messageId:Ye.id,message:Ye})}}}),ze.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let C=b.closest(".persona-approval-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=b.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",F=I.getMessages().find(we=>we.id===D);if(!(F!=null&&F.approval))return;let We=C.querySelector("[data-approval-buttons]");We&&We.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?I.resolveWebMcpApproval(D,U):I.resolveApproval(F.approval,U)});let ue=null,P=null,ee={artifacts:[],selectedId:null},Se=!1,rt={current:null};ze.addEventListener("click",c=>{var ie,Le,De,Ye,ht;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let C=b.getAttribute("data-download-artifact");if(!C||((De=(Le=(ie=n.features)==null?void 0:ie.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:De.call(Le,{type:"download",artifactId:C}))===!0)return;let $=I.getArtifactById(C),U=$==null?void 0:$.markdown,j=($==null?void 0:$.title)||"artifact";if(!U){let dt=b.closest("[data-open-artifact]"),wt=dt==null?void 0:dt.closest("[data-message-id]"),vt=wt==null?void 0:wt.getAttribute("data-message-id");if(vt){let $e=I.getMessages().find(nt=>nt.id===vt);if($e!=null&&$e.rawContent)try{let nt=JSON.parse($e.rawContent);U=(Ye=nt==null?void 0:nt.props)==null?void 0:Ye.markdown,j=((ht=nt==null?void 0:nt.props)==null?void 0:ht.title)||j}catch{}}}if(!U)return;let F=new Blob([U],{type:"text/markdown"}),We=URL.createObjectURL(F),we=document.createElement("a");we.href=We,we.download=`${j}.md`,we.click(),URL.revokeObjectURL(We)}),ze.addEventListener("click",c=>{var $,U,j;let b=c.target.closest("[data-open-artifact]");if(!b)return;let C=b.getAttribute("data-open-artifact");!C||((j=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:j.call(U,{type:"open",artifactId:C}))===!0||(c.preventDefault(),c.stopPropagation(),Se=!1,I.selectArtifact(C),ln())}),ze.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Qt=Ne.composerOverlay,Ft=(c,g,b)=>{var j,F,We,we;let C=g.trim();if(!C||!rt.current)return;let D=(j=c.getAttribute("data-tool-call-id"))!=null?j:"",$=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:C,answers:b.structured,values:(F=b.values)!=null?F:b.source==="multi"?C.split(", "):[C],isFreeText:$,source:b.source},bubbles:!0,composed:!0})),_o(Qt,D);let U=rt.current.getMessages().find(ie=>{var Le;return((Le=ie.toolCall)==null?void 0:Le.id)===D});(We=U==null?void 0:U.agentMetadata)!=null&&We.awaitingLocalTool?rt.current.resolveAskUserQuestion(U,(we=b.structured)!=null?we:C):rt.current.sendMessage(C)},tr=c=>{var D;let g=rt.current;if(!g)return;let b=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",C=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===b});C&&g.persistAskUserQuestionProgress(C,{answers:Fl(c,C),currentIndex:En(c)})},Pr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),_r=c=>{var D,$,U;if((($=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=En(c),b=qa(c);if(g>=b-1)return;let C=(U=rt.current)==null?void 0:U.getMessages().find(j=>{var F;return((F=j.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});C&&($l(c,C,n,g+1),tr(c))};Qt.addEventListener("click",c=>{var $,U,j,F,We,we,ie,Le,De,Ye,ht,dt,wt,vt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let C=b.closest("[data-persona-ask-sheet-for]");if(!C)return;let D=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let qe=($=C.getAttribute("data-tool-call-id"))!=null?$:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:qe},bubbles:!0,composed:!0})),_o(Qt,qe);let $e=(U=rt.current)==null?void 0:U.getMessages().find(nt=>{var H;return((H=nt.toolCall)==null?void 0:H.id)===qe});(j=$e==null?void 0:$e.agentMetadata)!=null&&j.awaitingLocalTool&&((F=rt.current)==null||F.markAskUserQuestionResolved($e),(We=rt.current)==null||We.resolveAskUserQuestion($e,"(dismissed)"));return}if(D==="pick"){let qe=b.getAttribute("data-option-label");if(!qe)return;let $e=C.getAttribute("data-multi-select")==="true",nt=Oo(C);if(nt&&$e){let H=fa(C)[En(C)],Oe=new Set(Array.isArray(H)?H:[]);Oe.has(qe)?Oe.delete(qe):Oe.add(qe),No(C,Array.from(Oe)),tr(C);return}if(nt){No(C,qe),tr(C),_r(C);return}if($e){let H=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",H?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!H);let Oe=C.querySelector('[data-ask-user-action="submit-multi"]');Oe&&(Oe.disabled=ru(C).length===0);return}Ft(C,qe,{source:"pick",values:[qe]});return}if(D==="submit-multi"){let qe=ru(C);if(qe.length===0)return;Ft(C,qe.join(", "),{source:"multi",values:qe});return}if(D==="open-free-text"){let qe=C.querySelector('[data-ask-free-text-row="true"]');if(qe){qe.classList.remove("persona-hidden");let $e=qe.querySelector('[data-ask-free-text-input="true"]');$e==null||$e.focus()}return}if(D==="focus-free-text"){let qe=C.querySelector('[data-ask-free-text-input="true"]');qe==null||qe.focus();return}if(D==="submit-free-text"){let qe=C.querySelector('[data-ask-free-text-input="true"]'),$e=(we=qe==null?void 0:qe.value)!=null?we:"";if(!$e.trim())return;if(Oo(C)){No(C,$e.trim()),tr(C),_r(C);return}Ft(C,$e,{source:"free-text"});return}if(D==="next"||D==="back"){if(!rt.current)return;let qe=(ie=C.getAttribute("data-tool-call-id"))!=null?ie:"",$e=rt.current.getMessages().find(it=>{var Pe;return((Pe=it.toolCall)==null?void 0:Pe.id)===qe});if(!$e)return;let nt=C.querySelector('[data-ask-free-text-input="true"]'),H=(De=(Le=nt==null?void 0:nt.value)==null?void 0:Le.trim())!=null?De:"";if(H){let it=fa(C)[En(C)];(typeof it!="string"||it!==H)&&No(C,H)}let Oe=D==="next"?1:-1,Je=En(C)+Oe;$l(C,$e,n,Je),tr(C);return}if(D==="submit-all"){if(!rt.current)return;let qe=(Ye=C.getAttribute("data-tool-call-id"))!=null?Ye:"",$e=rt.current.getMessages().find(it=>{var Pe;return((Pe=it.toolCall)==null?void 0:Pe.id)===qe});if(!$e)return;let nt=C.querySelector('[data-ask-free-text-input="true"]'),H=(dt=(ht=nt==null?void 0:nt.value)==null?void 0:ht.trim())!=null?dt:"";H&&No(C,H);let Oe=Fl(C,$e);rt.current.persistAskUserQuestionProgress($e,{answers:Oe,currentIndex:En(C)});let Je=Pr(Oe);Ft(C,Je||"(submitted)",{source:"submit-all",structured:Oe});return}if(D==="skip"){if(!rt.current)return;let qe=(wt=C.getAttribute("data-tool-call-id"))!=null?wt:"",$e=rt.current.getMessages().find(Pe=>{var zt;return((zt=Pe.toolCall)==null?void 0:zt.id)===qe});if(!$e)return;let nt=Oo(C),H=En(C),Oe=qa(C),Je=H>=Oe-1;if(!nt){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:qe},bubbles:!0,composed:!0})),_o(Qt,qe),(vt=$e.agentMetadata)!=null&&vt.awaitingLocalTool&&(rt.current.markAskUserQuestionResolved($e),rt.current.resolveAskUserQuestion($e,"(dismissed)"));return}No(C,"");let it=C.querySelector('[data-ask-free-text-input="true"]');if(it&&(it.value=""),Je){let Pe=Fl(C,$e),zt=Pr(Pe);Ft(C,zt||"(skipped)",{source:"submit-all",structured:Pe});return}$l(C,$e,n,H+1),tr(C);return}}),Qt.addEventListener("keydown",c=>{var $;if(c.key!=="Enter")return;let b=c.target;if(!(($=b.matches)!=null&&$.call(b,'[data-ask-free-text-input="true"]')))return;let C=b.closest("[data-persona-ask-sheet-for]");if(!C)return;c.preventDefault();let D=b.value;if(D.trim()){if(Oo(C)){No(C,D.trim()),tr(C),_r(C);return}Ft(C,D,{source:"free-text"})}});let wn=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let b=Qt.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let C=Number(c.key),$=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[C-1];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",wn);let Vt=null,$t=null,Ir=null,vn=null,bo=()=>{};function eo(){vn==null||vn(),vn=null}let wo=()=>{var U;if(!Vt||!$t)return;let c=t.classList.contains("persona-artifact-appearance-seamless"),b=((U=t.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||t.classList.contains("persona-artifact-narrow-host")||b){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let C=Vt.firstElementChild;if(!C||C===$t)return;let D=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${D}px`,$t.style.zIndex="5";let $=C.offsetWidth-D/2;$t.style.left=`${Math.max(0,$)}px`},qn=()=>{},ln=()=>{var b,C,D,$,U;if(!ue||!Ln(n))return;ql(t,n),zl(t,n),qn();let c=($=(D=(C=(b=n.features)==null?void 0:b.artifacts)==null?void 0:C.layout)==null?void 0:D.narrowHostMaxWidth)!=null?$:520,g=he.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),ue.update(ee),Se?(ue.setMobileOpen(!1),ue.element.classList.add("persona-hidden"),(U=ue.backdrop)==null||U.classList.add("persona-hidden")):ee.artifacts.length>0&&(ue.element.classList.remove("persona-hidden"),ue.setMobileOpen(!0)),bo()};if(Ln(n)){he.style.position="relative";let c=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(me),ue=Nx(n,{onSelect:b=>{var C;return(C=rt.current)==null?void 0:C.selectArtifact(b)},onDismiss:()=>{Se=!0,ln()}}),ue.element.classList.add("persona-hidden"),Vt=g,g.appendChild(c),g.appendChild(ue.element),ue.backdrop&&he.appendChild(ue.backdrop),he.appendChild(g),bo=()=>{var C,D,$,U;if(!Vt||!ue)return;if(!((($=(D=(C=n.features)==null?void 0:C.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue.element.style.removeProperty("width"),ue.element.style.removeProperty("maxWidth");return}if(!$t){let j=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let F=t.ownerDocument,We=(U=F.defaultView)!=null?U:window,we=ie=>{var wt,vt;if(!ue||ie.button!==0||t.classList.contains("persona-artifact-narrow-host")||We.innerWidth<=640)return;ie.preventDefault(),eo();let Le=ie.clientX,De=ue.element.getBoundingClientRect().width,Ye=(vt=(wt=n.features)==null?void 0:wt.artifacts)==null?void 0:vt.layout,ht=qe=>{let $e=Vt.getBoundingClientRect().width,nt=t.classList.contains("persona-artifact-appearance-seamless"),H=nt?0:qx(Vt,We),Oe=nt?0:j.getBoundingClientRect().width||6,Je=De-(qe.clientX-Le),it=zx(Je,$e,H,Oe,Ye==null?void 0:Ye.resizableMinWidth,Ye==null?void 0:Ye.resizableMaxWidth);ue.element.style.width=`${it}px`,ue.element.style.maxWidth="none",wo()},dt=()=>{F.removeEventListener("pointermove",ht),F.removeEventListener("pointerup",dt),F.removeEventListener("pointercancel",dt),vn=null;try{j.releasePointerCapture(ie.pointerId)}catch{}};vn=dt,F.addEventListener("pointermove",ht),F.addEventListener("pointerup",dt),F.addEventListener("pointercancel",dt);try{j.setPointerCapture(ie.pointerId)}catch{}};j.addEventListener("pointerdown",we),$t=j,Vt.insertBefore(j,ue.element),Ir=()=>{j.removeEventListener("pointerdown",we)}}if($t){let j=ee.artifacts.length>0&&!Se;$t.classList.toggle("persona-hidden",!j),wo()}},qn=()=>{var We,we,ie,Le,De,Ye,ht,dt,wt,vt,qe,$e,nt,H;if(!M||!ue||((we=(We=n.launcher)==null?void 0:We.sidebarMode)!=null?we:!1)||Ar(n)&&Mn(n).reveal==="emerge")return;let C=(ie=t.ownerDocument.defaultView)!=null?ie:window,D=(De=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?De:!0,$=(ht=(Ye=n.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?ht:640;if(D&&C.innerWidth<=$||!Ux(n,M))return;let U=(vt=(wt=(dt=n.launcher)==null?void 0:dt.width)!=null?wt:n.launcherWidth)!=null?vt:yn,j=(H=(nt=($e=(qe=n.features)==null?void 0:qe.artifacts)==null?void 0:$e.layout)==null?void 0:nt.expandedPanelWidth)!=null?H:"min(720px, calc(100vw - 24px))";ee.artifacts.length>0&&!Se?(he.style.width=j,he.style.maxWidth=j):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(P=new ResizeObserver(()=>{ln()}),P.observe(he))}else he.appendChild(me),W()&&tt&&(Ne.peekBanner&&tt.appendChild(Ne.peekBanner),tt.appendChild(Xe));t.appendChild(Ce),tt&&t.appendChild(tt);let Rn=()=>{var it,Pe,zt,bt,yr,Wr,Gt,jr,Br,pt,Ct,Gr,Fr,Vo,jo,Go,Aa,Sa,cr,Ko,Po,Bt,rn,io,Kr,nn,Yt,ir;if(W()){he.style.width="100%",he.style.maxWidth="100%";let Zt=(Pe=(it=n.launcher)==null?void 0:it.composerBar)!=null?Pe:{},pr=Ce.dataset.state==="expanded",on=(zt=Zt.expandedSize)!=null?zt:"anchored";if(!(pr&&on!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let Cr=(yr=(bt=n.theme)==null?void 0:bt.components)==null?void 0:yr.panel,jn=Da(n),lo=(Xo,Ci)=>{var us;return Xo==null||Xo===""?Ci:(us=Ba(jn,Xo))!=null?us:Xo},bi="1px solid var(--persona-border)",wi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",vi="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=lo(Cr==null?void 0:Cr.border,bi),me.style.borderRadius=lo(Cr==null?void 0:Cr.borderRadius,vi),me.style.boxShadow=lo(Cr==null?void 0:Cr.shadow,wi),me.style.overflow="hidden";return}let c=Ar(n),g=(Gt=(Wr=n.launcher)==null?void 0:Wr.sidebarMode)!=null?Gt:!1,b=c||g||((Br=(jr=n.launcher)==null?void 0:jr.fullHeight)!=null?Br:!1),C=((pt=n.launcher)==null?void 0:pt.enabled)===!1,D=(Gr=(Ct=n.theme)==null?void 0:Ct.components)==null?void 0:Gr.panel,$=Da(n),U=(Zt,pr)=>{var on;return Zt==null||Zt===""?pr:(on=Ba($,Zt))!=null?on:Zt},j=(Fr=t.ownerDocument.defaultView)!=null?Fr:window,F=(jo=(Vo=n.launcher)==null?void 0:Vo.mobileFullscreen)!=null?jo:!0,We=(Aa=(Go=n.launcher)==null?void 0:Go.mobileBreakpoint)!=null?Aa:640,we=j.innerWidth<=We,ie=F&&we&&M,Le=(cr=(Sa=n.launcher)==null?void 0:Sa.position)!=null?cr:"bottom-left",De=Le==="bottom-left"||Le==="top-left",Ye=(Po=(Ko=n.launcher)==null?void 0:Ko.zIndex)!=null?Po:qr,ht=g||ie?"none":"1px solid var(--persona-border)",dt=ie?"none":g?De?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ie&&(dt="none",ht="none");let wt=g||ie?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=U(D==null?void 0:D.border,ht),qe=U(D==null?void 0:D.shadow,dt),$e=U(D==null?void 0:D.borderRadius,wt),nt=J.scrollTop;t.style.cssText="",Ce.style.cssText="",he.style.cssText="",me.style.cssText="",J.style.cssText="",Xe.style.cssText="";let H=()=>{var pr;if(nt<=0)return;((pr=J.ownerDocument.defaultView)!=null?pr:window).requestAnimationFrame(()=>{if(J.scrollTop===nt)return;let on=J.scrollHeight-J.clientHeight;on<=0||(J.scrollTop=Math.min(nt,on))})};if(ie){Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ce.style.cssText=`
|
|
80
|
+
`,E.addEventListener("click",()=>{m=y,k.forEach((B,P)=>{let R=P<y;B.classList.toggle("selected",R),B.setAttribute("aria-checked",P===y-1?"true":"false")})}),k.push(E),S.appendChild(E)}u.appendChild(S);let T=null;if(d){let y=document.createElement("div");y.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),y.appendChild(T),u.appendChild(y)}let M=document.createElement("div");M.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(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=a,w.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let y=(T==null?void 0:T.value.trim())||void 0;await e(m,y),p.remove()}catch(y){w.disabled=!1,w.textContent=a,console.error("[CSAT Feedback] Failed to submit:",y)}}),M.appendChild(h),M.appendChild(w),u.appendChild(M),p.appendChild(u),p}function Yl(t){let{onSubmit:e,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let 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 S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,x.appendChild(S),f.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let h=document.createElement("span");h.className="persona-feedback-label-high",h.textContent=p,T.appendChild(M),T.appendChild(h);let w=document.createElement("div");w.className="persona-feedback-numbers";let y=[];for(let O=0;O<=10;O++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${O} out of 10`),V.textContent=String(O),V.dataset.rating=String(O),O<=6?V.classList.add("persona-feedback-detractor"):O<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{u=O,y.forEach((ne,be)=>{ne.classList.toggle("selected",be===O),ne.setAttribute("aria-checked",be===O?"true":"false")})}),y.push(V),w.appendChild(V)}k.appendChild(T),k.appendChild(w),f.appendChild(k);let E=null;if(d){let O=document.createElement("div");O.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"),O.appendChild(E),f.appendChild(O)}let B=document.createElement("div");B.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{r==null||r(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await e(u,O),m.remove()}catch(O){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),B.appendChild(P),B.appendChild(R),f.appendChild(B),m.appendChild(f),m}var Ka="persona-chat-history",dC=30*1e3,cC={"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 pC(t){var n,o,s;if(!t)return[];let e=[],r=Array.from((n=t.items)!=null?n:[]);for(let a of r){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=cC[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function Zl(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function uC(t){var e,r,n,o,s,a,i,d,l;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(r=t.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(n=t.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=t.clearOnChatClear)!=null?l:!0}:null}function fC(t){try{let e=t==="local"?localStorage:sessionStorage,r="__persist_test__";return e.setItem(r,"1"),e.removeItem(r),e}catch{return null}}var pu=t=>!t||typeof t!="object"?{}:{...t},Zx=t=>t.map(e=>({...e,streaming:!1})),ey=(t,e,r)=>{let n=t!=null&&t.markdown?na(t.markdown):null,o=Ea(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&r&&r())}let d;return t!=null&&t.postprocessMessage?d=t.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):n?d=n(a):d=oa(a),o?o(d):d}};function ty(t){var i,d,l,p;let e=v("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let r=(i=t==null?void 0:t.iconName)!=null?i:"upload",n=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(l=t==null?void 0:t.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=t==null?void 0:t.iconStrokeWidth)!=null?p:.5,a=Ie(r,n,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let m=v("span","persona-drop-overlay-label");m.textContent=t.label,e.appendChild(m)}return e}var ed=(t,e,r)=>{var Bu,Hu,Du,Ou,Nu,_u,Fu,$u,Uu,qu,zu,Vu,ju,Gu,Ku,Xu,Ju,Qu,Yu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,wf,vf,Cf,Af,Sf,Tf,Mf,kf,Ef;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let n=xl(e),o=Ys.getForInstance(n.plugins);n.components&&yo.registerAll(n.components);let s=Kx(),i=n.persistState===!1?null:(Bu=n.storageAdapter)!=null?Bu:jl(),d={},l=null,p=!1,m=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:A}=g;return A&&(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 m(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=m(g);b.metadata&&(d=pu(b.metadata)),(Hu=b.messages)!=null&&Hu.length&&(n={...n,initialMessages:b.messages}),(Du=b.artifacts)!=null&&Du.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Ou=b.selectedArtifactId)!=null?Ou:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=m({messages:[],metadata:{}});(Nu=c.messages)!=null&&Nu.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let u=()=>d,f=c=>{var b;d=(b=c({...d}))!=null?b:{},ya()},x=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Zs],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ha.message,ha.messageAndClick],S=ei({parsers:x,handlers:C,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let k=(Fu=(_u=n.launcher)==null?void 0:_u.enabled)!=null?Fu:!0,T=(Uu=($u=n.launcher)==null?void 0:$u.autoExpand)!=null?Uu:!1,M=(qu=n.autoFocusInput)!=null?qu:!1,h=T,w=k,y=(Vu=(zu=n.layout)==null?void 0:zu.header)==null?void 0:Vu.layout,E=!1,B=()=>Ho(n),P=()=>k||B(),R=B()?!1:k?T:!0,O=!1,V=null,ne=()=>{O=!0,V&&clearTimeout(V),V=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},be=ey(n,S,ne),Ye=(Gu=(ju=n.features)==null?void 0:ju.showReasoning)!=null?Gu:!0,Ge=(Xu=(Ku=n.features)==null?void 0:Ku.showToolCalls)!=null?Xu:!0,ve=(Qu=(Ju=n.features)==null?void 0:Ju.showEventStreamToggle)!=null?Qu:!1,Ee=(Zu=(Yu=n.features)==null?void 0:Yu.scrollToBottom)!=null?Zu:{},Ne=`${(tf=typeof n.persistState=="object"?(ef=n.persistState)==null?void 0:ef.keyPrefix:void 0)!=null?tf:"persona-"}event-stream`,X=ve?new Js(Ne):null,Ue=(of=(nf=(rf=n.features)==null?void 0:rf.eventStream)==null?void 0:nf.maxEvents)!=null?of:2e3,K=ve?new Xs(Ue,X):null,Te=ve?new Qs:null,oe=null,xe=!1,Me=null,Xe=0;X==null||X.open().then(()=>K==null?void 0:K.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ce={onCopy:c=>{var g,b;s.emit("message:copy",c),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(c.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(b=(g=n.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;s.emit("message:feedback",c),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(c.messageId,c.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(b=(g=n.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},te=(af=n.statusIndicator)!=null?af:{},le=c=>{var g,b,A,D;return c==="idle"?(g=te.idleText)!=null?g:Ur.idle:c==="connecting"?(b=te.connectingText)!=null?b:Ur.connecting:c==="connected"?(A=te.connectedText)!=null?A:Ur.connected:c==="error"?(D=te.errorText)!=null?D:Ur.error:Ur[c]};function ut(c,g,b,A){if(A==="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:Ce,panel:he,pillRoot:rt}=mx(n),_e=gx(n,P()),{container:me,body:J,messagesWrapper:ze,suggestions:Z,textarea:ge,sendButton:z,sendButtonWrapper:Re,composerForm:Ae,statusText:fe,introTitle:pe,introSubtitle:Be,closeButton:Q,iconHolder:_,headerTitle:ke,headerSubtitle:He,header:Ve,footer:Je,actionsRow:gt,leftActions:at,rightActions:Mt}=_e,Xt=_e.setSendButtonMode,G=_e.micButton,Jt=_e.micButtonWrapper,st=_e.attachmentButton,_t=_e.attachmentButtonWrapper,de=_e.attachmentInput,ye=_e.attachmentPreviewsContainer;me.classList.add("persona-relative"),J.classList.add("persona-relative");let Rt=12,ar=()=>{var c;return(c=Ee.label)!=null?c:""},kt=()=>{var c;return(c=Ee.iconName)!=null?c:"arrow-down"},mr=()=>Ee.enabled!==!1,Ot=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let Wt=v("span","persona-flex persona-items-center"),St=v("span","");Ot.append(Wt,St),me.appendChild(Ot);let Et=()=>{let g=Je.style.display==="none"?0:Je.offsetHeight;Ot.style.bottom=`${g+Rt}px`};Et();let sr=()=>{let c=!!ar();Ot.setAttribute("aria-label",ar()||"Jump to latest"),Ot.title=ar(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Wt.innerHTML="";let g=Ie(kt(),"14px","currentColor",2);g?(Wt.appendChild(g),Wt.style.display=""):Wt.style.display="none",St.textContent=ar(),St.style.display=c?"":"none"};sr();let ft=null,dr=null,wr=o.find(c=>c.renderHeader);if(wr!=null&&wr.renderHeader){let c=wr.renderHeader({config:n,defaultRenderer:()=>{let g=go({config:n,showClose:P()});return ua(me,g,n),g.header},onClose:()=>Kt(!1,"user")});if(c){let g=me.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ve=c)}}let Lr=()=>{var g,b,A,D;if(!K)return;if(xe=!0,!oe&&K&&(oe=Nx({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Or(),config:n,plugins:o,getThroughput:()=>{var $;return($=Te==null?void 0:Te.getMetric())!=null?$:{status:"idle"}}})),oe&&(J.style.display="none",(g=Je.parentNode)==null||g.insertBefore(oe.element,Je),oe.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${en.actionIconColor}`;let $=(D=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!xe)return;let $=Date.now();$-Xe>=200&&(oe==null||oe.update(),Xe=$),Me=requestAnimationFrame(c)};Xe=0,Me=requestAnimationFrame(c),oo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Or=()=>{var c,g,b;if(xe){if(xe=!1,oe&&oe.element.remove(),J.style.display="",xt){xt.style.boxShadow="";let A=(b=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;A&&A.split(/\s+/).forEach(D=>D&&xt.classList.remove(D))}Me!==null&&(cancelAnimationFrame(Me),Me=null),oo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(ve){let c=(lf=(sf=n.features)==null?void 0:sf.eventStream)==null?void 0:lf.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=v("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let b=Ie("activity","18px","currentColor",1.5);b&&xt.appendChild(b);let A=_e.clearChatButtonWrapper,D=_e.closeButtonWrapper,$=A||D;$&&$.parentNode===Ve?Ve.insertBefore(xt,$):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}let sn=c=>{var A,D,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(b,U):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=v("input");U.type="file",U.accept=((A=g.allowedTypes)!=null?A:mo).join(","),U.multiple=((D=g.maxFiles)!=null?D:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},fr=o.find(c=>c.renderComposer);if(fr!=null&&fr.renderComposer){let c=n.composer,g=fr.renderComposer({config:n,defaultRenderer:()=>_a({config:n}).footer,onSubmit:b=>{var U;if(!W||W.isStreaming())return;let A=b.trim(),D=(U=ft==null?void 0:ft.hasAttachments())!=null?U:!1;if(!A&&!D)return;as();let $;D&&($=[],$.push(...ft.getContentParts()),A&&$.push(Rs(A))),W.sendMessage(A,{contentParts:$}),D&&ft.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{de==null||de.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((df=n.voiceRecognition)==null?void 0:df.enabled)===!0?()=>{dr==null||dr()}:void 0});g&&(Je.replaceWith(g),Je=g)}let Un=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ae=g),b&&(ge=b),A&&(z=A),D&&(G=D,Jt=D.parentElement),$&&(fe=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Z=U);let j=c.querySelector(".persona-attachment-button");j&&(st=j,_t=j.parentElement),de=c.querySelector('input[type="file"]'),ye=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(gt=F)};sn(Je),Un(Je);let Rr=(mf=(cf=n.layout)==null?void 0:cf.contentMaxWidth)!=null?mf:B()?(ff=(uf=(pf=n.launcher)==null?void 0:pf.composerBar)==null?void 0:uf.contentMaxWidth)!=null?ff:"720px":void 0;if(Rr&&(ze.style.maxWidth=Rr,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%"),Rr&&Ae&&!B()&&(Ae.style.maxWidth=Rr,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Rr&&Z&&!B()&&(Z.style.maxWidth=Rr,Z.style.marginLeft="auto",Z.style.marginRight="auto"),Rr&&ye&&!B()&&(ye.style.maxWidth=Rr,ye.style.marginLeft="auto",ye.style.marginRight="auto"),(gf=n.attachments)!=null&&gf.enabled&&de&&ye){ft=ca.fromConfig(n.attachments),ft.setPreviewsContainer(ye),de.addEventListener("change",b=>{let A=b.target;ft==null||ft.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=ty(c);me.appendChild(g)}(()=>{var A,D;let c=(D=(A=n.layout)==null?void 0:A.slots)!=null?D:{},g=$=>{switch($){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ze;case"footer-top":return Z;case"composer":return Ae;case"footer-bottom":return fe;default:return null}},b=($,U)=>{var j;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ve.insertBefore(U,Ve.firstChild);else if($==="header-right")Ve.appendChild(U);else{let F=Ve.querySelector(".persona-flex-col");F?(j=F.parentNode)==null||j.insertBefore(U,F.nextSibling):Ve.appendChild(U)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(U):J.insertBefore(U,J.firstChild);break}case"body-bottom":J.appendChild(U);break;case"footer-top":Z.replaceWith(U);break;case"footer-bottom":fe.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let j=U({config:n,defaultContent:()=>g($)});j&&b($,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,j)}})();let Pn=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let A=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let D=A.getAttribute("data-message-id");if(!D)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?($a.has(D)?$a.delete(D):$a.add(D),bx(D,A)):$==="tool"&&(Ua.has(D)?Ua.delete(D):Ua.add(D),wx(D,A,n)),Bn.delete(D)};ze.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))}),ze.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;ze.addEventListener("click",c=>{var U;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.closest("[data-actions-for]");if(!A)return;let D=A.getAttribute("data-actions-for");if(!D)return;let $=b.getAttribute("data-action");if($==="copy"){let F=W.getMessages().find(We=>We.id===D);if(F&&ce.onCopy){let We=F.content||"";navigator.clipboard.writeText(We).then(()=>{b.classList.add("persona-message-action-success");let we=Ie("check",14,"currentColor",2);we&&(b.innerHTML="",b.appendChild(we)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let se=Ie("copy",14,"currentColor",2);se&&(b.innerHTML="",b.appendChild(se))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),ce.onCopy(F)}}else if($==="upvote"||$==="downvote"){let F=((U=In.get(D))!=null?U:null)===$,We=$==="upvote"?"thumbs-up":"thumbs-down";if(F){In.delete(D),b.classList.remove("persona-message-action-active");let we=Ie(We,14,"currentColor",2);we&&(b.innerHTML="",b.appendChild(we))}else{let we=$==="upvote"?"downvote":"upvote",se=A.querySelector(`[data-action="${we}"]`);if(se){se.classList.remove("persona-message-action-active");let ct=Ie(we==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(se.innerHTML="",se.appendChild(ct))}In.set(D,$),b.classList.add("persona-message-action-active");let Le=Ie(We,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 Ze=W.getMessages().find(ht=>ht.id===D);Ze&&ce.onFeedback&&ce.onFeedback({type:$,messageId:Ze.id,message:Ze})}}}),ze.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.closest(".persona-approval-bubble");if(!A)return;let D=A.getAttribute("data-message-id");if(!D)return;let $=b.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",F=W.getMessages().find(we=>we.id===D);if(!(F!=null&&F.approval))return;let We=A.querySelector("[data-approval-buttons]");We&&We.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?W.resolveWebMcpApproval(D,U):W.resolveApproval(F.approval,U)});let ue=null,I=null,ee={artifacts:[],selectedId:null},Se=!1,nt={current:null};ze.addEventListener("click",c=>{var se,Le,De,Ze,ht;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((De=(Le=(se=n.features)==null?void 0:se.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:De.call(Le,{type:"download",artifactId:A}))===!0)return;let $=W.getArtifactById(A),U=$==null?void 0:$.markdown,j=($==null?void 0:$.title)||"artifact";if(!U){let ct=b.closest("[data-open-artifact]"),wt=ct==null?void 0:ct.closest("[data-message-id]"),vt=wt==null?void 0:wt.getAttribute("data-message-id");if(vt){let $e=W.getMessages().find(ot=>ot.id===vt);if($e!=null&&$e.rawContent)try{let ot=JSON.parse($e.rawContent);U=(Ze=ot==null?void 0:ot.props)==null?void 0:Ze.markdown,j=((ht=ot==null?void 0:ot.props)==null?void 0:ht.title)||j}catch{}}}if(!U)return;let F=new Blob([U],{type:"text/markdown"}),We=URL.createObjectURL(F),we=document.createElement("a");we.href=We,we.download=`${j}.md`,we.click(),URL.revokeObjectURL(We)}),ze.addEventListener("click",c=>{var $,U,j;let b=c.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||((j=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:j.call(U,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),Se=!1,W.selectArtifact(A),ln())}),ze.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Qt=_e.composerOverlay,Ft=(c,g,b)=>{var j,F,We,we;let A=g.trim();if(!A||!nt.current)return;let D=(j=c.getAttribute("data-tool-call-id"))!=null?j:"",$=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:A,answers:b.structured,values:(F=b.values)!=null?F:b.source==="multi"?A.split(", "):[A],isFreeText:$,source:b.source},bubbles:!0,composed:!0})),_o(Qt,D);let U=nt.current.getMessages().find(se=>{var Le;return((Le=se.toolCall)==null?void 0:Le.id)===D});(We=U==null?void 0:U.agentMetadata)!=null&&We.awaitingLocalTool?nt.current.resolveAskUserQuestion(U,(we=b.structured)!=null?we:A):nt.current.sendMessage(A)},tr=c=>{var D;let g=nt.current;if(!g)return;let b=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",A=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===b});A&&g.persistAskUserQuestionProgress(A,{answers:$l(c,A),currentIndex:En(c)})},Pr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Nr=c=>{var D,$,U;if((($=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=En(c),b=za(c);if(g>=b-1)return;let A=(U=nt.current)==null?void 0:U.getMessages().find(j=>{var F;return((F=j.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});A&&(Ul(c,A,n,g+1),tr(c))};Qt.addEventListener("click",c=>{var $,U,j,F,We,we,se,Le,De,Ze,ht,ct,wt,vt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let A=b.closest("[data-persona-ask-sheet-for]");if(!A)return;let D=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let qe=($=A.getAttribute("data-tool-call-id"))!=null?$:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:qe},bubbles:!0,composed:!0})),_o(Qt,qe);let $e=(U=nt.current)==null?void 0:U.getMessages().find(ot=>{var H;return((H=ot.toolCall)==null?void 0:H.id)===qe});(j=$e==null?void 0:$e.agentMetadata)!=null&&j.awaitingLocalTool&&((F=nt.current)==null||F.markAskUserQuestionResolved($e),(We=nt.current)==null||We.resolveAskUserQuestion($e,"(dismissed)"));return}if(D==="pick"){let qe=b.getAttribute("data-option-label");if(!qe)return;let $e=A.getAttribute("data-multi-select")==="true",ot=No(A);if(ot&&$e){let H=ma(A)[En(A)],Oe=new Set(Array.isArray(H)?H:[]);Oe.has(qe)?Oe.delete(qe):Oe.add(qe),Fo(A,Array.from(Oe)),tr(A);return}if(ot){Fo(A,qe),tr(A),Nr(A);return}if($e){let H=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",H?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!H);let Oe=A.querySelector('[data-ask-user-action="submit-multi"]');Oe&&(Oe.disabled=nu(A).length===0);return}Ft(A,qe,{source:"pick",values:[qe]});return}if(D==="submit-multi"){let qe=nu(A);if(qe.length===0)return;Ft(A,qe.join(", "),{source:"multi",values:qe});return}if(D==="open-free-text"){let qe=A.querySelector('[data-ask-free-text-row="true"]');if(qe){qe.classList.remove("persona-hidden");let $e=qe.querySelector('[data-ask-free-text-input="true"]');$e==null||$e.focus()}return}if(D==="focus-free-text"){let qe=A.querySelector('[data-ask-free-text-input="true"]');qe==null||qe.focus();return}if(D==="submit-free-text"){let qe=A.querySelector('[data-ask-free-text-input="true"]'),$e=(we=qe==null?void 0:qe.value)!=null?we:"";if(!$e.trim())return;if(No(A)){Fo(A,$e.trim()),tr(A),Nr(A);return}Ft(A,$e,{source:"free-text"});return}if(D==="next"||D==="back"){if(!nt.current)return;let qe=(se=A.getAttribute("data-tool-call-id"))!=null?se:"",$e=nt.current.getMessages().find(lt=>{var Pe;return((Pe=lt.toolCall)==null?void 0:Pe.id)===qe});if(!$e)return;let ot=A.querySelector('[data-ask-free-text-input="true"]'),H=(De=(Le=ot==null?void 0:ot.value)==null?void 0:Le.trim())!=null?De:"";if(H){let lt=ma(A)[En(A)];(typeof lt!="string"||lt!==H)&&Fo(A,H)}let Oe=D==="next"?1:-1,Qe=En(A)+Oe;Ul(A,$e,n,Qe),tr(A);return}if(D==="submit-all"){if(!nt.current)return;let qe=(Ze=A.getAttribute("data-tool-call-id"))!=null?Ze:"",$e=nt.current.getMessages().find(lt=>{var Pe;return((Pe=lt.toolCall)==null?void 0:Pe.id)===qe});if(!$e)return;let ot=A.querySelector('[data-ask-free-text-input="true"]'),H=(ct=(ht=ot==null?void 0:ot.value)==null?void 0:ht.trim())!=null?ct:"";H&&Fo(A,H);let Oe=$l(A,$e);nt.current.persistAskUserQuestionProgress($e,{answers:Oe,currentIndex:En(A)});let Qe=Pr(Oe);Ft(A,Qe||"(submitted)",{source:"submit-all",structured:Oe});return}if(D==="skip"){if(!nt.current)return;let qe=(wt=A.getAttribute("data-tool-call-id"))!=null?wt:"",$e=nt.current.getMessages().find(Pe=>{var zt;return((zt=Pe.toolCall)==null?void 0:zt.id)===qe});if(!$e)return;let ot=No(A),H=En(A),Oe=za(A),Qe=H>=Oe-1;if(!ot){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:qe},bubbles:!0,composed:!0})),_o(Qt,qe),(vt=$e.agentMetadata)!=null&&vt.awaitingLocalTool&&(nt.current.markAskUserQuestionResolved($e),nt.current.resolveAskUserQuestion($e,"(dismissed)"));return}Fo(A,"");let lt=A.querySelector('[data-ask-free-text-input="true"]');if(lt&&(lt.value=""),Qe){let Pe=$l(A,$e),zt=Pr(Pe);Ft(A,zt||"(skipped)",{source:"submit-all",structured:Pe});return}Ul(A,$e,n,H+1),tr(A);return}}),Qt.addEventListener("keydown",c=>{var $;if(c.key!=="Enter")return;let b=c.target;if(!(($=b.matches)!=null&&$.call(b,'[data-ask-free-text-input="true"]')))return;let A=b.closest("[data-persona-ask-sheet-for]");if(!A)return;c.preventDefault();let D=b.value;if(D.trim()){if(No(A)){Fo(A,D.trim()),tr(A),Nr(A);return}Ft(A,D,{source:"free-text"})}});let wn=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let b=Qt.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let A=Number(c.key),$=b.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];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",wn);let Vt=null,$t=null,Ir=null,vn=null,bo=()=>{};function eo(){vn==null||vn(),vn=null}let wo=()=>{var U;if(!Vt||!$t)return;let c=t.classList.contains("persona-artifact-appearance-seamless"),b=((U=t.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||t.classList.contains("persona-artifact-narrow-host")||b){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let A=Vt.firstElementChild;if(!A||A===$t)return;let D=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${D}px`,$t.style.zIndex="5";let $=A.offsetWidth-D/2;$t.style.left=`${Math.max(0,$)}px`},qn=()=>{},ln=()=>{var b,A,D,$,U;if(!ue||!Ln(n))return;zl(t,n),Vl(t,n),qn();let c=($=(D=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:D.narrowHostMaxWidth)!=null?$:520,g=he.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),ue.update(ee),Se?(ue.setMobileOpen(!1),ue.element.classList.add("persona-hidden"),(U=ue.backdrop)==null||U.classList.add("persona-hidden")):ee.artifacts.length>0&&(ue.element.classList.remove("persona-hidden"),ue.setMobileOpen(!0)),bo()};if(Ln(n)){he.style.position="relative";let c=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(me),ue=$x(n,{onSelect:b=>{var A;return(A=nt.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{Se=!0,ln()}}),ue.element.classList.add("persona-hidden"),Vt=g,g.appendChild(c),g.appendChild(ue.element),ue.backdrop&&he.appendChild(ue.backdrop),he.appendChild(g),bo=()=>{var A,D,$,U;if(!Vt||!ue)return;if(!((($=(D=(A=n.features)==null?void 0:A.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue.element.style.removeProperty("width"),ue.element.style.removeProperty("maxWidth");return}if(!$t){let j=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let F=t.ownerDocument,We=(U=F.defaultView)!=null?U:window,we=se=>{var wt,vt;if(!ue||se.button!==0||t.classList.contains("persona-artifact-narrow-host")||We.innerWidth<=640)return;se.preventDefault(),eo();let Le=se.clientX,De=ue.element.getBoundingClientRect().width,Ze=(vt=(wt=n.features)==null?void 0:wt.artifacts)==null?void 0:vt.layout,ht=qe=>{let $e=Vt.getBoundingClientRect().width,ot=t.classList.contains("persona-artifact-appearance-seamless"),H=ot?0:Vx(Vt,We),Oe=ot?0:j.getBoundingClientRect().width||6,Qe=De-(qe.clientX-Le),lt=jx(Qe,$e,H,Oe,Ze==null?void 0:Ze.resizableMinWidth,Ze==null?void 0:Ze.resizableMaxWidth);ue.element.style.width=`${lt}px`,ue.element.style.maxWidth="none",wo()},ct=()=>{F.removeEventListener("pointermove",ht),F.removeEventListener("pointerup",ct),F.removeEventListener("pointercancel",ct),vn=null;try{j.releasePointerCapture(se.pointerId)}catch{}};vn=ct,F.addEventListener("pointermove",ht),F.addEventListener("pointerup",ct),F.addEventListener("pointercancel",ct);try{j.setPointerCapture(se.pointerId)}catch{}};j.addEventListener("pointerdown",we),$t=j,Vt.insertBefore(j,ue.element),Ir=()=>{j.removeEventListener("pointerdown",we)}}if($t){let j=ee.artifacts.length>0&&!Se;$t.classList.toggle("persona-hidden",!j),wo()}},qn=()=>{var We,we,se,Le,De,Ze,ht,ct,wt,vt,qe,$e,ot,H;if(!k||!ue||((we=(We=n.launcher)==null?void 0:We.sidebarMode)!=null?we:!1)||Ar(n)&&kn(n).reveal==="emerge")return;let A=(se=t.ownerDocument.defaultView)!=null?se:window,D=(De=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?De:!0,$=(ht=(Ze=n.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?ht:640;if(D&&A.innerWidth<=$||!zx(n,k))return;let U=(vt=(wt=(ct=n.launcher)==null?void 0:ct.width)!=null?wt:n.launcherWidth)!=null?vt:yn,j=(H=(ot=($e=(qe=n.features)==null?void 0:qe.artifacts)==null?void 0:$e.layout)==null?void 0:ot.expandedPanelWidth)!=null?H:"min(720px, calc(100vw - 24px))";ee.artifacts.length>0&&!Se?(he.style.width=j,he.style.maxWidth=j):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(I=new ResizeObserver(()=>{ln()}),I.observe(he))}else he.appendChild(me),B()&&rt&&(_e.peekBanner&&rt.appendChild(_e.peekBanner),rt.appendChild(Je));t.appendChild(Ce),rt&&t.appendChild(rt);let Rn=()=>{var lt,Pe,zt,bt,yr,Wr,Gt,jr,Br,pt,Ct,Gr,Fr,jo,Go,Ko,Sa,Ta,cr,Xo,Po,Bt,rn,io,Kr,nn,Yt,ir;if(B()){he.style.width="100%",he.style.maxWidth="100%";let Zt=(Pe=(lt=n.launcher)==null?void 0:lt.composerBar)!=null?Pe:{},pr=Ce.dataset.state==="expanded",on=(zt=Zt.expandedSize)!=null?zt:"anchored";if(!(pr&&on!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let Cr=(yr=(bt=n.theme)==null?void 0:bt.components)==null?void 0:yr.panel,jn=Oa(n),lo=(Jo,Ai)=>{var fs;return Jo==null||Jo===""?Ai:(fs=Ha(jn,Jo))!=null?fs:Jo},wi="1px solid var(--persona-border)",vi="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))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=lo(Cr==null?void 0:Cr.border,wi),me.style.borderRadius=lo(Cr==null?void 0:Cr.borderRadius,Ci),me.style.boxShadow=lo(Cr==null?void 0:Cr.shadow,vi),me.style.overflow="hidden";return}let c=Ar(n),g=(Gt=(Wr=n.launcher)==null?void 0:Wr.sidebarMode)!=null?Gt:!1,b=c||g||((Br=(jr=n.launcher)==null?void 0:jr.fullHeight)!=null?Br:!1),A=((pt=n.launcher)==null?void 0:pt.enabled)===!1,D=(Gr=(Ct=n.theme)==null?void 0:Ct.components)==null?void 0:Gr.panel,$=Oa(n),U=(Zt,pr)=>{var on;return Zt==null||Zt===""?pr:(on=Ha($,Zt))!=null?on:Zt},j=(Fr=t.ownerDocument.defaultView)!=null?Fr:window,F=(Go=(jo=n.launcher)==null?void 0:jo.mobileFullscreen)!=null?Go:!0,We=(Sa=(Ko=n.launcher)==null?void 0:Ko.mobileBreakpoint)!=null?Sa:640,we=j.innerWidth<=We,se=F&&we&&k,Le=(cr=(Ta=n.launcher)==null?void 0:Ta.position)!=null?cr:"bottom-left",De=Le==="bottom-left"||Le==="top-left",Ze=(Po=(Xo=n.launcher)==null?void 0:Xo.zIndex)!=null?Po:qr,ht=g||se?"none":"1px solid var(--persona-border)",ct=se?"none":g?De?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!se&&(ct="none",ht="none");let wt=g||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=U(D==null?void 0:D.border,ht),qe=U(D==null?void 0:D.shadow,ct),$e=U(D==null?void 0:D.borderRadius,wt),ot=J.scrollTop;t.style.cssText="",Ce.style.cssText="",he.style.cssText="",me.style.cssText="",J.style.cssText="",Je.style.cssText="";let H=()=>{var pr;if(ot<=0)return;((pr=J.ownerDocument.defaultView)!=null?pr:window).requestAnimationFrame(()=>{if(J.scrollTop===ot)return;let on=J.scrollHeight-J.clientHeight;on<=0||(J.scrollTop=Math.min(ot,on))})};if(se){Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ce.style.cssText=`
|
|
81
81
|
position: fixed !important;
|
|
82
82
|
inset: 0 !important;
|
|
83
83
|
width: 100% !important;
|
|
@@ -87,7 +87,7 @@ _Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;this
|
|
|
87
87
|
padding: 0 !important;
|
|
88
88
|
display: flex !important;
|
|
89
89
|
flex-direction: column !important;
|
|
90
|
-
z-index: ${
|
|
90
|
+
z-index: ${Ze} !important;
|
|
91
91
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
92
92
|
`,he.style.cssText=`
|
|
93
93
|
position: relative !important;
|
|
@@ -113,7 +113,7 @@ _Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;this
|
|
|
113
113
|
overflow: hidden !important;
|
|
114
114
|
border-radius: 0 !important;
|
|
115
115
|
border: none !important;
|
|
116
|
-
`,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",
|
|
116
|
+
`,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0",E=!0,H();return}let Oe=(rn=(Bt=n==null?void 0:n.launcher)==null?void 0:Bt.width)!=null?rn:n==null?void 0:n.launcherWidth,Qe=Oe!=null?Oe:yn;if(!g&&!c)A&&b?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=Qe,he.style.maxWidth=Qe);else if(c)if(kn(n).reveal==="emerge"){let pr=kn(n).width;he.style.width=pr,he.style.maxWidth=pr}else he.style.width="100%",he.style.maxWidth="100%";if(qn(),he.style.boxShadow=qe,he.style.borderRadius=$e,me.style.border=vt,me.style.borderRadius=$e,c&&!se&&(D==null?void 0:D.border)===void 0&&(me.style.border="none",kn(n).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),b&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",A&&(t.style.width="100%"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.height="100%",A&&(Ce.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0"),Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!A&&!c&&((io=$n[Le])!=null?io:$n["bottom-right"]).split(" ").forEach(pr=>Ce.classList.add(pr)),g){let Zt=(nn=(Kr=n.launcher)==null?void 0:Kr.sidebarWidth)!=null?nn:"420px";Ce.style.cssText=`
|
|
117
117
|
position: fixed !important;
|
|
118
118
|
top: 0 !important;
|
|
119
119
|
bottom: 0 !important;
|
|
@@ -124,7 +124,7 @@ _Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;this
|
|
|
124
124
|
padding: 0 !important;
|
|
125
125
|
display: flex !important;
|
|
126
126
|
flex-direction: column !important;
|
|
127
|
-
z-index: ${
|
|
127
|
+
z-index: ${Ze} !important;
|
|
128
128
|
${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
129
129
|
`,he.style.cssText=`
|
|
130
130
|
position: relative !important;
|
|
@@ -150,27 +150,27 @@ _Details: ${r.message}_`:n}var Wa=class t{constructor(e={},r){this.config=e;this
|
|
|
150
150
|
overflow: hidden !important;
|
|
151
151
|
border-radius: ${$e} !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(!C&&!c){let Zt="max-height: -moz-available !important; max-height: stretch !important;",pr=g?"":"padding-top: 1.25em !important;",on=g?"":`z-index: ${(ir=(Yt=n.launcher)==null?void 0:Yt.zIndex)!=null?ir:qr} !important;`;Ce.style.cssText+=Zt+pr+on}H()};Rn(),Io(t,n),ql(t,n),zl(t,n);let Pt=[];Pt.push(()=>{document.removeEventListener("keydown",wn)});let gr=null,hr=null;Pt.push(()=>{gr==null||gr(),gr=null,hr==null||hr(),hr=null}),P&&Pt.push(()=>{P==null||P.disconnect(),P=null}),Pt.push(()=>{Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue==null||ue.element.style.removeProperty("width"),ue==null||ue.element.style.removeProperty("maxWidth")}),ve&&Pt.push(()=>{ke!==null&&(cancelAnimationFrame(ke),ke=null),ae==null||ae.destroy(),ae=null,K==null||K.destroy(),K=null,X=null});let dn=null,vo=()=>{dn&&(dn(),dn=null),n.colorScheme==="auto"&&(dn=bl(()=>{Io(t,n)}))};vo(),Pt.push(()=>{dn&&(dn(),dn=null)});let Cn=(gf=n.features)==null?void 0:gf.streamAnimation;if(Cn!=null&&Cn.type&&Cn.type!=="none"){let c=$s(Cn.type,Cn.plugins);c&&(_p(c,t),Pt.push(()=>lx(t)))}let Wn=Rx(Z),cn=null,I,pn=!1,Bn=rx(),to=new Map,zn=new Map,Xa=0,Hn=Cl(),Dn=0,On=null,ro=!1,Fo=!1,ri=4,Ja=24,ni=80,ha=new Map,Lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Qa=(xf=(hf=n.voiceRecognition)==null?void 0:hf.autoResume)!=null?xf:!1,An=c=>{s.emit("voice:state",{active:Lt.active,source:c,timestamp:Date.now()})},tn=()=>{f(c=>({...c,voiceState:{active:Lt.active,timestamp:Date.now(),manuallyDeactivated:Lt.manuallyDeactivated}}))},oi=()=>{var C,D;if(((C=n.voiceRecognition)==null?void 0:C.enabled)===!1)return;let c=cu(d.voiceState),g=!!c.active,b=Number((D=c.timestamp)!=null?D:0);Lt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<iC&&setTimeout(()=>{var $,U;Lt.active||(Lt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),An("restore"),I.isVoiceActive()&&q()}):zo("restore"))},1e3)},ai=()=>I?Qx(I.getMessages()).filter(c=>!c.__skipPersist):[];function xa(c){if(!(i!=null&&i.save))return;let b={messages:c?Qx(c):I?ai():[],metadata:d,artifacts:ee.artifacts,selectedArtifactId:ee.selectedId};try{let C=i.save(b);C instanceof Promise&&C.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let no=null,si=()=>Ce.querySelector("#persona-scroll-container")||J,$o=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ro=!1},Ya=()=>{On!==null&&(cancelAnimationFrame(On),On=null),Fo=!1,$o()},oo=()=>{if(!mr()||xe){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==me&&me.appendChild(Ot),Et();let c=Os(J)>0;Ot.style.display=Hn.isFollowing()||!c?"none":""},Za=()=>{Hn.pause()&&(Ya(),oo())},Co=()=>{Hn.resume(),oo()},Ao=(c=!1)=>{Hn.isFollowing()&&(!c&&!pn||(On!==null&&(cancelAnimationFrame(On),On=null),Fo=!0,On=requestAnimationFrame(()=>{On=null,Fo=!1,Hn.isFollowing()&&ii(si(),c?220:140)})))},ii=(c,g=500)=>{let b=c.scrollTop,C=Os(c),D=C-b;if(Math.abs(D)<1){Dn=c.scrollTop;return}if(Math.abs(D)>=ni){$o(),ro=!0,c.scrollTop=C,Dn=c.scrollTop,ro=!1;return}$o();let $=performance.now();ro=!0;let U=F=>1-Math.pow(1-F,3),j=F=>{if(!Hn.isFollowing()){$o();return}let We=Os(c);We!==C&&(C=We,D=C-b);let we=F-$,ie=Math.min(we/g,1),Le=U(ie),De=b+D*Le;c.scrollTop=De,Dn=c.scrollTop,ie<1?no=requestAnimationFrame(j):(c.scrollTop=C,Dn=c.scrollTop,no=null,ro=!1)};no=requestAnimationFrame(j)},li=c=>{let g=new Map;c.forEach(b=>{let C=ha.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!C&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(C!=null&&C.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(C?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),ha.clear(),g.forEach((b,C)=>{ha.set(C,b)})},Uo=(c,g,b)=>{var dt,wt,vt,qe,$e,nt;let C=document.createElement("div"),$=(()=>{var Oe;let H=o.find(Je=>Je.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),U=(H,Oe)=>Oe==null?!1:typeof Oe=="string"?(H.textContent=Oe,!0):(H.appendChild(Oe),!0),j=new Set,F=new Set,We=o.some(H=>H.renderAskUserQuestion),we=[],ie=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(H=>{var jr,Br,pt,Ct,Gr,Fr,Vo,jo,Go,Aa,Sa,cr,Ko,Po;j.add(H.id);let Oe=We&&ho(H),Je=!Oe&&H.role==="assistant"&&!H.variant&&Le&&Kl(H);if(!Je&&zn.has(H.id)){let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime"),zn.delete(H.id)}let it=ho(H)?`:${(jr=H.agentMetadata)!=null&&jr.askUserQuestionAnswered?"a":"u"}:${(Br=H.agentMetadata)!=null&&Br.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Pe=tx(H,Xa)+it,zt=Oe||Je?null:nx(Bn,H.id,Pe);if(zt){C.appendChild(zt.cloneNode(!0)),ho(H)&&((pt=H.toolCall)!=null&&pt.id)&&((Ct=H.agentMetadata)==null?void 0:Ct.awaitingLocalTool)===!0&&!((Gr=H.agentMetadata)!=null&&Gr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),za(H,n,Ne.composerOverlay));return}let bt=null,yr=o.find(Bt=>!!(H.variant==="reasoning"&&Bt.renderReasoning||H.variant==="tool"&&Bt.renderToolCall||H.variant==="approval"&&Bt.renderApproval||!H.variant&&Bt.renderMessage)),Wr=(Fr=n.layout)==null?void 0:Fr.messages;if(ho(H)&&((Vo=H.agentMetadata)==null?void 0:Vo.askUserQuestionAnswered)===!0){to.delete(H.id);let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime");return}if(ho(H)&&((Go=(jo=n.features)==null?void 0:jo.askUserQuestion)==null?void 0:Go.enabled)!==!1){let Bt=o.find(rn=>typeof rn.renderAskUserQuestion=="function");if(Bt&&rt.current){let rn=to.get(H.id),io=rn!==Pe,Kr=null;if(io){let{payload:ir,complete:Zt}=xo(H),pr=H.id,on=()=>{var fn;return(fn=rt.current)==null?void 0:fn.getMessages().find(Cr=>Cr.id===pr)};Kr=Bt.renderAskUserQuestion({message:H,payload:ir,complete:Zt,resolve:fn=>{var jn;let Cr=on();Cr&&((jn=rt.current)==null||jn.resolveAskUserQuestion(Cr,fn))},dismiss:()=>{var Cr,jn,lo;let fn=on();(Cr=fn==null?void 0:fn.agentMetadata)!=null&&Cr.awaitingLocalTool&&((jn=rt.current)==null||jn.markAskUserQuestionResolved(fn),(lo=rt.current)==null||lo.resolveAskUserQuestion(fn,"(dismissed)"))},config:n})}let nn=rn!=null;if(io&&Kr===null&&!nn){((Aa=H.agentMetadata)==null?void 0:Aa.awaitingLocalTool)===!0&&!((Sa=H.agentMetadata)!=null&&Sa.askUserQuestionAnswered)&&(F.add(H.toolCall.id),za(H,n,Ne.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),C.appendChild(Yt),we.push({messageId:H.id,fingerprint:Pe,bubble:Kr});return}else{((cr=H.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Ko=H.agentMetadata)!=null&&Ko.askUserQuestionAnswered)&&(F.add(H.toolCall.id),za(H,n,Ne.composerOverlay));return}}else if(yr)if(H.variant==="reasoning"&&H.reasoning&&yr.renderReasoning){if(!Qe)return;bt=yr.renderReasoning({message:H,defaultRenderer:()=>Kp(H,n),config:n})}else if(H.variant==="tool"&&H.toolCall&&yr.renderToolCall){if(!je)return;bt=yr.renderToolCall({message:H,defaultRenderer:()=>Xp(H,n),config:n})}else if(H.variant==="approval"&&H.approval&&yr.renderApproval){if(n.approval===!1)return;bt=yr.renderApproval({message:H,defaultRenderer:()=>nu(H,n),config:n})}else yr.renderMessage&&(bt=yr.renderMessage({message:H,defaultRenderer:()=>{let Bt=Na(H,b,Wr,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n});return H.role!=="user"&&iu(Bt,H,n,I),Bt},config:n}));if(!bt&&Je){let Bt=Xl(H);if(Bt){let rn=zn.get(H.id),io=rn!==Pe,Kr=n.wrapComponentDirectiveInBubble!==!1,nn=null;if(io){let Yt=Gl(Bt,{config:n,message:H,transform:b});if(Yt)if(Kr){let ir=document.createElement("div");if(ir.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Zt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}else{let ir=document.createElement("div");if(ir.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),ir.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Zt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}}if(nn||rn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),Kr||Yt.classList.add("persona-w-full"),C.appendChild(Yt),ie.push({messageId:H.id,fingerprint:Pe,bubble:nn});return}}}if(!bt)if(H.variant==="reasoning"&&H.reasoning){if(!Qe)return;bt=Kp(H,n)}else if(H.variant==="tool"&&H.toolCall){if(!je)return;bt=Xp(H,n)}else if(H.variant==="approval"&&H.approval){if(n.approval===!1)return;bt=nu(H,n)}else{let Bt=(Po=n.layout)==null?void 0:Po.messages;Bt!=null&&Bt.renderUserMessage&&H.role==="user"?bt=Bt.renderUserMessage({message:H,config:n,streaming:!!H.streaming}):Bt!=null&&Bt.renderAssistantMessage&&H.role==="assistant"?bt=Bt.renderAssistantMessage({message:H,config:n,streaming:!!H.streaming}):bt=Na(H,b,Bt,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n}),H.role!=="user"&&bt&&iu(bt,H,n,I)}let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-${H.id}`,Gt.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Gt.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&Gt.classList.add("persona-w-full"),Gt.appendChild(bt),ox(Bn,H.id,Pe,Gt),C.appendChild(Gt)}),Ne.composerOverlay&&Ne.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Je=Oe.getAttribute("data-persona-ask-sheet-for");Je&&!F.has(Je)&&_o(Ne.composerOverlay,Je)}),(wt=(dt=n.features)==null?void 0:dt.toolCallDisplay)!=null&&wt.grouped){let H=[],Oe=[];g.forEach(Je=>{if(Je.variant==="tool"&&Je.toolCall&&je){Oe.push(Je);return}Oe.length>1&&H.push(Oe),Oe=[]}),Oe.length>1&&H.push(Oe),H.forEach((Je,it)=>{var Br,pt;let Pe=Je.map(Ct=>Array.from(C.children).find(Gr=>Gr instanceof HTMLElement&&Gr.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(Pe.length<2)return;let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-tool-group-${it}-${Je[0].id}`,zt.setAttribute("data-wrapper-id",`tool-group-${it}-${Je[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let yr=document.createElement("div");yr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Wr=`Called ${Je.length} tools`,Gt=(pt=(Br=n.toolCall)==null?void 0:Br.renderGroupedSummary)==null?void 0:pt.call(Br,{messages:Je,toolCalls:Je.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:Wr,config:n});U(yr,Gt)||(yr.textContent=Wr);let jr=document.createElement("div");jr.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(yr,jr),zt.appendChild(bt),Pe[0].before(zt),Pe.forEach((Ct,Gr)=>{let Fr=document.createElement("div");Fr.className="persona-tool-group-item persona-relative",Fr.setAttribute("data-persona-tool-group-item","true"),Gr<Pe.length-1&&Fr.setAttribute("data-persona-tool-group-connector","true"),Fr.appendChild(Ct),jr.appendChild(Fr)})})}ax(Bn,j);let De=g.some(H=>H.role==="assistant"&&H.streaming),Ye=g[g.length-1],ht=(Ye==null?void 0:Ye.role)==="assistant"&&!Ye.streaming&&Ye.variant!=="approval";if(pn&&g.some(H=>H.role==="user")&&!De&&!ht){let H={config:n,streaming:!0,location:"standalone",defaultRenderer:ua},Oe=o.find(it=>it.renderLoadingIndicator),Je=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Je=Oe.renderLoadingIndicator(H)),Je===null&&((vt=n.loadingIndicator)!=null&&vt.render)&&(Je=n.loadingIndicator.render(H)),Je===null&&(Je=ua()),Je){let it=document.createElement("div"),Pe=((qe=n.loadingIndicator)==null?void 0:qe.showBubble)!==!1;it.className=Pe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),it.setAttribute("data-typing-indicator","true"),it.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",it.appendChild(Je);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-typing-indicator",zt.setAttribute("data-wrapper-id","typing-indicator"),zt.appendChild(it),C.appendChild(zt)}}if(!pn&&g.length>0){let H=g[g.length-1],Oe={config:n,lastMessage:H,messageCount:g.length},Je=o.find(Pe=>Pe.renderIdleIndicator),it=null;if(Je!=null&&Je.renderIdleIndicator&&(it=Je.renderIdleIndicator(Oe)),it===null&&(($e=n.loadingIndicator)!=null&&$e.renderIdle)&&(it=n.loadingIndicator.renderIdle(Oe)),it){let Pe=document.createElement("div"),zt=((nt=n.loadingIndicator)==null?void 0:nt.showBubble)!==!1;Pe.className=zt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(it);let bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Pe),C.appendChild(bt)}}if(wl(c,C),we.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Je}of we){let it=c.querySelector(`#wrapper-${H}`);it&&Je!==null&&(it.replaceChildren(Je),it.setAttribute("data-bubble-fp",Oe),to.set(H,Oe))}if(to.size>0)for(let H of to.keys())j.has(H)||to.delete(H);if(ie.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Je}of ie){let it=c.querySelector(`#wrapper-${H}`);it&&Je!==null&&(it.replaceChildren(Je),it.setAttribute("data-bubble-fp",Oe),zn.set(H,Oe))}if(zn.size>0)for(let H of zn.keys())j.has(H)||zn.delete(H)},So=null,di=()=>{var b;if(So)return;let c=C=>{let D=C.composedPath();D.includes(Ce)||tt&&D.includes(tt)||Kt(!1,"user")};So=c,((b=t.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},es=()=>{var g;if(!So)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("pointerdown",So,!0),So=null};Pt.push(()=>es());let To=null,ci=()=>{var b;if(To)return;let c=C=>{C.key==="Escape"&&(C.isComposing||Kt(!1,"user"))};To=c,((b=t.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},ts=()=>{var g;if(!To)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("keydown",To,!0),To=null};Pt.push(()=>ts());let ko=!1,rs=new Set,pi=()=>{var g,b,C,D;let c=(C=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:C.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},ao=()=>{var wt,vt,qe,$e;if(!W())return;let c=Ne.peekBanner,g=Ne.peekTextNode;if(!c||!g)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let b=(wt=I==null?void 0:I.getMessages())!=null?wt:[],C;for(let nt=b.length-1;nt>=0;nt--){let H=b[nt];if(H.role==="assistant"&&H.content){C=H;break}}if(!C){c.classList.remove("persona-pill-peek--visible");return}let D=C.content,$=!!C.streaming,U=pi(),j=Tl(U),F=j.type!=="none"?$s(j.type,U==null?void 0:U.plugins):null,We=((vt=F==null?void 0:F.isAnimating)==null?void 0:vt.call(F,C))===!0,we=F!==null&&($||We);we&&F&&!rs.has(F.name)&&(_p(F,t),rs.add(F.name));let ie=we&&(F!=null&&F.containerClass)?F.containerClass:null,Le=(qe=g.dataset.personaPeekStreamClass)!=null?qe:null;Le&&Le!==ie&&(g.classList.remove(Le),delete g.dataset.personaPeekStreamClass),ie&&Le!==ie&&(g.classList.add(ie),g.dataset.personaPeekStreamClass=ie),we?(g.style.setProperty("--persona-stream-step",`${j.speed}ms`),g.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let De=we?kl(D,j.buffer,F,C,$):D;if(we&&j.placeholder==="skeleton"&&$&&(!De||!De.trim())){let nt=document.createElement("div"),H=qs();H.classList.add("persona-pill-peek__skeleton"),nt.appendChild(H),wl(g,nt)}else{let nt=Math.max(0,De.length-100),H=De.length>100?De.slice(-100):De,Oe=na(H);if(!we||!F){let Je=De.length>100?`\u2026${H}`:H;g.textContent!==Je&&(g.textContent=Je)}else{let Je=Oe;(F.wrap==="char"||F.wrap==="word")&&(Je=Us(Oe,F.wrap,`peek-${C.id}`,{skipTags:F.skipTags,startIndex:nt}));let it=document.createElement("div");if(it.innerHTML=Je,F.useCaret&&H.length>0){let Pe=Ml(),zt=it.querySelectorAll(".persona-stream-char, .persona-stream-word"),bt=zt[zt.length-1];bt!=null&&bt.parentNode?bt.parentNode.insertBefore(Pe,bt.nextSibling):it.appendChild(Pe)}wl(g,it),($e=F.onAfterRender)==null||$e.call(F,{container:g,bubble:c,messageId:C.id,message:C,speed:j.speed,duration:j.duration})}}let dt=pn||ko;c.classList.toggle("persona-pill-peek--visible",dt)};if(W()){let c=Ne.peekBanner;if(c){let C=D=>{D.preventDefault(),D.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",C),Pt.push(()=>{c.removeEventListener("pointerdown",C)})}let g=()=>{ko||(ko=!0,ao())},b=()=>{ko&&(ko=!1,ao())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",b),Pt.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",b)}),tt&&(tt.addEventListener("pointerenter",g),tt.addEventListener("pointerleave",b),Pt.push(()=>{tt.removeEventListener("pointerenter",g),tt.removeEventListener("pointerleave",b)}))}let ui=c=>{var Le,De,Ye,ht,dt,wt,vt,qe;let g=(De=(Le=n.launcher)==null?void 0:Le.composerBar)!=null?De:{},b=(Ye=g.expandedSize)!=null?Ye:"anchored",C=(ht=g.bottomOffset)!=null?ht:"16px",D=g.collapsedMaxWidth,$=(dt=g.expandedMaxWidth)!=null?dt:"880px",U=(wt=g.expandedTopOffset)!=null?wt:"5vh",j=(vt=g.modalMaxWidth)!=null?vt:"880px",F=(qe=g.modalMaxHeight)!=null?qe:"min(90vh, 800px)",We="calc(100vw - 32px)",we="var(--persona-pill-area-height, 80px)",ie=Ce.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",tt){let $e=tt.style;$e.bottom=C,$e.width=D!=null?D:""}if(c&&b!=="fullscreen"){if(b==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=j,ie.maxWidth=We,ie.maxHeight=F,ie.height=F;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${C} + ${we})`,ie.top=U,ie.width=$,ie.maxWidth=We}},Mo=()=>{var F,We,we,ie,Le,De,Ye,ht;if(!R())return;if(W()){let wt=(we=((We=(F=n.launcher)==null?void 0:F.composerBar)!=null?We:{}).expandedSize)!=null?we:"anchored",vt=B?"expanded":"collapsed";Ce.dataset.state=vt,Ce.dataset.expandedSize=wt,tt&&(tt.dataset.state=vt,tt.dataset.expandedSize=wt),Ce.style.removeProperty("display"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ui(B),me.style.display=B?"flex":"none",Rn(),B?(di(),ci()):(es(),ts()),ao();return}let c=Ar(n),g=(ie=t.ownerDocument.defaultView)!=null?ie:window,b=(De=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?De:640,C=(ht=(Ye=n.launcher)==null?void 0:Ye.mobileFullscreen)!=null?ht:!0,D=g.innerWidth<=b,$=C&&D&&M,U=Mn(n).reveal;B?(Ce.style.removeProperty("display"),Ce.style.display=c?"flex":"",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),Fe?Fe.element.style.display="none":lt&&(lt.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Ce.style.removeProperty("display"),Ce.style.display="flex",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.setProperty("display","none","important"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.display="",Ce.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),Fe?Fe.element.style.display=c?"none":"":lt&&(lt.style.display=c?"none":""))},Kt=(c,g="user")=>{var $,U;if(!R()||B===c)return;let b=B;B=c,Mo();let C=(()=>{var Ye,ht,dt,wt,vt,qe,$e,nt,H,Oe;let j=(ht=(Ye=n.launcher)==null?void 0:Ye.sidebarMode)!=null?ht:!1,F=(dt=t.ownerDocument.defaultView)!=null?dt:window,We=(vt=(wt=n.launcher)==null?void 0:wt.mobileFullscreen)!=null?vt:!0,we=($e=(qe=n.launcher)==null?void 0:qe.mobileBreakpoint)!=null?$e:640,ie=F.innerWidth<=we,Le=Ar(n)&&We&&ie,De=W()&&((Oe=(H=(nt=n.launcher)==null?void 0:nt.composerBar)==null?void 0:H.expandedSize)!=null?Oe:"fullscreen")==="fullscreen";return j||We&&ie&&M||Le||De})();if(B&&C){if(!gr){let j=t.getRootNode(),F=j instanceof ShadowRoot?j.host:t.closest(".persona-host");F&&(gr=Np(F,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:qr))}hr||(hr=Fp(t.ownerDocument))}else B||(gr==null||gr(),gr=null,hr==null||hr(),hr=null);B&&(jt(),Ao(!0));let D={open:B,source:g,timestamp:Date.now()};B&&!b?s.emit("widget:opened",D):!B&&b&&s.emit("widget:closed",D),s.emit("widget:state",{open:B,launcherEnabled:M,voiceActive:Lt.active,streaming:I.isStreaming()})},ya=c=>{Xt(c?"stop":"send"),G&&(G.disabled=c),Wn.buttons.forEach(g=>{g.disabled=c}),Xe.dataset.personaComposerStreaming=c?"true":"false",Xe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},ba=()=>{Lt.active||ge&&ge.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>ba(),200)});let ns=()=>{var b,C,D,$,U,j,F,We,we,ie,Le;pe.textContent=(C=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?C:"Hello \u{1F44B}",Be.textContent=($=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ge.placeholder=(j=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?j:"How can I help...";let c=J.querySelector("[data-persona-intro-card]");if(c){let De=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=De?"":"none",De?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}!((we=(We=n.sendButton)==null?void 0:We.useIcon)!=null&&we)&&!(I!=null&&I.isStreaming())&&(z.textContent=(Le=(ie=n.copy)==null?void 0:ie.sendButtonLabel)!=null?Le:"Send"),ge.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ge.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let Vn=null,fi=()=>{Vn==null&&(Vn=setInterval(()=>{let c=ze.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Vn),Vn=null;return}let g=Date.now();c.forEach(b=>{let C=Number(b.getAttribute("data-tool-elapsed"));C&&(b.textContent=zi(g-C))})},100))};if(I=new Wa(n,{onMessagesChanged(c){Uo(ze,c,be),fi(),I&&(c.some(D=>D.role==="user")?Wn.render([],I,ge,c):Wn.render(n.suggestionChips,I,ge,c,n.suggestionChipsConfig)),Ao(!pn),li(c);let g=[...c].reverse().find(C=>C.role==="user"),b=Lt.lastUserMessageId;g&&g.id!==b&&(Lt.lastUserMessageId=g.id,s.emit("user:message",g)),Lt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),xa(c),ao()},onStatusChanged(c){var C;let g=(C=n.statusIndicator)!=null?C:{};ut(fe,(D=>{var $,U,j,F;return D==="idle"?($=g.idleText)!=null?$:Ur.idle:D==="connecting"?(U=g.connectingText)!=null?U:Ur.connecting:D==="connected"?(j=g.connectedText)!=null?j:Ur.connected:D==="error"?(F=g.errorText)!=null?F:Ur.error:Ur[D]})(c),g,c)},onStreamingChanged(c){pn=c,ya(c),I&&Uo(ze,I.getMessages(),be),c||Ao(!0),ao()},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":Y(),O();break;case"speaking":Y(),se();break;default:c==="idle"&&I.isBargeInActive()?(Y(),q(),G==null||G.setAttribute("aria-label","End voice session")):(Lt.active=!1,Y(),An("system"),tn());break}},onArtifactsState(c){ee=c,ln(),xa()}}),rt.current=I,((bf=(yf=n.voiceRecognition)==null?void 0:yf.provider)==null?void 0:bf.type)==="runtype")try{I.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&I.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||n.onSSEEvent)&&I.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,c,g),Te==null||Te.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,C;c&&(c.metadata&&(d=cu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length&&I.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&I.hydrateArtifacts(c.artifacts,(C=c.selectedArtifactId)!=null?C:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let os=()=>{var g,b,C;!W()||B||!((C=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||C)||Kt(!0,"auto")},as=c=>{var D;if(c.preventDefault(),I.isStreaming()){I.cancel(),Te==null||Te.reset(),ae==null||ae.update();return}let g=ge.value.trim(),b=(D=ft==null?void 0:ft.hasAttachments())!=null?D:!1;if(!g&&!b)return;os();let C;b&&(C=[],C.push(...ft.getContentParts()),g&&C.push(Rs(g))),ge.value="",ge.style.height="auto",qo(),I.sendMessage(g,{contentParts:C}),b&&ft.clearAttachments()},mi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},wa={...vl},va=!1,qo=()=>{wa={...vl}},gi=()=>I.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),hi=c=>{if(!ge)return;va=!0,ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),va=!1;let g=ge.value.length;ge.setSelectionRange(g,g)},ss=()=>{va||qo()},is=c=>{if(ge){if(mi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ge.selectionStart===0&&ge.selectionEnd===0,b=ex({direction:c.key==="ArrowUp"?"up":"down",history:gi(),currentValue:ge.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(I.isStreaming()){c.preventDefault();return}qo(),c.preventDefault(),z.click()}}},ls=c=>{c.key!=="Escape"||c.isComposing||I.isStreaming()&&c.composedPath().includes(me)&&(I.cancel(),Te==null||Te.reset(),ae==null||ae.update(),qo(),c.preventDefault(),c.stopImmediatePropagation())},ds=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!ft)return;let g=dC(c.clipboardData);g.length!==0&&(c.preventDefault(),await ft.handleFiles(g))},zr=null,un=!1,so=null,yt=null,cs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,zo=(c="user")=>{var $,U,j,F,We,we,ie;if(un||I.isStreaming())return;let g=cs();if(!g)return;zr=new g;let C=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;zr.continuous=!0,zr.interimResults=!0,zr.lang="en-US";let D=ge.value;zr.onresult=Le=>{let De="",Ye="";for(let dt=0;dt<Le.results.length;dt++){let wt=Le.results[dt],vt=wt[0].transcript;wt.isFinal?De+=vt+" ":Ye=vt}let ht=D+De+Ye;ge.value=ht,so&&clearTimeout(so),(De||Ye)&&(so=window.setTimeout(()=>{let dt=ge.value.trim();dt&&zr&&un&&(_n(),ge.value="",ge.style.height="auto",I.sendMessage(dt,{viaVoice:!0}))},C))},zr.onerror=Le=>{Le.error!=="no-speech"&&_n()},zr.onend=()=>{if(un){let Le=ge.value.trim();Le&&Le!==D.trim()&&(ge.value="",ge.style.height="auto",I.sendMessage(Le,{viaVoice:!0})),_n()}};try{if(zr.start(),un=!0,Lt.active=!0,c!=="system"&&(Lt.manuallyDeactivated=!1),An(c),tn(),G){let Le=(j=n.voiceRecognition)!=null?j:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(F=Le.iconName)!=null?F:"mic",iconSize:parseFloat((ie=(we=Le.iconSize)!=null?we:(We=n.sendButton)==null?void 0:We.size)!=null?ie:"40")||24};let De=Le.recordingBackgroundColor,Ye=Le.recordingIconColor,ht=Le.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Ye!=null?Ye:"var(--persona-voice-recording-indicator, #ffffff)",Ye){let dt=G.querySelector("svg");dt&&dt.setAttribute("stroke",Ye)}ht&&(G.style.borderColor=ht),G.setAttribute("aria-label","Stop voice recognition")}}catch{_n("system")}},_n=(c="user")=>{if(un){if(un=!1,so&&(clearTimeout(so),so=null),zr){try{zr.stop()}catch{}zr=null}if(Lt.active=!1,An(c),tn(),G){if(G.classList.remove("persona-voice-recording"),yt){G.style.backgroundColor=yt.backgroundColor,G.style.color=yt.color,G.style.borderColor=yt.borderColor;let g=G.querySelector("svg");g&&g.setAttribute("stroke",yt.color||"currentColor"),yt=null}G.setAttribute("aria-label","Start voice recognition")}}},xi=(c,g)=>{var wt,vt,qe,$e,nt,H,Oe,Je;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((wt=c==null?void 0:c.provider)==null?void 0:wt.type)==="runtype";if(!(b||C))return null;let $=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let j=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",F=(qe=g==null?void 0:g.size)!=null?qe:"40px",We=($e=c==null?void 0:c.iconSize)!=null?$e:F,we=parseFloat(We)||24,ie=(nt=c==null?void 0:c.backgroundColor)!=null?nt:g==null?void 0:g.backgroundColor,Le=(H=c==null?void 0:c.iconColor)!=null?H:g==null?void 0:g.textColor;U.style.width=We,U.style.height=We,U.style.minWidth=We,U.style.minHeight=We,U.style.fontSize="18px",U.style.lineHeight="1",Le?U.style.color=Le:U.style.color="var(--persona-text, #111827)";let Ye=Ie(j,we,Le||"currentColor",1.5);Ye?U.appendChild(Ye):U.textContent="\u{1F3A4}",ie?U.style.backgroundColor=ie:U.style.backgroundColor="",c!=null&&c.borderWidth&&(U.style.borderWidth=c.borderWidth,U.style.borderStyle="solid"),c!=null&&c.borderColor&&(U.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(U.style.paddingLeft=c.paddingX,U.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(U.style.paddingTop=c.paddingY,U.style.paddingBottom=c.paddingY),$.appendChild(U);let ht=(Oe=c==null?void 0:c.tooltipText)!=null?Oe:"Start voice recognition";if(((Je=c==null?void 0:c.showTooltip)!=null?Je:!1)&&ht){let it=v("div","persona-send-button-tooltip");it.textContent=ht,$.appendChild(it)}return{micButton:U,micButtonWrapper:$}},Eo=()=>{var g,b,C,D,$;if(!G||yt)return;let c=(g=n.voiceRecognition)!=null?g:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat(($=(D=c.iconSize)!=null?D:(C=n.sendButton)==null?void 0:C.size)!=null?$:"40")||24}},st=(c,g)=>{var $,U,j,F,We;if(!G)return;let b=G.querySelector("svg");b&&b.remove();let C=(We=yt==null?void 0:yt.iconSize)!=null?We:parseFloat((F=(j=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?j:(U=n.sendButton)==null?void 0:U.size)!=null?F:"40")||24,D=Ie(c,C,g,1.5);D&&G.appendChild(D)},L=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},q=()=>{var D;if(!G)return;Eo();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,C=c.recordingBorderColor;if(L(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let $=G.querySelector("svg");$&&$.setAttribute("stroke",b)}C&&(G.style.borderColor=C),G.setAttribute("aria-label","Stop voice recognition")},O=()=>{var j,F,We,we,ie,Le,De,Ye;if(!G)return;Eo();let c=(j=n.voiceRecognition)!=null?j:{},g=I.getVoiceInterruptionMode(),b=(F=c.processingIconName)!=null?F:"loader",C=(we=(We=c.processingIconColor)!=null?We:yt==null?void 0:yt.color)!=null?we:"",D=(Le=(ie=c.processingBackgroundColor)!=null?ie:yt==null?void 0:yt.backgroundColor)!=null?Le:"",$=(Ye=(De=c.processingBorderColor)!=null?De:yt==null?void 0:yt.borderColor)!=null?Ye:"";L(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=D,G.style.borderColor=$;let U=C||"currentColor";G.style.color=U,st(b,U),G.setAttribute("aria-label","Processing voice input"),g==="none"&&(G.style.cursor="default")},se=()=>{var We,we,ie,Le,De,Ye,ht,dt,wt,vt,qe,$e;if(!G)return;Eo();let c=(We=n.voiceRecognition)!=null?We:{},g=I.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(we=c.speakingIconName)!=null?we:b,D=(Ye=c.speakingIconColor)!=null?Ye:g==="barge-in"?(Le=(ie=c.recordingIconColor)!=null?ie:yt==null?void 0:yt.color)!=null?Le:"":(De=yt==null?void 0:yt.color)!=null?De:"",$=(wt=c.speakingBackgroundColor)!=null?wt:g==="barge-in"?(ht=c.recordingBackgroundColor)!=null?ht:"var(--persona-voice-recording-bg, #ef4444)":(dt=yt==null?void 0:yt.backgroundColor)!=null?dt:"",U=($e=c.speakingBorderColor)!=null?$e:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(qe=yt==null?void 0:yt.borderColor)!=null?qe:"";L(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=$,G.style.borderColor=U;let j=D||"currentColor";G.style.color=j,st(C,j);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",F),g==="none"&&(G.style.cursor="default"),g==="barge-in"&&G.classList.add("persona-voice-recording")},Y=()=>{var c,g,b;G&&(L(),yt&&(G.style.backgroundColor=(c=yt.backgroundColor)!=null?c:"",G.style.color=(g=yt.color)!=null?g:"",G.style.borderColor=(b=yt.borderColor)!=null?b:"",st(yt.iconName,yt.color||"currentColor"),yt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},te=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=I.getVoiceStatus(),C=I.getVoiceInterruptionMode();if(C==="none"&&(b==="processing"||b==="speaking"))return;if(C==="cancel"&&(b==="processing"||b==="speaking")){I.stopVoicePlayback();return}if(I.isBargeInActive()){I.stopVoicePlayback(),I.deactivateBargeIn().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),Y()});return}I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),Lt.manuallyDeactivated=!I.isVoiceActive(),tn(),An("user"),I.isVoiceActive()?q():Y()});return}if(un){let b=ge.value.trim();Lt.manuallyDeactivated=!0,tn(),_n("user"),b&&(ge.value="",ge.style.height="auto",I.sendMessage(b))}else Lt.manuallyDeactivated=!1,tn(),zo("user")};dr=te,G&&(G.addEventListener("click",te),Pt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(I.isVoiceActive()&&I.toggleVoice(),Y()):_n("system"),G&&G.removeEventListener("click",te)}));let ct=s.on("assistant:complete",()=>{Qa&&(Lt.active||Lt.manuallyDeactivated||Qa==="assistant"&&!Lt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Lt.active&&!Lt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),An("auto"),I.isVoiceActive()&&q()}):zo("auto"))},600))});Pt.push(ct);let et=s.on("action:resubmit",()=>{setTimeout(()=>{I&&!I.isStreaming()&&I.continueConversation()},100)});Pt.push(et);let mt=()=>{Kt(!B,"user")},Fe=null,lt=null;if(M&&!W()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Vs(n,mt).element,onToggle:mt});g&&(lt=g)}lt||(Fe=Vs(n,mt))}Fe?t.appendChild(Fe.element):lt&&t.appendChild(lt),Mo(),Wn.render(n.suggestionChips,I,ge,void 0,n.suggestionChipsConfig),ns(),ya(I.isStreaming()),Ao(!0),oi(),E&&(!M||W()?setTimeout(()=>ba(),0):B&&setTimeout(()=>ba(),200));let jt=()=>{var F,We,we,ie,Le,De,Ye,ht,dt,wt,vt,qe,$e,nt,H,Oe,Je,it,Pe,zt,bt,yr;if(W()){Et(),Mo();return}let c=Ar(n),g=(We=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?We:!1,b=c||g||((ie=(we=n.launcher)==null?void 0:we.fullHeight)!=null?ie:!1),C=(Le=t.ownerDocument.defaultView)!=null?Le:window,D=(Ye=(De=n.launcher)==null?void 0:De.mobileFullscreen)!=null?Ye:!0,$=(dt=(ht=n.launcher)==null?void 0:ht.mobileBreakpoint)!=null?dt:640,U=C.innerWidth<=$,j=D&&U&&M;try{if(j){Rn(),Io(t,n);return}if(T&&(T=!1,Rn(),Io(t,n)),!M&&!c){he.style.height="",he.style.width="";return}if(!g&&!c){let Wr=(vt=(wt=n==null?void 0:n.launcher)==null?void 0:wt.width)!=null?vt:n==null?void 0:n.launcherWidth,Gt=Wr!=null?Wr:yn;he.style.width=Gt,he.style.maxWidth=Gt}if(qn(),!b){let Wr=C.innerHeight,Gt=64,jr=($e=(qe=n.launcher)==null?void 0:qe.heightOffset)!=null?$e:0,Br=Math.max(200,Wr-Gt),pt=Math.min(640,Br),Ct=Math.max(200,pt-jr);he.style.height=`${Ct}px`}}finally{if(Et(),Mo(),B&&M){let Gt=((nt=t.ownerDocument.defaultView)!=null?nt:window).innerWidth<=((Oe=(H=n.launcher)==null?void 0:H.mobileBreakpoint)!=null?Oe:640),jr=(it=(Je=n.launcher)==null?void 0:Je.sidebarMode)!=null?it:!1,Br=(zt=(Pe=n.launcher)==null?void 0:Pe.mobileFullscreen)!=null?zt:!0,pt=Ar(n)&&Br&&Gt,Ct=jr||Br&&Gt&&M||pt;if(Ct&&!hr){let Gr=t.getRootNode(),Fr=Gr instanceof ShadowRoot?Gr.host:t.closest(".persona-host");Fr&&!gr&&(gr=Np(Fr,(yr=(bt=n.launcher)==null?void 0:bt.zIndex)!=null?yr:qr)),hr=Fp(t.ownerDocument)}else Ct||(gr==null||gr(),gr=null,hr==null||hr(),hr=null)}}};jt();let Sr=(wf=t.ownerDocument.defaultView)!=null?wf:window;if(Sr.addEventListener("resize",jt),Pt.push(()=>Sr.removeEventListener("resize",jt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Et()});c.observe(Xe),Pt.push(()=>c.disconnect())}Dn=J.scrollTop;let _t=J.scrollHeight,qt=()=>{let c=J.scrollTop,g=J.scrollHeight,b=g<_t;_t=g;let{action:C,nextLastScrollTop:D}=Al({following:Hn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:_s(J,Ja),userScrollThreshold:ri,isAutoScrolling:ro||Fo||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=D,C==="resume"){Co();return}C==="pause"&&Za()};J.addEventListener("scroll",qt,{passive:!0}),Pt.push(()=>J.removeEventListener("scroll",qt));let Tr=c=>{let g=Sl({following:Hn.isFollowing(),deltaY:c.deltaY,nearBottom:_s(J,Ja),resumeWhenNearBottom:!0});g==="pause"?Za():g==="resume"&&Co()};J.addEventListener("wheel",Tr,{passive:!0}),Pt.push(()=>J.removeEventListener("wheel",Tr)),Ot.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,Dn=J.scrollTop,Co(),Ao(!0)}),Pt.push(()=>Ot.remove()),Pt.push(()=>{Ya()});let Nr=()=>{Q&&(cn&&(Q.removeEventListener("click",cn),cn=null),R()?(Q.style.display="",cn=()=>{Kt(!1,"user")},Q.addEventListener("click",cn)):Q.style.display="none")};Nr(),(()=>{let{clearChatButton:c}=Ne;c&&c.addEventListener("click",()=>{I.clearMessages(),Bn.clear(),Co(),_o(Ne.composerOverlay);try{localStorage.removeItem(Ga),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(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(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},S.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),ae==null||ae.update()})})(),Ae&&Ae.addEventListener("submit",as),ge==null||ge.addEventListener("keydown",is),ge==null||ge.addEventListener("input",ss),ge==null||ge.addEventListener("paste",ds);let xr=(vf=t.ownerDocument)!=null?vf:document;xr.addEventListener("keydown",ls,!0);let Sn="persona-attachment-drop-active",ps=0,nd=()=>{ps=0,me.classList.remove(Sn)},Ca=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&ft!==null},Mu=c=>{!Yl(c.dataTransfer)||!Ca()||(ps++,ps===1&&me.classList.add(Sn))},Eu=c=>{!Yl(c.dataTransfer)||!Ca()||(ps--,ps<=0&&nd())},Lu=c=>{!Yl(c.dataTransfer)||!Ca()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Pu=c=>{var b;if(!Yl(c.dataTransfer)||!Ca())return;c.preventDefault(),c.stopPropagation(),nd();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&ft.handleFiles(g)},Lo=!0;me.addEventListener("dragenter",Mu,Lo),me.addEventListener("dragleave",Eu,Lo),t.addEventListener("dragover",Lu,Lo),t.addEventListener("drop",Pu,Lo);let yi=t.ownerDocument,Iu=c=>{Ca()&&c.preventDefault()},Ru=c=>{Ca()&&c.preventDefault()};yi.addEventListener("dragover",Iu),yi.addEventListener("drop",Ru),Pt.push(()=>{Ae&&Ae.removeEventListener("submit",as),ge==null||ge.removeEventListener("keydown",is),ge==null||ge.removeEventListener("input",ss),ge==null||ge.removeEventListener("paste",ds),xr.removeEventListener("keydown",ls,!0)}),Pt.push(()=>{me.removeEventListener("dragenter",Mu,Lo),me.removeEventListener("dragleave",Eu,Lo),t.removeEventListener("dragover",Lu,Lo),t.removeEventListener("drop",Pu,Lo),yi.removeEventListener("dragover",Iu),yi.removeEventListener("drop",Ru),nd()}),Pt.push(()=>{I.cancel()}),Fe?Pt.push(()=>{Fe==null||Fe.destroy()}):lt&&Pt.push(()=>{lt==null||lt.remove()});let vr={update(c){var Cr,jn,lo,bi,wi,vi,Xo,Ci,us,Ef,Lf,Pf,If,Rf,Wf,Bf,Hf,Df,Of,_f,Nf,Ff,$f,Uf,qf,zf,Vf,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,wm,vm,Cm,Am,Sm,Tm,km,Mm,Em,Lm,Pm,Im,Rm,Wm,Bm,Hm,Dm,Om,_m,Nm,Fm,$m,Um,qm,zm,Vm,jm,Gm,Km,Xm,Jm,Qm,Ym,Zm,eg,tg,rg,ng,og,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,wg,vg,Cg,Ag;let g=n.toolCall,b=n.messageActions,C=(Cr=n.layout)==null?void 0:Cr.messages,D=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,j=(jn=n.features)==null?void 0:jn.showReasoning,F=(lo=n.features)==null?void 0:lo.showToolCalls,We=(bi=n.features)==null?void 0:bi.toolCallDisplay,we=(wi=n.features)==null?void 0:wi.reasoningDisplay;n={...n,...c},Rn(),Io(t,n),ql(t,n),zl(t,n),ln(),n.colorScheme!==D&&vo();let ie=Qs.getForInstance(n.plugins);o.length=0,o.push(...ie),M=(Xo=(vi=n.launcher)==null?void 0:vi.enabled)!=null?Xo:!0,k=(us=(Ci=n.launcher)==null?void 0:Ci.autoExpand)!=null?us:!1,Qe=(Lf=(Ef=n.features)==null?void 0:Ef.showReasoning)!=null?Lf:!0,je=(If=(Pf=n.features)==null?void 0:Pf.showToolCalls)!=null?If:!0,Ee=(Wf=(Rf=n.features)==null?void 0:Rf.scrollToBottom)!=null?Wf:{},sr(),oo();let Le=ve;if(ve=(Hf=(Bf=n.features)==null?void 0:Bf.showEventStreamToggle)!=null?Hf:!1,ve&&!Le){if(K||(X=new Xs(_e),K=new Ks(Ue,X),Te=Te!=null?Te:new Js,X.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),I.setSSEEventCallback((ne,Dt)=>{var rr;(rr=n.onSSEEvent)==null||rr.call(n,ne,Dt),Te==null||Te.processEvent(ne,Dt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Dt)})})),!xt&&Ve){let ne=(Of=(Df=n.features)==null?void 0:Df.eventStream)==null?void 0:Of.classNames,Dt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");xt=v("button",Dt),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let rr=Ie("activity","18px","currentColor",1.5);rr&&xt.appendChild(rr);let At=Ne.clearChatButtonWrapper,Ut=Ne.closeButtonWrapper,kr=At||Ut;kr&&kr.parentNode===Ve?Ve.insertBefore(xt,kr):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}}else!ve&&Le&&(Or(),xt&&(xt.remove(),xt=null),K==null||K.clear(),X==null||X.destroy(),K=null,X=null,Te==null||Te.reset(),Te=null);if(((_f=n.launcher)==null?void 0:_f.enabled)===!1&&Fe&&(Fe.destroy(),Fe=null),((Nf=n.launcher)==null?void 0:Nf.enabled)===!1&<&&(lt.remove(),lt=null),((Ff=n.launcher)==null?void 0:Ff.enabled)!==!1&&!Fe&&!lt){let ne=o.find(Dt=>Dt.renderLauncher);if(ne!=null&&ne.renderLauncher){let Dt=ne.renderLauncher({config:n,defaultRenderer:()=>Vs(n,mt).element,onToggle:mt});Dt&&(lt=Dt,t.appendChild(lt))}lt||(Fe=Vs(n,mt),t.appendChild(Fe.element))}Fe&&Fe.update(n),Me&&(($f=n.launcher)==null?void 0:$f.title)!==void 0&&(Me.textContent=n.launcher.title),He&&((Uf=n.launcher)==null?void 0:Uf.subtitle)!==void 0&&(He.textContent=n.launcher.subtitle);let De=(qf=n.layout)==null?void 0:qf.header;if((De==null?void 0:De.layout)!==x&&Ve){let ne=De?Oa(n,De,{showClose:R(),onClose:()=>Kt(!1,"user")}):go({config:n,showClose:R(),onClose:()=>Kt(!1,"user")});Ve.replaceWith(ne.header),Ve=ne.header,N=ne.iconHolder,Me=ne.headerTitle,He=ne.headerSubtitle,Q=ne.closeButton,x=De==null?void 0:De.layout}else if(De&&(N&&(N.style.display=De.showIcon===!1?"none":""),Me&&(Me.style.display=De.showTitle===!1?"none":""),He&&(He.style.display=De.showSubtitle===!1?"none":""),Q&&(Q.style.display=De.showCloseButton===!1?"none":""),Ne.clearChatButtonWrapper)){let ne=De.showClearChat;if(ne!==void 0){Ne.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Dt}=Ne;Dt&&!Dt.classList.contains("persona-absolute")&&(ne?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"))}}let ht=((zf=n.layout)==null?void 0:zf.showHeader)!==!1;Ve&&(Ve.style.display=ht?"":"none");let dt=((Vf=n.layout)==null?void 0:Vf.showFooter)!==!1;Xe&&(Xe.style.display=dt?"":"none"),Et(),oo(),M!==w?M?Kt(k,"auto"):(B=!0,Mo()):k!==h&&Kt(k,"auto"),h=k,w=M,jt(),Nr();let qe=JSON.stringify(c.toolCall)!==JSON.stringify(g),$e=JSON.stringify(n.messageActions)!==JSON.stringify(b),nt=JSON.stringify((jf=n.layout)==null?void 0:jf.messages)!==JSON.stringify(C),H=((Gf=n.loadingIndicator)==null?void 0:Gf.render)!==($==null?void 0:$.render)||((Kf=n.loadingIndicator)==null?void 0:Kf.renderIdle)!==($==null?void 0:$.renderIdle)||((Xf=n.loadingIndicator)==null?void 0:Xf.showBubble)!==($==null?void 0:$.showBubble),Oe=n.iterationDisplay!==U,Je=((Qf=(Jf=n.features)==null?void 0:Jf.showReasoning)!=null?Qf:!0)!==(j!=null?j:!0)||((Zf=(Yf=n.features)==null?void 0:Yf.showToolCalls)!=null?Zf:!0)!==(F!=null?F:!0)||JSON.stringify((em=n.features)==null?void 0:em.toolCallDisplay)!==JSON.stringify(We)||JSON.stringify((tm=n.features)==null?void 0:tm.reasoningDisplay)!==JSON.stringify(we);(qe||$e||nt||H||Oe||Je)&&I&&(Xa++,Uo(ze,I.getMessages(),be));let Pe=(rm=n.launcher)!=null?rm:{},zt=(nm=Pe.headerIconHidden)!=null?nm:!1,bt=(am=(om=n.layout)==null?void 0:om.header)==null?void 0:am.showIcon,yr=zt||bt===!1,Wr=Pe.headerIconName,Gt=(sm=Pe.headerIconSize)!=null?sm:"48px";if(N){let ne=me.querySelector(".persona-border-b-persona-divider"),Dt=ne==null?void 0:ne.querySelector(".persona-flex-col");if(yr)N.style.display="none",ne&&Dt&&!ne.contains(Dt)&&ne.insertBefore(Dt,ne.firstChild);else{if(N.style.display="",N.style.height=Gt,N.style.width=Gt,ne&&Dt&&(ne.contains(N)?N.nextSibling!==Dt&&(N.remove(),ne.insertBefore(N,Dt)):ne.insertBefore(N,Dt)),Wr){let At=parseFloat(Gt)||24,Ut=Ie(Wr,At*.6,"#ffffff",2);Ut?N.replaceChildren(Ut):N.textContent=(im=Pe.agentIconText)!=null?im:"\u{1F4AC}"}else if(Pe.iconUrl){let At=N.querySelector("img");if(At)At.src=Pe.iconUrl,At.style.height=Gt,At.style.width=Gt;else{let Ut=document.createElement("img");Ut.src=Pe.iconUrl,Ut.alt="",Ut.className="persona-rounded-xl persona-object-cover",Ut.style.height=Gt,Ut.style.width=Gt,N.replaceChildren(Ut)}}else{let At=N.querySelector("svg"),Ut=N.querySelector("img");(At||Ut)&&N.replaceChildren(),N.textContent=(lm=Pe.agentIconText)!=null?lm:"\u{1F4AC}"}let rr=N.querySelector("img");rr&&(rr.style.height=Gt,rr.style.width=Gt)}}let jr=(cm=(dm=n.layout)==null?void 0:dm.header)==null?void 0:cm.showTitle,Br=(um=(pm=n.layout)==null?void 0:pm.header)==null?void 0:um.showSubtitle;if(Me&&(Me.style.display=jr===!1?"none":""),He&&(He.style.display=Br===!1?"none":""),Q){((mm=(fm=n.layout)==null?void 0:fm.header)==null?void 0:mm.showCloseButton)===!1?Q.style.display="none":Q.style.display="";let Dt=(gm=Pe.closeButtonSize)!=null?gm:"32px",rr=(hm=Pe.closeButtonPlacement)!=null?hm:"inline";Q.style.height=Dt,Q.style.width=Dt;let{closeButtonWrapper:At}=Ne,Ut=rr==="top-right",kr=At==null?void 0:At.classList.contains("persona-absolute");if(At&&Ut!==kr)if(At.remove(),Ut)At.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(At);else{let Tt=(ym=(xm=Pe.clearChat)==null?void 0:xm.placement)!=null?ym:"inline",Mr=(wm=(bm=Pe.clearChat)==null?void 0:bm.enabled)!=null?wm:!0;At.className=Mr&&Tt==="inline"?"":"persona-ml-auto";let an=me.querySelector(".persona-border-b-persona-divider");an&&an.appendChild(At)}if(Q.style.color=Pe.closeButtonColor||en.actionIconColor,Pe.closeButtonBackgroundColor?(Q.style.backgroundColor=Pe.closeButtonBackgroundColor,Q.classList.remove("hover:persona-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Tt=Pe.closeButtonBorderWidth||"0px",Mr=Pe.closeButtonBorderColor||"transparent";Q.style.border=`${Tt} solid ${Mr}`,Q.classList.remove("persona-border-none")}else Q.style.border="",Q.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Q.style.borderRadius=Pe.closeButtonBorderRadius,Q.classList.remove("persona-rounded-full")):(Q.style.borderRadius="",Q.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Q.style.paddingLeft=Pe.closeButtonPaddingX,Q.style.paddingRight=Pe.closeButtonPaddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),Pe.closeButtonPaddingY?(Q.style.paddingTop=Pe.closeButtonPaddingY,Q.style.paddingBottom=Pe.closeButtonPaddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let $r=(vm=Pe.closeButtonIconName)!=null?vm:"x",Nn=(Cm=Pe.closeButtonIconText)!=null?Cm:"\xD7";Q.innerHTML="";let Xr=Ie($r,"28px","currentColor",1);Xr?Q.appendChild(Xr):Q.textContent=Nn;let br=(Am=Pe.closeButtonTooltipText)!=null?Am:"Close chat",mn=(Sm=Pe.closeButtonShowTooltip)!=null?Sm:!0;if(Q.setAttribute("aria-label",br),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),mn&&br)){let Tt=null,Mr=()=>{if(Tt||!Q)return;let Jo=Q.ownerDocument,fs=Jo.body;if(!fs)return;Tt=Qn(Jo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let ms=Qn(Jo,"div");ms.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(ms);let Qo=Q.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Ro),Tt.style.left=`${Qo.left+Qo.width/2}px`,Tt.style.top=`${Qo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",fs.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};At.addEventListener("mouseenter",Mr),At.addEventListener("mouseleave",an),Q.addEventListener("focus",Mr),Q.addEventListener("blur",an),At._cleanupTooltip=()=>{an(),At&&(At.removeEventListener("mouseenter",Mr),At.removeEventListener("mouseleave",an)),Q&&(Q.removeEventListener("focus",Mr),Q.removeEventListener("blur",an))}}}let{clearChatButton:pt,clearChatButtonWrapper:Ct}=Ne;if(pt){let ne=(Tm=Pe.clearChat)!=null?Tm:{},Dt=(km=ne.enabled)!=null?km:!0,rr=(Em=(Mm=n.layout)==null?void 0:Mm.header)==null?void 0:Em.showClearChat,At=rr!==void 0?rr:Dt,Ut=(Lm=ne.placement)!=null?Lm:"inline";if(Ct){Ct.style.display=At?"":"none";let{closeButtonWrapper:kr}=Ne;!W()&&kr&&!kr.classList.contains("persona-absolute")&&(At?kr.classList.remove("persona-ml-auto"):kr.classList.add("persona-ml-auto"));let $r=Ut==="top-right",Nn=Ct.classList.contains("persona-absolute");if(!W()&&$r!==Nn&&At){if(Ct.remove(),$r)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",me.style.position="relative",me.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let br=me.querySelector(".persona-border-b-persona-divider"),mn=Ne.closeButtonWrapper;br&&mn&&mn.parentElement===br?br.insertBefore(Ct,mn):br&&br.appendChild(Ct)}let Xr=Ne.closeButtonWrapper;Xr&&!Xr.classList.contains("persona-absolute")&&($r?Xr.classList.add("persona-ml-auto"):Xr.classList.remove("persona-ml-auto"))}}if(At){if(!W()){let Tt=(Pm=ne.size)!=null?Pm:"32px";pt.style.height=Tt,pt.style.width=Tt}let kr=(Im=ne.iconName)!=null?Im:"refresh-cw",$r=(Rm=ne.iconColor)!=null?Rm:"";pt.style.color=$r||en.actionIconColor,pt.innerHTML="";let Nn=W()?"14px":"20px",Xr=Ie(kr,Nn,"currentColor",2);if(Xr&&pt.appendChild(Xr),ne.backgroundColor?(pt.style.backgroundColor=ne.backgroundColor,pt.classList.remove("hover:persona-bg-gray-100")):(pt.style.backgroundColor="",pt.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let Tt=ne.borderWidth||"0px",Mr=ne.borderColor||"transparent";pt.style.border=`${Tt} solid ${Mr}`,pt.classList.remove("persona-border-none")}else pt.style.border="",pt.classList.add("persona-border-none");ne.borderRadius?(pt.style.borderRadius=ne.borderRadius,pt.classList.remove("persona-rounded-full")):(pt.style.borderRadius="",pt.classList.add("persona-rounded-full")),ne.paddingX?(pt.style.paddingLeft=ne.paddingX,pt.style.paddingRight=ne.paddingX):(pt.style.paddingLeft="",pt.style.paddingRight=""),ne.paddingY?(pt.style.paddingTop=ne.paddingY,pt.style.paddingBottom=ne.paddingY):(pt.style.paddingTop="",pt.style.paddingBottom="");let br=(Wm=ne.tooltipText)!=null?Wm:"Clear chat",mn=(Bm=ne.showTooltip)!=null?Bm:!0;if(pt.setAttribute("aria-label",br),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),mn&&br)){let Tt=null,Mr=()=>{if(Tt||!pt)return;let Jo=pt.ownerDocument,fs=Jo.body;if(!fs)return;Tt=Qn(Jo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let ms=Qn(Jo,"div");ms.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(ms);let Qo=pt.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Ro),Tt.style.left=`${Qo.left+Qo.width/2}px`,Tt.style.top=`${Qo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",fs.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};Ct.addEventListener("mouseenter",Mr),Ct.addEventListener("mouseleave",an),pt.addEventListener("focus",Mr),pt.addEventListener("blur",an),Ct._cleanupTooltip=()=>{an(),Ct&&(Ct.removeEventListener("mouseenter",Mr),Ct.removeEventListener("mouseleave",an)),pt&&(pt.removeEventListener("focus",Mr),pt.removeEventListener("blur",an))}}}}let Gr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ys],Fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ga.message,ga.messageAndClick];S=Zs({parsers:Gr,handlers:Fr,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),be=Yx(n,S,oe),I.updateConfig(n),Uo(ze,I.getMessages(),be),Wn.render(n.suggestionChips,I,ge,void 0,n.suggestionChipsConfig),ns(),ya(I.isStreaming());let Vo=((Hm=n.voiceRecognition)==null?void 0:Hm.enabled)===!0,jo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Go=((Om=(Dm=n.voiceRecognition)==null?void 0:Dm.provider)==null?void 0:Om.type)==="runtype";if(Vo&&(jo||Go))if(!G||!Jt){let ne=xi(n.voiceRecognition,n.sendButton);ne&&(G=ne.micButton,Jt=ne.micButtonWrapper,kt.insertBefore(Jt,Re),G.addEventListener("click",te),G.disabled=I.isStreaming())}else{let ne=(_m=n.voiceRecognition)!=null?_m:{},Dt=(Nm=n.sendButton)!=null?Nm:{},rr=(Fm=ne.iconName)!=null?Fm:"mic",At=($m=Dt.size)!=null?$m:"40px",Ut=(Um=ne.iconSize)!=null?Um:At,kr=parseFloat(Ut)||24;G.style.width=Ut,G.style.height=Ut,G.style.minWidth=Ut,G.style.minHeight=Ut;let $r=(zm=(qm=ne.iconColor)!=null?qm:Dt.textColor)!=null?zm:"currentColor";G.innerHTML="";let Nn=Ie(rr,kr,$r,2);Nn?G.appendChild(Nn):G.textContent="\u{1F3A4}";let Xr=(Vm=ne.backgroundColor)!=null?Vm:Dt.backgroundColor;Xr?G.style.backgroundColor=Xr:G.style.backgroundColor="",$r?G.style.color=$r:G.style.color="var(--persona-text, #111827)",ne.borderWidth?(G.style.borderWidth=ne.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ne.borderColor?G.style.borderColor=ne.borderColor:G.style.borderColor="",ne.paddingX?(G.style.paddingLeft=ne.paddingX,G.style.paddingRight=ne.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ne.paddingY?(G.style.paddingTop=ne.paddingY,G.style.paddingBottom=ne.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let br=Jt==null?void 0:Jt.querySelector(".persona-send-button-tooltip"),mn=(jm=ne.tooltipText)!=null?jm:"Start voice recognition";if(((Gm=ne.showTooltip)!=null?Gm:!1)&&mn)if(br)br.textContent=mn,br.style.display="";else{let Mr=document.createElement("div");Mr.className="persona-send-button-tooltip",Mr.textContent=mn,Jt==null||Jt.insertBefore(Mr,G)}else br&&(br.style.display="none");Jt.style.display="",G.disabled=I.isStreaming()}else G&&Jt&&(Jt.style.display="none",((Xm=(Km=n.voiceRecognition)==null?void 0:Km.provider)==null?void 0:Xm.type)==="runtype"?I.isVoiceActive()&&I.toggleVoice():un&&_n());if(((Jm=n.attachments)==null?void 0:Jm.enabled)===!0)if(!Nt||!at){let ne=(Qm=n.attachments)!=null?Qm:{},rr=(Zm=((Ym=n.sendButton)!=null?Ym:{}).size)!=null?Zm:"40px";ye||(ye=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ye.style.display="none",Ae.insertBefore(ye,ge)),de||(de=document.createElement("input"),de.type="file",de.accept=((eg=ne.allowedTypes)!=null?eg:mo).join(","),de.multiple=((tg=ne.maxFiles)!=null?tg:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Ae.insertBefore(de,ge)),Nt=v("div","persona-send-button-wrapper"),at=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),at.type="button",at.setAttribute("aria-label",(rg=ne.buttonTooltipText)!=null?rg:"Attach file");let At=(ng=ne.buttonIconName)!=null?ng:"paperclip",Ut=rr,kr=parseFloat(Ut)||40,$r=Math.round(kr*.6);at.style.width=Ut,at.style.height=Ut,at.style.minWidth=Ut,at.style.minHeight=Ut,at.style.fontSize="18px",at.style.lineHeight="1",at.style.backgroundColor="transparent",at.style.color="var(--persona-primary, #111827)",at.style.border="none",at.style.borderRadius="6px",at.style.transition="background-color 0.15s ease",at.addEventListener("mouseenter",()=>{at.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),at.addEventListener("mouseleave",()=>{at.style.backgroundColor="transparent"});let Nn=Ie(At,$r,"currentColor",1.5);Nn?at.appendChild(Nn):at.textContent="\u{1F4CE}",at.addEventListener("click",mn=>{mn.preventDefault(),de==null||de.click()}),Nt.appendChild(at);let Xr=(og=ne.buttonTooltipText)!=null?og:"Attach file",br=v("div","persona-send-button-tooltip");br.textContent=Xr,Nt.appendChild(br),ot.append(Nt),!ft&&de&&ye&&(ft=da.fromConfig(ne),ft.setPreviewsContainer(ye),de.addEventListener("change",async()=>{ft&&(de!=null&&de.files)&&(await ft.handleFileSelect(de.files),de.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(Zx(ne.dropOverlay))}else{Nt.style.display="";let ne=(ag=n.attachments)!=null?ag:{};de&&(de.accept=((sg=ne.allowedTypes)!=null?sg:mo).join(","),de.multiple=((ig=ne.maxFiles)!=null?ig:4)>1),ft&&ft.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else Nt&&(Nt.style.display="none"),ft&&ft.clearAttachments(),(lg=me.querySelector(".persona-attachment-drop-overlay"))==null||lg.remove();let cr=(dg=n.sendButton)!=null?dg:{},Ko=(cg=cr.useIcon)!=null?cg:!1,Po=(pg=cr.iconText)!=null?pg:"\u2191",Bt=cr.iconName,rn=(ug=cr.tooltipText)!=null?ug:"Send message",io=(fg=cr.showTooltip)!=null?fg:!1,Kr=(mg=cr.size)!=null?mg:"40px",nn=cr.backgroundColor,Yt=cr.textColor;if(Ko){if(z.style.width=Kr,z.style.height=Kr,z.style.minWidth=Kr,z.style.minHeight=Kr,z.style.fontSize="18px",z.style.lineHeight="1",z.innerHTML="",Yt?z.style.color=Yt:z.style.color="var(--persona-button-primary-fg, #ffffff)",Bt){let ne=parseFloat(Kr)||24,Dt=(Yt==null?void 0:Yt.trim())||"currentColor",rr=Ie(Bt,ne,Dt,2);rr?z.appendChild(rr):z.textContent=Po}else z.textContent=Po;z.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nn?(z.style.backgroundColor=nn,z.classList.remove("persona-bg-persona-primary")):(z.style.backgroundColor="",z.classList.add("persona-bg-persona-primary"))}else z.textContent=(hg=(gg=n.copy)==null?void 0:gg.sendButtonLabel)!=null?hg:"Send",z.style.width="",z.style.height="",z.style.minWidth="",z.style.minHeight="",z.style.fontSize="",z.style.lineHeight="",z.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?(z.style.backgroundColor=nn,z.classList.remove("persona-bg-persona-accent")):z.classList.add("persona-bg-persona-accent"),Yt?z.style.color=Yt:z.classList.add("persona-text-white");cr.borderWidth?(z.style.borderWidth=cr.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),cr.borderColor?z.style.borderColor=cr.borderColor:z.style.borderColor="",cr.paddingX?(z.style.paddingLeft=cr.paddingX,z.style.paddingRight=cr.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),cr.paddingY?(z.style.paddingTop=cr.paddingY,z.style.paddingBottom=cr.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let ir=Re==null?void 0:Re.querySelector(".persona-send-button-tooltip");if(io&&rn)if(ir)ir.textContent=rn,ir.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=rn,Re==null||Re.insertBefore(ne,z)}else ir&&(ir.style.display="none");let Zt=(vg=(xg=n.layout)==null?void 0:xg.contentMaxWidth)!=null?vg:W()?(wg=(bg=(yg=n.launcher)==null?void 0:yg.composerBar)==null?void 0:bg.contentMaxWidth)!=null?wg:"720px":void 0;Zt?(ze.style.maxWidth=Zt,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%",Ae&&(Ae.style.maxWidth=Zt,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Z&&(Z.style.maxWidth=Zt,Z.style.marginLeft="auto",Z.style.marginRight="auto")):(ze.style.maxWidth="",ze.style.marginLeft="",ze.style.marginRight="",ze.style.width="",Ae&&(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight=""),Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight=""));let pr=(Cg=n.statusIndicator)!=null?Cg:{},on=(Ag=pr.visible)!=null?Ag:!0;if(fe.style.display=on?"":"none",I){let ne=I.getStatus();ut(fe,(rr=>{var At,Ut,kr,$r;return rr==="idle"?(At=pr.idleText)!=null?At:Ur.idle:rr==="connecting"?(Ut=pr.connectingText)!=null?Ut:Ur.connecting:rr==="connected"?(kr=pr.connectedText)!=null?kr:Ur.connected:rr==="error"?($r=pr.errorText)!=null?$r:Ur.error:Ur[rr]})(ne),pr,ne)}fe.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=pr.align==="left"?"persona-text-left":pr.align==="center"?"persona-text-center":"persona-text-right";fe.classList.add(fn)},open(){R()&&Kt(!0,"api")},close(){R()&&Kt(!1,"api")},toggle(){R()&&Kt(!B,"api")},clearChat(){Se=!1,I.clearMessages(),Bn.clear(),Co();try{localStorage.removeItem(Ga),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(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={},S.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),ae==null||ae.update()},setMessage(c){return!ge||I.isStreaming()?!1:(!B&&R()&&Kt(!0,"system"),ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(I.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ge.value.trim();return g?(!B&&R()&&Kt(!0,"system"),ge.value="",ge.style.height="auto",I.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return I.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(I.isVoiceActive()||(!B&&R()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),I.toggleVoice().then(()=>{Lt.active=I.isVoiceActive(),An("user"),I.isVoiceActive()&&q()})),!0):un?!0:cs()?(!B&&R()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),zo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?I.isVoiceActive()?(I.toggleVoice().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),Y()}),!0):!1:un?(Lt.manuallyDeactivated=!0,tn(),_n("user"),!0):!1},injectMessage(c){return!B&&R()&&Kt(!0,"system"),I.injectMessage(c)},injectAssistantMessage(c){!B&&R()&&Kt(!0,"system");let g=I.injectAssistantMessage(c);return _&&(_=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{I&&!I.isStreaming()&&I.continueConversation()},100)),g},injectUserMessage(c){return!B&&R()&&Kt(!0,"system"),I.injectUserMessage(c)},injectSystemMessage(c){return!B&&R()&&Kt(!0,"system"),I.injectSystemMessage(c)},injectMessageBatch(c){return!B&&R()&&Kt(!0,"system"),I.injectMessageBatch(c)},injectComponentDirective(c){return!B&&R()&&Kt(!0,"system"),I.injectComponentDirective(c)},injectTestMessage(c){!B&&R()&&Kt(!0,"system"),I.injectTestEvent(c)},async connectStream(c,g){return I.connectStream(c,g)},__pushEventStreamEvent(c){K&&(Te==null||Te.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ve||!K||Lr()},hideEventStream(){xe&&Or()},isEventStreamVisible(){return xe},showArtifacts(){Ln(n)&&(Se=!1,ln(),ue==null||ue.setMobileOpen(!0))},hideArtifacts(){Ln(n)&&(Se=!0,ln())},upsertArtifact(c){return Ln(n)?(Se=!1,I.upsertArtifact(c)):null},selectArtifact(c){Ln(n)&&I.selectArtifact(c)},clearArtifacts(){Ln(n)&&I.clearArtifacts()},getArtifacts(){var c;return(c=I==null?void 0:I.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=I==null?void 0:I.getSelectedArtifactId())!=null?c:null},focusInput(){return M&&!B&&!W()||!ge?!1:(ge.focus(),!0)},async resolveApproval(c,g){let C=I.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===c});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${c}`);if(C.approval.toolType==="webmcp"){I.resolveWebMcpApproval(C.id,g);return}return I.resolveApproval(C.approval,g)},getMessages(){return I.getMessages()},getStatus(){return I.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return R()&&B},isVoiceActive(){return Lt.active},getState(){return{open:R()&&B,launcherEnabled:M,voiceActive:Lt.active,streaming:I.isStreaming()}},showCSATFeedback(c){!B&&R()&&Kt(!0,"system");let g=ze.querySelector(".persona-feedback-container");g&&g.remove();let b=Jl({onSubmit:async(C,D)=>{var $;I.isClientTokenMode()&&await I.submitCSATFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ze.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&R()&&Kt(!0,"system");let g=ze.querySelector(".persona-feedback-container");g&&g.remove();let b=Ql({onSubmit:async(C,D)=>{var $;I.isClientTokenMode()&&await I.submitNPSFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ze.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return I.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return I.submitNPSFeedback(c,g)},destroy(){Vn!=null&&(clearInterval(Vn),Vn=null),Pt.forEach(c=>c()),Ce.remove(),tt==null||tt.remove(),Fe==null||Fe.destroy(),lt==null||lt.remove(),cn&&Q.removeEventListener("click",cn)}};if((((Cf=r==null?void 0:r.debugTools)!=null?Cf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:vr,getMessages:vr.getMessages,getStatus:vr.getStatus,getMetadata:vr.getPersistentMetadata,updateMetadata:vr.updatePersistentMetadata,clearHistory:()=>vr.clearChat(),setVoiceActive:b=>b?vr.startVoiceRecognition():vr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Pt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.focusInput()};if(window.addEventListener("persona:focusInput",g),Pt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ve){let j=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.showEventStream()},F=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",F),Pt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",F)})}let b=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.showArtifacts()},C=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.hideArtifacts()},D=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&vr.upsertArtifact(F.artifact)},$=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&vr.selectArtifact(F.id)},U=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),Pt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Tn=cC(n.persistState);if(Tn&&R()){let c=pC(Tn.storage),g=`${Tn.keyPrefix}widget-open`,b=`${Tn.keyPrefix}widget-voice`,C=`${Tn.keyPrefix}widget-voice-mode`;if(c){let D=((Af=Tn.persist)==null?void 0:Af.openState)&&c.getItem(g)==="true",$=((Sf=Tn.persist)==null?void 0:Sf.voiceState)&&c.getItem(b)==="true",U=((Tf=Tn.persist)==null?void 0:Tf.voiceState)&&c.getItem(C)==="true";if(D&&setTimeout(()=>{vr.open(),setTimeout(()=>{var j;if($||U)vr.startVoiceRecognition();else if((j=Tn.persist)!=null&&j.focusInput){let F=t.querySelector("textarea");F&&F.focus()}},100)},0),(kf=Tn.persist)!=null&&kf.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Mf=Tn.persist)!=null&&Mf.voiceState&&(s.on("voice:state",j=>{c.setItem(b,j.active?"true":"false")}),s.on("user:message",j=>{c.setItem(C,j.viaVoice?"true":"false")})),Tn.clearOnChatClear){let j=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(C)},F=()=>j();window.addEventListener("persona:clear-chat",F),Pt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return p&&R()&&setTimeout(()=>{vr.open()},0),ao(),vr};var uC=(t,e)=>{let r=t.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,e*parseFloat(o[1])/100):420},ey=(t,e)=>{var n,o;let r=(o=(n=e==null?void 0:e.launcher)==null?void 0:n.enabled)!=null?o:!0;t.className="persona-host",t.style.height=r?"":"100%",t.style.display=r?"":"flex",t.style.flexDirection=r?"":"column",t.style.flex=r?"":"1 1 auto",t.style.minHeight=r?"":"0"},mu=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},ty=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.minWidth="",mu(t)},pu=t=>{t.style.transition=""},uu=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform=""},fu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},ed=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},fC=(t,e,r,n,o)=>{o?r.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(r,n),t.appendChild(e)):r.parentElement===e&&(e.replaceChildren(),t.appendChild(r),t.appendChild(n))},mC=(t,e,r,n,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==n&&a.replaceChildren(n,r):a.lastElementChild!==n&&a.replaceChildren(r,n)},ry=(t,e,r,n,o,s,a)=>{var y,A,S,M,k,E;let i=Mn(s),d=i.reveal==="push";fC(t,e,r,n,d),mC(t,e,r,n,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=t.ownerDocument.defaultView,p=(A=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?A:!0,m=(M=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?M:640,u=l!=null?l.innerWidth<=m:!1;if(p&&u&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),uu(e),pu(n),ty(n),fu(r),ed(o,n),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((E=(k=s==null?void 0:s.launcher)==null?void 0:k.zIndex)!=null?E:qr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),ty(n),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",uu(e),pu(n),fu(r),ed(o,n);let h=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",x=a?"translateX(0)":w;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=h,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"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",pu(n),mu(n),ed(o,n);let h=uC(i.width,t.clientWidth),w=Math.max(0,t.clientWidth),x=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${h}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${h}px)`;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${w+h}px`,e.style.transition=x,e.style.transform=T,r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",uu(e),mu(n),fu(r),ed(o,n);let h=i.reveal==="emerge";h?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let w=a?i.width:"0px",x=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${w}`,n.style.width=w,n.style.maxWidth=w,n.style.minWidth=w,n.style.minHeight="0",n.style.position="relative",n.style.overflow=h||T?"hidden":"visible",n.style.transition=x,h&&(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")}},gC=(t,e)=>{let r=t.ownerDocument.createElement("div");return ey(r,e),t.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){ey(r,n)},destroy(){r.remove()}}},hC=(t,e)=>{var k,E,h,w;let{ownerDocument:r}=t,n=t.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=t.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=r.createElement("div"),i=r.createElement("div"),d=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),m=(E=(k=e==null?void 0:e.launcher)==null?void 0:k.enabled)==null||E?(w=(h=e==null?void 0:e.launcher)==null?void 0:h.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),n.insertBefore(a,t),d.appendChild(t);let u=null,f=()=>{u==null||u.disconnect(),u=null},y=()=>{f(),Mn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{ry(a,i,d,l,p,e,m)}),u.observe(a))},A=()=>{ry(a,i,d,l,p,e,m),y()},S=a.ownerDocument.defaultView,M=()=>{A()};return S==null||S.addEventListener("resize",M),Mn(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),A(),{mode:"docked",host:p,shell:a,syncWidgetState(x){let T=x.launcherEnabled?x.open:!0;m!==T&&(m=T,A())},updateConfig(x){var T,W;e=x,((W=(T=e==null?void 0:e.launcher)==null?void 0:T.enabled)!=null?W:!0)===!1&&(m=!0),A()},destroy(){S==null||S.removeEventListener("resize",M),f(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(t,s):n.appendChild(t)),a.remove()}}},ei=(t,e)=>Ar(e)?hC(t,e):gC(t,e);var gu={},ny=!1,xC=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let e=document.querySelector(t);if(!e)throw new Error(`Chat widget target "${t}" was not found`);return e}return t},yC=()=>{try{if(typeof gu!="undefined"&&gu.url)return new URL("../widget.css",gu.url).href}catch{}return null},oy=(t,e)=>{let r=yC(),n=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let o=e.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);t.insertBefore(s,t.firstChild)};if(t instanceof ShadowRoot)if(r){let o=e.createElement("link");o.rel="stylesheet",o.href=r,o.setAttribute("data-persona","true"),t.insertBefore(o,t.firstChild)}else n();else if(!e.head.querySelector("link[data-persona]")&&r){let s=e.createElement("link");s.rel="stylesheet",s.href=r,s.setAttribute("data-persona","true"),e.head.appendChild(s)}},ay=t=>{let e=xC(t.target),r=t.useShadowDom===!0,n=e.ownerDocument,o=t.config,s=ei(e,o),a,i=[],d=(S,M)=>{var w,x;let E=!((x=(w=M==null?void 0:M.launcher)==null?void 0:w.enabled)!=null?x:!0)||Ar(M),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),E&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),r){let T=S.attachShadow({mode:"open"});T.appendChild(h),oy(T,n)}else S.appendChild(h),oy(S,n);return e.id&&h.setAttribute("data-persona-instance",e.id),h},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let S=d(s.host,o);a=Zl(S,o,{debugTools:t.debugTools}),p()},u=()=>{i.forEach(S=>S()),i=[],a.destroy()};m(),t.onChatReady?t.onChatReady():t.onReady&&(ny||(ny=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),t.onReady());let f=S=>{u(),s.destroy(),s=ei(e,S),o=S,m()},y={update(S){var x,T,W,R,B,_;let M={...o,...S,launcher:{...(x=o==null?void 0:o.launcher)!=null?x:{},...(T=S==null?void 0:S.launcher)!=null?T:{},dock:{...(R=(W=o==null?void 0:o.launcher)==null?void 0:W.dock)!=null?R:{},...(_=(B=S==null?void 0:S.launcher)==null?void 0:B.dock)!=null?_:{}}}},k=Ar(o),E=Ar(M),h=Bo(o),w=Bo(M);if(k!==E||h!==w){f(M);return}o=M,s.updateConfig(o),a.update(S),l()},destroy(){u(),s.destroy(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}},A=new Proxy(y,{get(S,M,k){if(M==="host")return s.host;if(M in S)return Reflect.get(S,M,k);let E=a[M];return typeof E=="function"?E.bind(a):E}});return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=A),A};var cy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),bC=new Set(["button","a","input","select","textarea","details","summary"]),wC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),hu=/\b(product|card|item|listing|result)\b/i,yu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,vC=3e3,CC=100;function py(t){let e=typeof t.className=="string"?t.className:"";if(hu.test(e)||t.id&&hu.test(t.id))return!0;for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];if(n.name.startsWith("data-")&&hu.test(n.value))return!0}return!1}function uy(t){var e;return yu.test(((e=t.textContent)!=null?e:"").trim())}function fy(t){var r;let e=t.querySelectorAll("a[href]");for(let n=0;n<e.length;n++){let o=(r=e[n].getAttribute("href"))!=null?r:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function AC(t){return!!t.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function sy(t){let e=t.match(yu);return e?e[0]:null}function iy(t){var n,o,s;let e=(n=t.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:t.querySelector("a[href]");if(e&&((o=e.textContent)!=null&&o.trim())){let a=e.getAttribute("href");return{title:e.textContent.trim(),href:a&&a!=="#"?a:null}}let r=t.querySelector("h1, h2, h3, h4, h5, h6");return(s=r==null?void 0:r.textContent)!=null&&s.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function SC(t){let e=[],r=n=>{let o=n.trim();o&&!e.includes(o)&&e.push(o)};return t.querySelectorAll("button").forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('[role="button"]').forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;r((o=n.value)!=null?o:"")}),e.slice(0,6)}var TC="commerce-card",kC="result-card";function ly(t){return!py(t)||!uy(t)||!fy(t)&&!AC(t)?0:5200}function dy(t){var n;return!py(t)||uy(t)||!fy(t)||((n=t.textContent)!=null?n:"").trim().length<20||!(!!t.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!t.querySelector(".snippet, .description, p"))?0:2800}var bu=[{id:TC,scoreElement(t){return ly(t)},shouldSuppressDescendant(t,e,r){if(e===t||!t.contains(e))return!1;if(r.interactivity==="static"){let n=r.text.trim();return!!(n.length===0||yu.test(n)&&n.length<32)}return!0},formatSummary(t,e){var d,l,p;if(ly(t)===0)return null;let{title:r,href:n}=iy(t),o=(p=(l=sy(((d=t.textContent)!=null?d:"").trim()))!=null?l:sy(e.text))!=null?p:"",s=SC(t);return[n&&r?`[${r}](${n})${o?` \u2014 ${o}`:""}`:r?`${r}${o?` \u2014 ${o}`:""}`:o||e.text.trim().slice(0,120),`selector: ${e.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
158
|
-
`)}},{id:
|
|
159
|
-
`)}}];function
|
|
157
|
+
`}if(!A&&!c){let Zt="max-height: -moz-available !important; max-height: stretch !important;",pr=g?"":"padding-top: 1.25em !important;",on=g?"":`z-index: ${(ir=(Yt=n.launcher)==null?void 0:Yt.zIndex)!=null?ir:qr} !important;`;Ce.style.cssText+=Zt+pr+on}H()};Rn(),Ro(t,n),zl(t,n),Vl(t,n);let Pt=[];Pt.push(()=>{document.removeEventListener("keydown",wn)});let gr=null,hr=null;Pt.push(()=>{gr==null||gr(),gr=null,hr==null||hr(),hr=null}),I&&Pt.push(()=>{I==null||I.disconnect(),I=null}),Pt.push(()=>{Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue==null||ue.element.style.removeProperty("width"),ue==null||ue.element.style.removeProperty("maxWidth")}),ve&&Pt.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),oe==null||oe.destroy(),oe=null,K==null||K.destroy(),K=null,X=null});let dn=null,vo=()=>{dn&&(dn(),dn=null),n.colorScheme==="auto"&&(dn=wl(()=>{Ro(t,n)}))};vo(),Pt.push(()=>{dn&&(dn(),dn=null)});let Cn=(hf=n.features)==null?void 0:hf.streamAnimation;if(Cn!=null&&Cn.type&&Cn.type!=="none"){let c=Us(Cn.type,Cn.plugins);c&&(_p(c,t),Pt.push(()=>cx(t)))}let Wn=Bx(Z),cn=null,W,pn=!1,Bn=ox(),to=new Map,zn=new Map,Ja=0,Hn=Al(),Dn=0,On=null,ro=!1,$o=!1,ni=4,Qa=24,oi=80,xa=new Map,Lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ya=(yf=(xf=n.voiceRecognition)==null?void 0:xf.autoResume)!=null?yf:!1,An=c=>{s.emit("voice:state",{active:Lt.active,source:c,timestamp:Date.now()})},tn=()=>{f(c=>({...c,voiceState:{active:Lt.active,timestamp:Date.now(),manuallyDeactivated:Lt.manuallyDeactivated}}))},ai=()=>{var A,D;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=pu(d.voiceState),g=!!c.active,b=Number((D=c.timestamp)!=null?D:0);Lt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<dC&&setTimeout(()=>{var $,U;Lt.active||(Lt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),An("restore"),W.isVoiceActive()&&q()}):Vo("restore"))},1e3)},si=()=>W?Zx(W.getMessages()).filter(c=>!c.__skipPersist):[];function ya(c){if(!(i!=null&&i.save))return;let b={messages:c?Zx(c):W?si():[],metadata:d,artifacts:ee.artifacts,selectedArtifactId:ee.selectedId};try{let A=i.save(b);A instanceof Promise&&A.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let no=null,ii=()=>Ce.querySelector("#persona-scroll-container")||J,Uo=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ro=!1},Za=()=>{On!==null&&(cancelAnimationFrame(On),On=null),$o=!1,Uo()},oo=()=>{if(!mr()||xe){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==me&&me.appendChild(Ot),Et();let c=Ns(J)>0;Ot.style.display=Hn.isFollowing()||!c?"none":""},es=()=>{Hn.pause()&&(Za(),oo())},Co=()=>{Hn.resume(),oo()},Ao=(c=!1)=>{Hn.isFollowing()&&(!c&&!pn||(On!==null&&(cancelAnimationFrame(On),On=null),$o=!0,On=requestAnimationFrame(()=>{On=null,$o=!1,Hn.isFollowing()&&li(ii(),c?220:140)})))},li=(c,g=500)=>{let b=c.scrollTop,A=Ns(c),D=A-b;if(Math.abs(D)<1){Dn=c.scrollTop;return}if(Math.abs(D)>=oi){Uo(),ro=!0,c.scrollTop=A,Dn=c.scrollTop,ro=!1;return}Uo();let $=performance.now();ro=!0;let U=F=>1-Math.pow(1-F,3),j=F=>{if(!Hn.isFollowing()){Uo();return}let We=Ns(c);We!==A&&(A=We,D=A-b);let we=F-$,se=Math.min(we/g,1),Le=U(se),De=b+D*Le;c.scrollTop=De,Dn=c.scrollTop,se<1?no=requestAnimationFrame(j):(c.scrollTop=A,Dn=c.scrollTop,no=null,ro=!1)};no=requestAnimationFrame(j)},di=c=>{let g=new Map;c.forEach(b=>{let A=xa.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!A&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(A!=null&&A.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(A?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),xa.clear(),g.forEach((b,A)=>{xa.set(A,b)})},qo=(c,g,b)=>{var ct,wt,vt,qe,$e,ot;let A=document.createElement("div"),$=(()=>{var Oe;let H=o.find(Qe=>Qe.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),U=(H,Oe)=>Oe==null?!1:typeof Oe=="string"?(H.textContent=Oe,!0):(H.appendChild(Oe),!0),j=new Set,F=new Set,We=o.some(H=>H.renderAskUserQuestion),we=[],se=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(H=>{var jr,Br,pt,Ct,Gr,Fr,jo,Go,Ko,Sa,Ta,cr,Xo,Po;j.add(H.id);let Oe=We&&ho(H),Qe=!Oe&&H.role==="assistant"&&!H.variant&&Le&&Xl(H);if(!Qe&&zn.has(H.id)){let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime"),zn.delete(H.id)}let lt=ho(H)?`:${(jr=H.agentMetadata)!=null&&jr.askUserQuestionAnswered?"a":"u"}:${(Br=H.agentMetadata)!=null&&Br.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Pe=nx(H,Ja)+lt,zt=Oe||Qe?null:ax(Bn,H.id,Pe);if(zt){A.appendChild(zt.cloneNode(!0)),ho(H)&&((pt=H.toolCall)!=null&&pt.id)&&((Ct=H.agentMetadata)==null?void 0:Ct.awaitingLocalTool)===!0&&!((Gr=H.agentMetadata)!=null&&Gr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Va(H,n,_e.composerOverlay));return}let bt=null,yr=o.find(Bt=>!!(H.variant==="reasoning"&&Bt.renderReasoning||H.variant==="tool"&&Bt.renderToolCall||H.variant==="approval"&&Bt.renderApproval||!H.variant&&Bt.renderMessage)),Wr=(Fr=n.layout)==null?void 0:Fr.messages;if(ho(H)&&((jo=H.agentMetadata)==null?void 0:jo.askUserQuestionAnswered)===!0){to.delete(H.id);let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime");return}if(ho(H)&&((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&&nt.current){let rn=to.get(H.id),io=rn!==Pe,Kr=null;if(io){let{payload:ir,complete:Zt}=xo(H),pr=H.id,on=()=>{var fn;return(fn=nt.current)==null?void 0:fn.getMessages().find(Cr=>Cr.id===pr)};Kr=Bt.renderAskUserQuestion({message:H,payload:ir,complete:Zt,resolve:fn=>{var jn;let Cr=on();Cr&&((jn=nt.current)==null||jn.resolveAskUserQuestion(Cr,fn))},dismiss:()=>{var Cr,jn,lo;let fn=on();(Cr=fn==null?void 0:fn.agentMetadata)!=null&&Cr.awaitingLocalTool&&((jn=nt.current)==null||jn.markAskUserQuestionResolved(fn),(lo=nt.current)==null||lo.resolveAskUserQuestion(fn,"(dismissed)"))},config:n})}let nn=rn!=null;if(io&&Kr===null&&!nn){((Sa=H.agentMetadata)==null?void 0:Sa.awaitingLocalTool)===!0&&!((Ta=H.agentMetadata)!=null&&Ta.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Va(H,n,_e.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),A.appendChild(Yt),we.push({messageId:H.id,fingerprint:Pe,bubble:Kr});return}else{((cr=H.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Xo=H.agentMetadata)!=null&&Xo.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Va(H,n,_e.composerOverlay));return}}else if(yr)if(H.variant==="reasoning"&&H.reasoning&&yr.renderReasoning){if(!Ye)return;bt=yr.renderReasoning({message:H,defaultRenderer:()=>Xp(H,n),config:n})}else if(H.variant==="tool"&&H.toolCall&&yr.renderToolCall){if(!Ge)return;bt=yr.renderToolCall({message:H,defaultRenderer:()=>Jp(H,n),config:n})}else if(H.variant==="approval"&&H.approval&&yr.renderApproval){if(n.approval===!1)return;bt=yr.renderApproval({message:H,defaultRenderer:()=>ou(H,n),config:n})}else yr.renderMessage&&(bt=yr.renderMessage({message:H,defaultRenderer:()=>{let Bt=Fa(H,b,Wr,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n});return H.role!=="user"&&lu(Bt,H,n,W),Bt},config:n}));if(!bt&&Qe){let Bt=Jl(H);if(Bt){let rn=zn.get(H.id),io=rn!==Pe,Kr=n.wrapComponentDirectiveInBubble!==!1,nn=null;if(io){let Yt=Kl(Bt,{config:n,message:H,transform:b});if(Yt)if(Kr){let ir=document.createElement("div");if(ir.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Zt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}else{let ir=document.createElement("div");if(ir.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),ir.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Zt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}}if(nn||rn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),Kr||Yt.classList.add("persona-w-full"),A.appendChild(Yt),se.push({messageId:H.id,fingerprint:Pe,bubble:nn});return}}}if(!bt)if(H.variant==="reasoning"&&H.reasoning){if(!Ye)return;bt=Xp(H,n)}else if(H.variant==="tool"&&H.toolCall){if(!Ge)return;bt=Jp(H,n)}else if(H.variant==="approval"&&H.approval){if(n.approval===!1)return;bt=ou(H,n)}else{let Bt=(Po=n.layout)==null?void 0:Po.messages;Bt!=null&&Bt.renderUserMessage&&H.role==="user"?bt=Bt.renderUserMessage({message:H,config:n,streaming:!!H.streaming}):Bt!=null&&Bt.renderAssistantMessage&&H.role==="assistant"?bt=Bt.renderAssistantMessage({message:H,config:n,streaming:!!H.streaming}):bt=Fa(H,b,Bt,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n}),H.role!=="user"&&bt&&lu(bt,H,n,W)}let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-${H.id}`,Gt.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Gt.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&Gt.classList.add("persona-w-full"),Gt.appendChild(bt),sx(Bn,H.id,Pe,Gt),A.appendChild(Gt)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Qe=Oe.getAttribute("data-persona-ask-sheet-for");Qe&&!F.has(Qe)&&_o(_e.composerOverlay,Qe)}),(wt=(ct=n.features)==null?void 0:ct.toolCallDisplay)!=null&&wt.grouped){let H=[],Oe=[];g.forEach(Qe=>{if(Qe.variant==="tool"&&Qe.toolCall&&Ge){Oe.push(Qe);return}Oe.length>1&&H.push(Oe),Oe=[]}),Oe.length>1&&H.push(Oe),H.forEach((Qe,lt)=>{var Br,pt;let Pe=Qe.map(Ct=>Array.from(A.children).find(Gr=>Gr instanceof HTMLElement&&Gr.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(Pe.length<2)return;let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-tool-group-${lt}-${Qe[0].id}`,zt.setAttribute("data-wrapper-id",`tool-group-${lt}-${Qe[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let yr=document.createElement("div");yr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Wr=`Called ${Qe.length} tools`,Gt=(pt=(Br=n.toolCall)==null?void 0:Br.renderGroupedSummary)==null?void 0:pt.call(Br,{messages:Qe,toolCalls:Qe.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:Wr,config:n});U(yr,Gt)||(yr.textContent=Wr);let jr=document.createElement("div");jr.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(yr,jr),zt.appendChild(bt),Pe[0].before(zt),Pe.forEach((Ct,Gr)=>{let Fr=document.createElement("div");Fr.className="persona-tool-group-item persona-relative",Fr.setAttribute("data-persona-tool-group-item","true"),Gr<Pe.length-1&&Fr.setAttribute("data-persona-tool-group-connector","true"),Fr.appendChild(Ct),jr.appendChild(Fr)})})}ix(Bn,j);let De=g.some(H=>H.role==="assistant"&&H.streaming),Ze=g[g.length-1],ht=(Ze==null?void 0:Ze.role)==="assistant"&&!Ze.streaming&&Ze.variant!=="approval";if(pn&&g.some(H=>H.role==="user")&&!De&&!ht){let H={config:n,streaming:!0,location:"standalone",defaultRenderer:fa},Oe=o.find(lt=>lt.renderLoadingIndicator),Qe=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Qe=Oe.renderLoadingIndicator(H)),Qe===null&&((vt=n.loadingIndicator)!=null&&vt.render)&&(Qe=n.loadingIndicator.render(H)),Qe===null&&(Qe=fa()),Qe){let lt=document.createElement("div"),Pe=((qe=n.loadingIndicator)==null?void 0:qe.showBubble)!==!1;lt.className=Pe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),lt.setAttribute("data-typing-indicator","true"),lt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",lt.appendChild(Qe);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-typing-indicator",zt.setAttribute("data-wrapper-id","typing-indicator"),zt.appendChild(lt),A.appendChild(zt)}}if(!pn&&g.length>0){let H=g[g.length-1],Oe={config:n,lastMessage:H,messageCount:g.length},Qe=o.find(Pe=>Pe.renderIdleIndicator),lt=null;if(Qe!=null&&Qe.renderIdleIndicator&&(lt=Qe.renderIdleIndicator(Oe)),lt===null&&(($e=n.loadingIndicator)!=null&&$e.renderIdle)&&(lt=n.loadingIndicator.renderIdle(Oe)),lt){let Pe=document.createElement("div"),zt=((ot=n.loadingIndicator)==null?void 0:ot.showBubble)!==!1;Pe.className=zt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(lt);let bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Pe),A.appendChild(bt)}}if(vl(c,A),we.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Qe}of we){let lt=c.querySelector(`#wrapper-${H}`);lt&&Qe!==null&&(lt.replaceChildren(Qe),lt.setAttribute("data-bubble-fp",Oe),to.set(H,Oe))}if(to.size>0)for(let H of to.keys())j.has(H)||to.delete(H);if(se.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Qe}of se){let lt=c.querySelector(`#wrapper-${H}`);lt&&Qe!==null&&(lt.replaceChildren(Qe),lt.setAttribute("data-bubble-fp",Oe),zn.set(H,Oe))}if(zn.size>0)for(let H of zn.keys())j.has(H)||zn.delete(H)},So=null,ci=()=>{var b;if(So)return;let c=A=>{let D=A.composedPath();D.includes(Ce)||rt&&D.includes(rt)||Kt(!1,"user")};So=c,((b=t.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},ts=()=>{var g;if(!So)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("pointerdown",So,!0),So=null};Pt.push(()=>ts());let To=null,pi=()=>{var b;if(To)return;let c=A=>{A.key==="Escape"&&(A.isComposing||Kt(!1,"user"))};To=c,((b=t.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},rs=()=>{var g;if(!To)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("keydown",To,!0),To=null};Pt.push(()=>rs());let Mo=!1,ns=new Set,ui=()=>{var g,b,A,D;let c=(A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:A.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},ao=()=>{var wt,vt,qe,$e;if(!B())return;let c=_e.peekBanner,g=_e.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(wt=W==null?void 0:W.getMessages())!=null?wt:[],A;for(let ot=b.length-1;ot>=0;ot--){let H=b[ot];if(H.role==="assistant"&&H.content){A=H;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let D=A.content,$=!!A.streaming,U=ui(),j=Ml(U),F=j.type!=="none"?Us(j.type,U==null?void 0:U.plugins):null,We=((vt=F==null?void 0:F.isAnimating)==null?void 0:vt.call(F,A))===!0,we=F!==null&&($||We);we&&F&&!ns.has(F.name)&&(_p(F,t),ns.add(F.name));let se=we&&(F!=null&&F.containerClass)?F.containerClass:null,Le=(qe=g.dataset.personaPeekStreamClass)!=null?qe:null;Le&&Le!==se&&(g.classList.remove(Le),delete g.dataset.personaPeekStreamClass),se&&Le!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),we?(g.style.setProperty("--persona-stream-step",`${j.speed}ms`),g.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let De=we?kl(D,j.buffer,F,A,$):D;if(we&&j.placeholder==="skeleton"&&$&&(!De||!De.trim())){let ot=document.createElement("div"),H=zs();H.classList.add("persona-pill-peek__skeleton"),ot.appendChild(H),vl(g,ot)}else{let ot=Math.max(0,De.length-100),H=De.length>100?De.slice(-100):De,Oe=oa(H);if(!we||!F){let Qe=De.length>100?`\u2026${H}`:H;g.textContent!==Qe&&(g.textContent=Qe)}else{let Qe=Oe;(F.wrap==="char"||F.wrap==="word")&&(Qe=qs(Oe,F.wrap,`peek-${A.id}`,{skipTags:F.skipTags,startIndex:ot}));let lt=document.createElement("div");if(lt.innerHTML=Qe,F.useCaret&&H.length>0){let Pe=El(),zt=lt.querySelectorAll(".persona-stream-char, .persona-stream-word"),bt=zt[zt.length-1];bt!=null&&bt.parentNode?bt.parentNode.insertBefore(Pe,bt.nextSibling):lt.appendChild(Pe)}vl(g,lt),($e=F.onAfterRender)==null||$e.call(F,{container:g,bubble:c,messageId:A.id,message:A,speed:j.speed,duration:j.duration})}}let ct=pn||Mo;c.classList.toggle("persona-pill-peek--visible",ct)};if(B()){let c=_e.peekBanner;if(c){let A=D=>{D.preventDefault(),D.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",A),Pt.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{Mo||(Mo=!0,ao())},b=()=>{Mo&&(Mo=!1,ao())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",b),Pt.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",b)}),rt&&(rt.addEventListener("pointerenter",g),rt.addEventListener("pointerleave",b),Pt.push(()=>{rt.removeEventListener("pointerenter",g),rt.removeEventListener("pointerleave",b)}))}let fi=c=>{var Le,De,Ze,ht,ct,wt,vt,qe;let g=(De=(Le=n.launcher)==null?void 0:Le.composerBar)!=null?De:{},b=(Ze=g.expandedSize)!=null?Ze:"anchored",A=(ht=g.bottomOffset)!=null?ht:"16px",D=g.collapsedMaxWidth,$=(ct=g.expandedMaxWidth)!=null?ct:"880px",U=(wt=g.expandedTopOffset)!=null?wt:"5vh",j=(vt=g.modalMaxWidth)!=null?vt:"880px",F=(qe=g.modalMaxHeight)!=null?qe:"min(90vh, 800px)",We="calc(100vw - 32px)",we="var(--persona-pill-area-height, 80px)",se=Ce.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",rt){let $e=rt.style;$e.bottom=A,$e.width=D!=null?D:""}if(c&&b!=="fullscreen"){if(b==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=j,se.maxWidth=We,se.maxHeight=F,se.height=F;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${A} + ${we})`,se.top=U,se.width=$,se.maxWidth=We}},ko=()=>{var F,We,we,se,Le,De,Ze,ht;if(!P())return;if(B()){let wt=(we=((We=(F=n.launcher)==null?void 0:F.composerBar)!=null?We:{}).expandedSize)!=null?we:"anchored",vt=R?"expanded":"collapsed";Ce.dataset.state=vt,Ce.dataset.expandedSize=wt,rt&&(rt.dataset.state=vt,rt.dataset.expandedSize=wt),Ce.style.removeProperty("display"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),fi(R),me.style.display=R?"flex":"none",Rn(),R?(ci(),pi()):(ts(),rs()),ao();return}let c=Ar(n),g=(se=t.ownerDocument.defaultView)!=null?se:window,b=(De=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?De:640,A=(ht=(Ze=n.launcher)==null?void 0:Ze.mobileFullscreen)!=null?ht:!0,D=g.innerWidth<=b,$=A&&D&&k,U=kn(n).reveal;R?(Ce.style.removeProperty("display"),Ce.style.display=c?"flex":"",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),Fe?Fe.element.style.display="none":dt&&(dt.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Ce.style.removeProperty("display"),Ce.style.display="flex",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.setProperty("display","none","important"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.display="",Ce.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),Fe?Fe.element.style.display=c?"none":"":dt&&(dt.style.display=c?"none":""))},Kt=(c,g="user")=>{var $,U;if(!P()||R===c)return;let b=R;R=c,ko();let A=(()=>{var Ze,ht,ct,wt,vt,qe,$e,ot,H,Oe;let j=(ht=(Ze=n.launcher)==null?void 0:Ze.sidebarMode)!=null?ht:!1,F=(ct=t.ownerDocument.defaultView)!=null?ct:window,We=(vt=(wt=n.launcher)==null?void 0:wt.mobileFullscreen)!=null?vt:!0,we=($e=(qe=n.launcher)==null?void 0:qe.mobileBreakpoint)!=null?$e:640,se=F.innerWidth<=we,Le=Ar(n)&&We&&se,De=B()&&((Oe=(H=(ot=n.launcher)==null?void 0:ot.composerBar)==null?void 0:H.expandedSize)!=null?Oe:"fullscreen")==="fullscreen";return j||We&&se&&k||Le||De})();if(R&&A){if(!gr){let j=t.getRootNode(),F=j instanceof ShadowRoot?j.host:t.closest(".persona-host");F&&(gr=Fp(F,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:qr))}hr||(hr=$p(t.ownerDocument))}else R||(gr==null||gr(),gr=null,hr==null||hr(),hr=null);R&&(jt(),Ao(!0));let D={open:R,source:g,timestamp:Date.now()};R&&!b?s.emit("widget:opened",D):!R&&b&&s.emit("widget:closed",D),s.emit("widget:state",{open:R,launcherEnabled:k,voiceActive:Lt.active,streaming:W.isStreaming()})},ba=c=>{Xt(c?"stop":"send"),G&&(G.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)})},wa=()=>{Lt.active||ge&&ge.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>wa(),200)});let os=()=>{var b,A,D,$,U,j,F,We,we,se,Le;pe.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",Be.textContent=($=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ge.placeholder=(j=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?j:"How can I help...";let c=J.querySelector("[data-persona-intro-card]");if(c){let De=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=De?"":"none",De?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}!((we=(We=n.sendButton)==null?void 0:We.useIcon)!=null&&we)&&!(W!=null&&W.isStreaming())&&(z.textContent=(Le=(se=n.copy)==null?void 0:se.sendButtonLabel)!=null?Le:"Send"),ge.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ge.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let Vn=null,mi=()=>{Vn==null&&(Vn=setInterval(()=>{let c=ze.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Vn),Vn=null;return}let g=Date.now();c.forEach(b=>{let A=Number(b.getAttribute("data-tool-elapsed"));A&&(b.textContent=Vi(g-A))})},100))};if(W=new Ba(n,{onMessagesChanged(c){qo(ze,c,be),mi(),W&&(c.some(D=>D.role==="user")?Wn.render([],W,ge,c):Wn.render(n.suggestionChips,W,ge,c,n.suggestionChipsConfig)),Ao(!pn),di(c);let g=[...c].reverse().find(A=>A.role==="user"),b=Lt.lastUserMessageId;g&&g.id!==b&&(Lt.lastUserMessageId=g.id,s.emit("user:message",g)),Lt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ya(c),ao()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};ut(fe,(D=>{var $,U,j,F;return D==="idle"?($=g.idleText)!=null?$:Ur.idle:D==="connecting"?(U=g.connectingText)!=null?U:Ur.connecting:D==="connected"?(j=g.connectedText)!=null?j:Ur.connected:D==="error"?(F=g.errorText)!=null?F:Ur.error:Ur[D]})(c),g,c)},onStreamingChanged(c){pn=c,ba(c),W&&qo(ze,W.getMessages(),be),c||Ao(!0),ao()},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":ie(),N();break;case"speaking":ie(),ae();break;default:c==="idle"&&W.isBargeInActive()?(ie(),q(),G==null||G.setAttribute("aria-label","End voice session")):(Lt.active=!1,ie(),An("system"),tn());break}},onArtifactsState(c){ee=c,ln(),ya()}}),nt.current=W,((wf=(bf=n.voiceRecognition)==null?void 0:bf.provider)==null?void 0:wf.type)==="runtype")try{W.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&W.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||n.onSSEEvent)&&W.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,c,g),Te==null||Te.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,A;c&&(c.metadata&&(d=pu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length&&W.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&W.hydrateArtifacts(c.artifacts,(A=c.selectedArtifactId)!=null?A:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let as=()=>{var g,b,A;!B()||R||!((A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||A)||Kt(!0,"auto")},ss=c=>{var D;if(c.preventDefault(),W.isStreaming()){W.cancel(),Te==null||Te.reset(),oe==null||oe.update();return}let g=ge.value.trim(),b=(D=ft==null?void 0:ft.hasAttachments())!=null?D:!1;if(!g&&!b)return;as();let A;b&&(A=[],A.push(...ft.getContentParts()),g&&A.push(Rs(g))),ge.value="",ge.style.height="auto",zo(),W.sendMessage(g,{contentParts:A}),b&&ft.clearAttachments()},gi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},va={...Cl},Ca=!1,zo=()=>{va={...Cl}},hi=()=>W.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),xi=c=>{if(!ge)return;Ca=!0,ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),Ca=!1;let g=ge.value.length;ge.setSelectionRange(g,g)},is=()=>{Ca||zo()},ls=c=>{if(ge){if(gi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ge.selectionStart===0&&ge.selectionEnd===0,b=rx({direction:c.key==="ArrowUp"?"up":"down",history:hi(),currentValue:ge.value,atStart:g,state:va});if(va=b.state,b.handled){c.preventDefault(),b.value!==void 0&&xi(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(W.isStreaming()){c.preventDefault();return}zo(),c.preventDefault(),z.click()}}},ds=c=>{c.key!=="Escape"||c.isComposing||W.isStreaming()&&c.composedPath().includes(me)&&(W.cancel(),Te==null||Te.reset(),oe==null||oe.update(),zo(),c.preventDefault(),c.stopImmediatePropagation())},cs=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!ft)return;let g=pC(c.clipboardData);g.length!==0&&(c.preventDefault(),await ft.handleFiles(g))},zr=null,un=!1,so=null,yt=null,ps=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Vo=(c="user")=>{var $,U,j,F,We,we,se;if(un||W.isStreaming())return;let g=ps();if(!g)return;zr=new g;let A=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;zr.continuous=!0,zr.interimResults=!0,zr.lang="en-US";let D=ge.value;zr.onresult=Le=>{let De="",Ze="";for(let ct=0;ct<Le.results.length;ct++){let wt=Le.results[ct],vt=wt[0].transcript;wt.isFinal?De+=vt+" ":Ze=vt}let ht=D+De+Ze;ge.value=ht,so&&clearTimeout(so),(De||Ze)&&(so=window.setTimeout(()=>{let ct=ge.value.trim();ct&&zr&&un&&(Nn(),ge.value="",ge.style.height="auto",W.sendMessage(ct,{viaVoice:!0}))},A))},zr.onerror=Le=>{Le.error!=="no-speech"&&Nn()},zr.onend=()=>{if(un){let Le=ge.value.trim();Le&&Le!==D.trim()&&(ge.value="",ge.style.height="auto",W.sendMessage(Le,{viaVoice:!0})),Nn()}};try{if(zr.start(),un=!0,Lt.active=!0,c!=="system"&&(Lt.manuallyDeactivated=!1),An(c),tn(),G){let Le=(j=n.voiceRecognition)!=null?j:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(F=Le.iconName)!=null?F:"mic",iconSize:parseFloat((se=(we=Le.iconSize)!=null?we:(We=n.sendButton)==null?void 0:We.size)!=null?se:"40")||24};let De=Le.recordingBackgroundColor,Ze=Le.recordingIconColor,ht=Le.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Ze!=null?Ze:"var(--persona-voice-recording-indicator, #ffffff)",Ze){let ct=G.querySelector("svg");ct&&ct.setAttribute("stroke",Ze)}ht&&(G.style.borderColor=ht),G.setAttribute("aria-label","Stop voice recognition")}}catch{Nn("system")}},Nn=(c="user")=>{if(un){if(un=!1,so&&(clearTimeout(so),so=null),zr){try{zr.stop()}catch{}zr=null}if(Lt.active=!1,An(c),tn(),G){if(G.classList.remove("persona-voice-recording"),yt){G.style.backgroundColor=yt.backgroundColor,G.style.color=yt.color,G.style.borderColor=yt.borderColor;let g=G.querySelector("svg");g&&g.setAttribute("stroke",yt.color||"currentColor"),yt=null}G.setAttribute("aria-label","Start voice recognition")}}},yi=(c,g)=>{var wt,vt,qe,$e,ot,H,Oe,Qe;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((wt=c==null?void 0:c.provider)==null?void 0:wt.type)==="runtype";if(!(b||A))return null;let $=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let j=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",F=(qe=g==null?void 0:g.size)!=null?qe:"40px",We=($e=c==null?void 0:c.iconSize)!=null?$e:F,we=parseFloat(We)||24,se=(ot=c==null?void 0:c.backgroundColor)!=null?ot:g==null?void 0:g.backgroundColor,Le=(H=c==null?void 0:c.iconColor)!=null?H:g==null?void 0:g.textColor;U.style.width=We,U.style.height=We,U.style.minWidth=We,U.style.minHeight=We,U.style.fontSize="18px",U.style.lineHeight="1",Le?U.style.color=Le:U.style.color="var(--persona-text, #111827)";let Ze=Ie(j,we,Le||"currentColor",1.5);Ze?U.appendChild(Ze):U.textContent="\u{1F3A4}",se?U.style.backgroundColor=se:U.style.backgroundColor="",c!=null&&c.borderWidth&&(U.style.borderWidth=c.borderWidth,U.style.borderStyle="solid"),c!=null&&c.borderColor&&(U.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(U.style.paddingLeft=c.paddingX,U.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(U.style.paddingTop=c.paddingY,U.style.paddingBottom=c.paddingY),$.appendChild(U);let ht=(Oe=c==null?void 0:c.tooltipText)!=null?Oe:"Start voice recognition";if(((Qe=c==null?void 0:c.showTooltip)!=null?Qe:!1)&&ht){let lt=v("div","persona-send-button-tooltip");lt.textContent=ht,$.appendChild(lt)}return{micButton:U,micButtonWrapper:$}},Eo=()=>{var g,b,A,D,$;if(!G||yt)return;let c=(g=n.voiceRecognition)!=null?g:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat(($=(D=c.iconSize)!=null?D:(A=n.sendButton)==null?void 0:A.size)!=null?$:"40")||24}},it=(c,g)=>{var $,U,j,F,We;if(!G)return;let b=G.querySelector("svg");b&&b.remove();let A=(We=yt==null?void 0:yt.iconSize)!=null?We:parseFloat((F=(j=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?j:(U=n.sendButton)==null?void 0:U.size)!=null?F:"40")||24,D=Ie(c,A,g,1.5);D&&G.appendChild(D)},L=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},q=()=>{var D;if(!G)return;Eo();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,A=c.recordingBorderColor;if(L(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let $=G.querySelector("svg");$&&$.setAttribute("stroke",b)}A&&(G.style.borderColor=A),G.setAttribute("aria-label","Stop voice recognition")},N=()=>{var j,F,We,we,se,Le,De,Ze;if(!G)return;Eo();let c=(j=n.voiceRecognition)!=null?j:{},g=W.getVoiceInterruptionMode(),b=(F=c.processingIconName)!=null?F:"loader",A=(we=(We=c.processingIconColor)!=null?We:yt==null?void 0:yt.color)!=null?we:"",D=(Le=(se=c.processingBackgroundColor)!=null?se:yt==null?void 0:yt.backgroundColor)!=null?Le:"",$=(Ze=(De=c.processingBorderColor)!=null?De:yt==null?void 0:yt.borderColor)!=null?Ze:"";L(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=D,G.style.borderColor=$;let U=A||"currentColor";G.style.color=U,it(b,U),G.setAttribute("aria-label","Processing voice input"),g==="none"&&(G.style.cursor="default")},ae=()=>{var We,we,se,Le,De,Ze,ht,ct,wt,vt,qe,$e;if(!G)return;Eo();let c=(We=n.voiceRecognition)!=null?We:{},g=W.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(we=c.speakingIconName)!=null?we:b,D=(Ze=c.speakingIconColor)!=null?Ze:g==="barge-in"?(Le=(se=c.recordingIconColor)!=null?se:yt==null?void 0:yt.color)!=null?Le:"":(De=yt==null?void 0:yt.color)!=null?De:"",$=(wt=c.speakingBackgroundColor)!=null?wt:g==="barge-in"?(ht=c.recordingBackgroundColor)!=null?ht:"var(--persona-voice-recording-bg, #ef4444)":(ct=yt==null?void 0:yt.backgroundColor)!=null?ct:"",U=($e=c.speakingBorderColor)!=null?$e:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(qe=yt==null?void 0:yt.borderColor)!=null?qe:"";L(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=$,G.style.borderColor=U;let j=D||"currentColor";G.style.color=j,it(A,j);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",F),g==="none"&&(G.style.cursor="default"),g==="barge-in"&&G.classList.add("persona-voice-recording")},ie=()=>{var c,g,b;G&&(L(),yt&&(G.style.backgroundColor=(c=yt.backgroundColor)!=null?c:"",G.style.color=(g=yt.color)!=null?g:"",G.style.borderColor=(b=yt.borderColor)!=null?b:"",it(yt.iconName,yt.color||"currentColor"),yt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Y=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=W.getVoiceStatus(),A=W.getVoiceInterruptionMode();if(A==="none"&&(b==="processing"||b==="speaking"))return;if(A==="cancel"&&(b==="processing"||b==="speaking")){W.stopVoicePlayback();return}if(W.isBargeInActive()){W.stopVoicePlayback(),W.deactivateBargeIn().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),ie()});return}W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),Lt.manuallyDeactivated=!W.isVoiceActive(),tn(),An("user"),W.isVoiceActive()?q():ie()});return}if(un){let b=ge.value.trim();Lt.manuallyDeactivated=!0,tn(),Nn("user"),b&&(ge.value="",ge.style.height="auto",W.sendMessage(b))}else Lt.manuallyDeactivated=!1,tn(),Vo("user")};dr=Y,G&&(G.addEventListener("click",Y),Pt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(W.isVoiceActive()&&W.toggleVoice(),ie()):Nn("system"),G&&G.removeEventListener("click",Y)}));let je=s.on("assistant:complete",()=>{Ya&&(Lt.active||Lt.manuallyDeactivated||Ya==="assistant"&&!Lt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Lt.active&&!Lt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),An("auto"),W.isVoiceActive()&&q()}):Vo("auto"))},600))});Pt.push(je);let tt=s.on("action:resubmit",()=>{setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)});Pt.push(tt);let mt=()=>{Kt(!R,"user")},Fe=null,dt=null;if(k&&!B()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>js(n,mt).element,onToggle:mt});g&&(dt=g)}dt||(Fe=js(n,mt))}Fe?t.appendChild(Fe.element):dt&&t.appendChild(dt),ko(),Wn.render(n.suggestionChips,W,ge,void 0,n.suggestionChipsConfig),os(),ba(W.isStreaming()),Ao(!0),ai(),M&&(!k||B()?setTimeout(()=>wa(),0):R&&setTimeout(()=>wa(),200));let jt=()=>{var F,We,we,se,Le,De,Ze,ht,ct,wt,vt,qe,$e,ot,H,Oe,Qe,lt,Pe,zt,bt,yr;if(B()){Et(),ko();return}let c=Ar(n),g=(We=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?We:!1,b=c||g||((se=(we=n.launcher)==null?void 0:we.fullHeight)!=null?se:!1),A=(Le=t.ownerDocument.defaultView)!=null?Le:window,D=(Ze=(De=n.launcher)==null?void 0:De.mobileFullscreen)!=null?Ze:!0,$=(ct=(ht=n.launcher)==null?void 0:ht.mobileBreakpoint)!=null?ct:640,U=A.innerWidth<=$,j=D&&U&&k;try{if(j){Rn(),Ro(t,n);return}if(E&&(E=!1,Rn(),Ro(t,n)),!k&&!c){he.style.height="",he.style.width="";return}if(!g&&!c){let Wr=(vt=(wt=n==null?void 0:n.launcher)==null?void 0:wt.width)!=null?vt:n==null?void 0:n.launcherWidth,Gt=Wr!=null?Wr:yn;he.style.width=Gt,he.style.maxWidth=Gt}if(qn(),!b){let Wr=A.innerHeight,Gt=64,jr=($e=(qe=n.launcher)==null?void 0:qe.heightOffset)!=null?$e:0,Br=Math.max(200,Wr-Gt),pt=Math.min(640,Br),Ct=Math.max(200,pt-jr);he.style.height=`${Ct}px`}}finally{if(Et(),ko(),R&&k){let Gt=((ot=t.ownerDocument.defaultView)!=null?ot:window).innerWidth<=((Oe=(H=n.launcher)==null?void 0:H.mobileBreakpoint)!=null?Oe:640),jr=(lt=(Qe=n.launcher)==null?void 0:Qe.sidebarMode)!=null?lt:!1,Br=(zt=(Pe=n.launcher)==null?void 0:Pe.mobileFullscreen)!=null?zt:!0,pt=Ar(n)&&Br&&Gt,Ct=jr||Br&&Gt&&k||pt;if(Ct&&!hr){let Gr=t.getRootNode(),Fr=Gr instanceof ShadowRoot?Gr.host:t.closest(".persona-host");Fr&&!gr&&(gr=Fp(Fr,(yr=(bt=n.launcher)==null?void 0:bt.zIndex)!=null?yr:qr)),hr=$p(t.ownerDocument)}else Ct||(gr==null||gr(),gr=null,hr==null||hr(),hr=null)}}};jt();let Sr=(vf=t.ownerDocument.defaultView)!=null?vf:window;if(Sr.addEventListener("resize",jt),Pt.push(()=>Sr.removeEventListener("resize",jt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Et()});c.observe(Je),Pt.push(()=>c.disconnect())}Dn=J.scrollTop;let Nt=J.scrollHeight,qt=()=>{let c=J.scrollTop,g=J.scrollHeight,b=g<Nt;Nt=g;let{action:A,nextLastScrollTop:D}=Sl({following:Hn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:_s(J,Qa),userScrollThreshold:ni,isAutoScrolling:ro||$o||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=D,A==="resume"){Co();return}A==="pause"&&es()};J.addEventListener("scroll",qt,{passive:!0}),Pt.push(()=>J.removeEventListener("scroll",qt));let Tr=c=>{let g=Tl({following:Hn.isFollowing(),deltaY:c.deltaY,nearBottom:_s(J,Qa),resumeWhenNearBottom:!0});g==="pause"?es():g==="resume"&&Co()};J.addEventListener("wheel",Tr,{passive:!0}),Pt.push(()=>J.removeEventListener("wheel",Tr)),Ot.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,Dn=J.scrollTop,Co(),Ao(!0)}),Pt.push(()=>Ot.remove()),Pt.push(()=>{Za()});let _r=()=>{Q&&(cn&&(Q.removeEventListener("click",cn),cn=null),P()?(Q.style.display="",cn=()=>{Kt(!1,"user")},Q.addEventListener("click",cn)):Q.style.display="none")};_r(),(()=>{let{clearChatButton:c}=_e;c&&c.addEventListener("click",()=>{W.clearMessages(),Bn.clear(),Co(),_o(_e.composerOverlay);try{localStorage.removeItem(Ka),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ka}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ka)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(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},S.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),oe==null||oe.update()})})(),Ae&&Ae.addEventListener("submit",ss),ge==null||ge.addEventListener("keydown",ls),ge==null||ge.addEventListener("input",is),ge==null||ge.addEventListener("paste",cs);let xr=(Cf=t.ownerDocument)!=null?Cf:document;xr.addEventListener("keydown",ds,!0);let Sn="persona-attachment-drop-active",us=0,od=()=>{us=0,me.classList.remove(Sn)},Aa=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&ft!==null},Eu=c=>{!Zl(c.dataTransfer)||!Aa()||(us++,us===1&&me.classList.add(Sn))},Lu=c=>{!Zl(c.dataTransfer)||!Aa()||(us--,us<=0&&od())},Pu=c=>{!Zl(c.dataTransfer)||!Aa()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Iu=c=>{var b;if(!Zl(c.dataTransfer)||!Aa())return;c.preventDefault(),c.stopPropagation(),od();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&ft.handleFiles(g)},Lo=!0;me.addEventListener("dragenter",Eu,Lo),me.addEventListener("dragleave",Lu,Lo),t.addEventListener("dragover",Pu,Lo),t.addEventListener("drop",Iu,Lo);let bi=t.ownerDocument,Ru=c=>{Aa()&&c.preventDefault()},Wu=c=>{Aa()&&c.preventDefault()};bi.addEventListener("dragover",Ru),bi.addEventListener("drop",Wu),Pt.push(()=>{Ae&&Ae.removeEventListener("submit",ss),ge==null||ge.removeEventListener("keydown",ls),ge==null||ge.removeEventListener("input",is),ge==null||ge.removeEventListener("paste",cs),xr.removeEventListener("keydown",ds,!0)}),Pt.push(()=>{me.removeEventListener("dragenter",Eu,Lo),me.removeEventListener("dragleave",Lu,Lo),t.removeEventListener("dragover",Pu,Lo),t.removeEventListener("drop",Iu,Lo),bi.removeEventListener("dragover",Ru),bi.removeEventListener("drop",Wu),od()}),Pt.push(()=>{W.cancel()}),Fe?Pt.push(()=>{Fe==null||Fe.destroy()}):dt&&Pt.push(()=>{dt==null||dt.remove()});let vr={update(c){var Cr,jn,lo,wi,vi,Ci,Jo,Ai,fs,Lf,Pf,If,Rf,Wf,Bf,Hf,Df,Of,Nf,_f,Ff,$f,Uf,qf,zf,Vf,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,wm,vm,Cm,Am,Sm,Tm,Mm,km,Em,Lm,Pm,Im,Rm,Wm,Bm,Hm,Dm,Om,Nm,_m,Fm,$m,Um,qm,zm,Vm,jm,Gm,Km,Xm,Jm,Qm,Ym,Zm,eg,tg,rg,ng,og,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,wg,vg,Cg,Ag,Sg;let g=n.toolCall,b=n.messageActions,A=(Cr=n.layout)==null?void 0:Cr.messages,D=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,j=(jn=n.features)==null?void 0:jn.showReasoning,F=(lo=n.features)==null?void 0:lo.showToolCalls,We=(wi=n.features)==null?void 0:wi.toolCallDisplay,we=(vi=n.features)==null?void 0:vi.reasoningDisplay;n={...n,...c},Rn(),Ro(t,n),zl(t,n),Vl(t,n),ln(),n.colorScheme!==D&&vo();let se=Ys.getForInstance(n.plugins);o.length=0,o.push(...se),k=(Jo=(Ci=n.launcher)==null?void 0:Ci.enabled)!=null?Jo:!0,T=(fs=(Ai=n.launcher)==null?void 0:Ai.autoExpand)!=null?fs:!1,Ye=(Pf=(Lf=n.features)==null?void 0:Lf.showReasoning)!=null?Pf:!0,Ge=(Rf=(If=n.features)==null?void 0:If.showToolCalls)!=null?Rf:!0,Ee=(Bf=(Wf=n.features)==null?void 0:Wf.scrollToBottom)!=null?Bf:{},sr(),oo();let Le=ve;if(ve=(Df=(Hf=n.features)==null?void 0:Hf.showEventStreamToggle)!=null?Df:!1,ve&&!Le){if(K||(X=new Js(Ne),K=new Xs(Ue,X),Te=Te!=null?Te:new Qs,X.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),W.setSSEEventCallback((re,Dt)=>{var rr;(rr=n.onSSEEvent)==null||rr.call(n,re,Dt),Te==null||Te.processEvent(re,Dt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Dt)})})),!xt&&Ve){let re=(Nf=(Of=n.features)==null?void 0:Of.eventStream)==null?void 0:Nf.classNames,Dt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");xt=v("button",Dt),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let rr=Ie("activity","18px","currentColor",1.5);rr&&xt.appendChild(rr);let At=_e.clearChatButtonWrapper,Ut=_e.closeButtonWrapper,Mr=At||Ut;Mr&&Mr.parentNode===Ve?Ve.insertBefore(xt,Mr):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}}else!ve&&Le&&(Or(),xt&&(xt.remove(),xt=null),K==null||K.clear(),X==null||X.destroy(),K=null,X=null,Te==null||Te.reset(),Te=null);if(((_f=n.launcher)==null?void 0:_f.enabled)===!1&&Fe&&(Fe.destroy(),Fe=null),((Ff=n.launcher)==null?void 0:Ff.enabled)===!1&&dt&&(dt.remove(),dt=null),(($f=n.launcher)==null?void 0:$f.enabled)!==!1&&!Fe&&!dt){let re=o.find(Dt=>Dt.renderLauncher);if(re!=null&&re.renderLauncher){let Dt=re.renderLauncher({config:n,defaultRenderer:()=>js(n,mt).element,onToggle:mt});Dt&&(dt=Dt,t.appendChild(dt))}dt||(Fe=js(n,mt),t.appendChild(Fe.element))}Fe&&Fe.update(n),ke&&((Uf=n.launcher)==null?void 0:Uf.title)!==void 0&&(ke.textContent=n.launcher.title),He&&((qf=n.launcher)==null?void 0:qf.subtitle)!==void 0&&(He.textContent=n.launcher.subtitle);let De=(zf=n.layout)==null?void 0:zf.header;if((De==null?void 0:De.layout)!==y&&Ve){let re=De?Na(n,De,{showClose:P(),onClose:()=>Kt(!1,"user")}):go({config:n,showClose:P(),onClose:()=>Kt(!1,"user")});Ve.replaceWith(re.header),Ve=re.header,_=re.iconHolder,ke=re.headerTitle,He=re.headerSubtitle,Q=re.closeButton,y=De==null?void 0:De.layout}else if(De&&(_&&(_.style.display=De.showIcon===!1?"none":""),ke&&(ke.style.display=De.showTitle===!1?"none":""),He&&(He.style.display=De.showSubtitle===!1?"none":""),Q&&(Q.style.display=De.showCloseButton===!1?"none":""),_e.clearChatButtonWrapper)){let re=De.showClearChat;if(re!==void 0){_e.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Dt}=_e;Dt&&!Dt.classList.contains("persona-absolute")&&(re?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"))}}let ht=((Vf=n.layout)==null?void 0:Vf.showHeader)!==!1;Ve&&(Ve.style.display=ht?"":"none");let ct=((jf=n.layout)==null?void 0:jf.showFooter)!==!1;Je&&(Je.style.display=ct?"":"none"),Et(),oo(),k!==w?k?Kt(T,"auto"):(R=!0,ko()):T!==h&&Kt(T,"auto"),h=T,w=k,jt(),_r();let qe=JSON.stringify(c.toolCall)!==JSON.stringify(g),$e=JSON.stringify(n.messageActions)!==JSON.stringify(b),ot=JSON.stringify((Gf=n.layout)==null?void 0:Gf.messages)!==JSON.stringify(A),H=((Kf=n.loadingIndicator)==null?void 0:Kf.render)!==($==null?void 0:$.render)||((Xf=n.loadingIndicator)==null?void 0:Xf.renderIdle)!==($==null?void 0:$.renderIdle)||((Jf=n.loadingIndicator)==null?void 0:Jf.showBubble)!==($==null?void 0:$.showBubble),Oe=n.iterationDisplay!==U,Qe=((Yf=(Qf=n.features)==null?void 0:Qf.showReasoning)!=null?Yf:!0)!==(j!=null?j:!0)||((em=(Zf=n.features)==null?void 0:Zf.showToolCalls)!=null?em:!0)!==(F!=null?F:!0)||JSON.stringify((tm=n.features)==null?void 0:tm.toolCallDisplay)!==JSON.stringify(We)||JSON.stringify((rm=n.features)==null?void 0:rm.reasoningDisplay)!==JSON.stringify(we);(qe||$e||ot||H||Oe||Qe)&&W&&(Ja++,qo(ze,W.getMessages(),be));let Pe=(nm=n.launcher)!=null?nm:{},zt=(om=Pe.headerIconHidden)!=null?om:!1,bt=(sm=(am=n.layout)==null?void 0:am.header)==null?void 0:sm.showIcon,yr=zt||bt===!1,Wr=Pe.headerIconName,Gt=(im=Pe.headerIconSize)!=null?im:"48px";if(_){let re=me.querySelector(".persona-border-b-persona-divider"),Dt=re==null?void 0:re.querySelector(".persona-flex-col");if(yr)_.style.display="none",re&&Dt&&!re.contains(Dt)&&re.insertBefore(Dt,re.firstChild);else{if(_.style.display="",_.style.height=Gt,_.style.width=Gt,re&&Dt&&(re.contains(_)?_.nextSibling!==Dt&&(_.remove(),re.insertBefore(_,Dt)):re.insertBefore(_,Dt)),Wr){let At=parseFloat(Gt)||24,Ut=Ie(Wr,At*.6,"#ffffff",2);Ut?_.replaceChildren(Ut):_.textContent=(lm=Pe.agentIconText)!=null?lm:"\u{1F4AC}"}else if(Pe.iconUrl){let At=_.querySelector("img");if(At)At.src=Pe.iconUrl,At.style.height=Gt,At.style.width=Gt;else{let Ut=document.createElement("img");Ut.src=Pe.iconUrl,Ut.alt="",Ut.className="persona-rounded-xl persona-object-cover",Ut.style.height=Gt,Ut.style.width=Gt,_.replaceChildren(Ut)}}else{let At=_.querySelector("svg"),Ut=_.querySelector("img");(At||Ut)&&_.replaceChildren(),_.textContent=(dm=Pe.agentIconText)!=null?dm:"\u{1F4AC}"}let rr=_.querySelector("img");rr&&(rr.style.height=Gt,rr.style.width=Gt)}}let jr=(pm=(cm=n.layout)==null?void 0:cm.header)==null?void 0:pm.showTitle,Br=(fm=(um=n.layout)==null?void 0:um.header)==null?void 0:fm.showSubtitle;if(ke&&(ke.style.display=jr===!1?"none":""),He&&(He.style.display=Br===!1?"none":""),Q){((gm=(mm=n.layout)==null?void 0:mm.header)==null?void 0:gm.showCloseButton)===!1?Q.style.display="none":Q.style.display="";let Dt=(hm=Pe.closeButtonSize)!=null?hm:"32px",rr=(xm=Pe.closeButtonPlacement)!=null?xm:"inline";Q.style.height=Dt,Q.style.width=Dt;let{closeButtonWrapper:At}=_e,Ut=rr==="top-right",Mr=At==null?void 0:At.classList.contains("persona-absolute");if(At&&Ut!==Mr)if(At.remove(),Ut)At.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(At);else{let Tt=(bm=(ym=Pe.clearChat)==null?void 0:ym.placement)!=null?bm:"inline",kr=(vm=(wm=Pe.clearChat)==null?void 0:wm.enabled)!=null?vm:!0;At.className=kr&&Tt==="inline"?"":"persona-ml-auto";let an=me.querySelector(".persona-border-b-persona-divider");an&&an.appendChild(At)}if(Q.style.color=Pe.closeButtonColor||en.actionIconColor,Pe.closeButtonBackgroundColor?(Q.style.backgroundColor=Pe.closeButtonBackgroundColor,Q.classList.remove("hover:persona-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Tt=Pe.closeButtonBorderWidth||"0px",kr=Pe.closeButtonBorderColor||"transparent";Q.style.border=`${Tt} solid ${kr}`,Q.classList.remove("persona-border-none")}else Q.style.border="",Q.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Q.style.borderRadius=Pe.closeButtonBorderRadius,Q.classList.remove("persona-rounded-full")):(Q.style.borderRadius="",Q.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Q.style.paddingLeft=Pe.closeButtonPaddingX,Q.style.paddingRight=Pe.closeButtonPaddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),Pe.closeButtonPaddingY?(Q.style.paddingTop=Pe.closeButtonPaddingY,Q.style.paddingBottom=Pe.closeButtonPaddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let $r=(Cm=Pe.closeButtonIconName)!=null?Cm:"x",_n=(Am=Pe.closeButtonIconText)!=null?Am:"\xD7";Q.innerHTML="";let Xr=Ie($r,"28px","currentColor",1);Xr?Q.appendChild(Xr):Q.textContent=_n;let br=(Sm=Pe.closeButtonTooltipText)!=null?Sm:"Close chat",mn=(Tm=Pe.closeButtonShowTooltip)!=null?Tm:!0;if(Q.setAttribute("aria-label",br),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),mn&&br)){let Tt=null,kr=()=>{if(Tt||!Q)return;let Qo=Q.ownerDocument,ms=Qo.body;if(!ms)return;Tt=Qn(Qo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let gs=Qn(Qo,"div");gs.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(gs);let Yo=Q.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Wo),Tt.style.left=`${Yo.left+Yo.width/2}px`,Tt.style.top=`${Yo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",ms.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};At.addEventListener("mouseenter",kr),At.addEventListener("mouseleave",an),Q.addEventListener("focus",kr),Q.addEventListener("blur",an),At._cleanupTooltip=()=>{an(),At&&(At.removeEventListener("mouseenter",kr),At.removeEventListener("mouseleave",an)),Q&&(Q.removeEventListener("focus",kr),Q.removeEventListener("blur",an))}}}let{clearChatButton:pt,clearChatButtonWrapper:Ct}=_e;if(pt){let re=(Mm=Pe.clearChat)!=null?Mm:{},Dt=(km=re.enabled)!=null?km:!0,rr=(Lm=(Em=n.layout)==null?void 0:Em.header)==null?void 0:Lm.showClearChat,At=rr!==void 0?rr:Dt,Ut=(Pm=re.placement)!=null?Pm:"inline";if(Ct){Ct.style.display=At?"":"none";let{closeButtonWrapper:Mr}=_e;!B()&&Mr&&!Mr.classList.contains("persona-absolute")&&(At?Mr.classList.remove("persona-ml-auto"):Mr.classList.add("persona-ml-auto"));let $r=Ut==="top-right",_n=Ct.classList.contains("persona-absolute");if(!B()&&$r!==_n&&At){if(Ct.remove(),$r)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",me.style.position="relative",me.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let br=me.querySelector(".persona-border-b-persona-divider"),mn=_e.closeButtonWrapper;br&&mn&&mn.parentElement===br?br.insertBefore(Ct,mn):br&&br.appendChild(Ct)}let Xr=_e.closeButtonWrapper;Xr&&!Xr.classList.contains("persona-absolute")&&($r?Xr.classList.add("persona-ml-auto"):Xr.classList.remove("persona-ml-auto"))}}if(At){if(!B()){let Tt=(Im=re.size)!=null?Im:"32px";pt.style.height=Tt,pt.style.width=Tt}let Mr=(Rm=re.iconName)!=null?Rm:"refresh-cw",$r=(Wm=re.iconColor)!=null?Wm:"";pt.style.color=$r||en.actionIconColor,pt.innerHTML="";let _n=B()?"14px":"20px",Xr=Ie(Mr,_n,"currentColor",2);if(Xr&&pt.appendChild(Xr),re.backgroundColor?(pt.style.backgroundColor=re.backgroundColor,pt.classList.remove("hover:persona-bg-gray-100")):(pt.style.backgroundColor="",pt.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let Tt=re.borderWidth||"0px",kr=re.borderColor||"transparent";pt.style.border=`${Tt} solid ${kr}`,pt.classList.remove("persona-border-none")}else pt.style.border="",pt.classList.add("persona-border-none");re.borderRadius?(pt.style.borderRadius=re.borderRadius,pt.classList.remove("persona-rounded-full")):(pt.style.borderRadius="",pt.classList.add("persona-rounded-full")),re.paddingX?(pt.style.paddingLeft=re.paddingX,pt.style.paddingRight=re.paddingX):(pt.style.paddingLeft="",pt.style.paddingRight=""),re.paddingY?(pt.style.paddingTop=re.paddingY,pt.style.paddingBottom=re.paddingY):(pt.style.paddingTop="",pt.style.paddingBottom="");let br=(Bm=re.tooltipText)!=null?Bm:"Clear chat",mn=(Hm=re.showTooltip)!=null?Hm:!0;if(pt.setAttribute("aria-label",br),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),mn&&br)){let Tt=null,kr=()=>{if(Tt||!pt)return;let Qo=pt.ownerDocument,ms=Qo.body;if(!ms)return;Tt=Qn(Qo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let gs=Qn(Qo,"div");gs.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(gs);let Yo=pt.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Wo),Tt.style.left=`${Yo.left+Yo.width/2}px`,Tt.style.top=`${Yo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",ms.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};Ct.addEventListener("mouseenter",kr),Ct.addEventListener("mouseleave",an),pt.addEventListener("focus",kr),pt.addEventListener("blur",an),Ct._cleanupTooltip=()=>{an(),Ct&&(Ct.removeEventListener("mouseenter",kr),Ct.removeEventListener("mouseleave",an)),pt&&(pt.removeEventListener("focus",kr),pt.removeEventListener("blur",an))}}}}let Gr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Zs],Fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ha.message,ha.messageAndClick];S=ei({parsers:Gr,handlers:Fr,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),be=ey(n,S,ne),W.updateConfig(n),qo(ze,W.getMessages(),be),Wn.render(n.suggestionChips,W,ge,void 0,n.suggestionChipsConfig),os(),ba(W.isStreaming());let jo=((Dm=n.voiceRecognition)==null?void 0:Dm.enabled)===!0,Go=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ko=((Nm=(Om=n.voiceRecognition)==null?void 0:Om.provider)==null?void 0:Nm.type)==="runtype";if(jo&&(Go||Ko))if(!G||!Jt){let re=yi(n.voiceRecognition,n.sendButton);re&&(G=re.micButton,Jt=re.micButtonWrapper,Mt.insertBefore(Jt,Re),G.addEventListener("click",Y),G.disabled=W.isStreaming())}else{let re=(_m=n.voiceRecognition)!=null?_m:{},Dt=(Fm=n.sendButton)!=null?Fm:{},rr=($m=re.iconName)!=null?$m:"mic",At=(Um=Dt.size)!=null?Um:"40px",Ut=(qm=re.iconSize)!=null?qm:At,Mr=parseFloat(Ut)||24;G.style.width=Ut,G.style.height=Ut,G.style.minWidth=Ut,G.style.minHeight=Ut;let $r=(Vm=(zm=re.iconColor)!=null?zm:Dt.textColor)!=null?Vm:"currentColor";G.innerHTML="";let _n=Ie(rr,Mr,$r,2);_n?G.appendChild(_n):G.textContent="\u{1F3A4}";let Xr=(jm=re.backgroundColor)!=null?jm:Dt.backgroundColor;Xr?G.style.backgroundColor=Xr:G.style.backgroundColor="",$r?G.style.color=$r:G.style.color="var(--persona-text, #111827)",re.borderWidth?(G.style.borderWidth=re.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),re.borderColor?G.style.borderColor=re.borderColor:G.style.borderColor="",re.paddingX?(G.style.paddingLeft=re.paddingX,G.style.paddingRight=re.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),re.paddingY?(G.style.paddingTop=re.paddingY,G.style.paddingBottom=re.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let br=Jt==null?void 0:Jt.querySelector(".persona-send-button-tooltip"),mn=(Gm=re.tooltipText)!=null?Gm:"Start voice recognition";if(((Km=re.showTooltip)!=null?Km:!1)&&mn)if(br)br.textContent=mn,br.style.display="";else{let kr=document.createElement("div");kr.className="persona-send-button-tooltip",kr.textContent=mn,Jt==null||Jt.insertBefore(kr,G)}else br&&(br.style.display="none");Jt.style.display="",G.disabled=W.isStreaming()}else G&&Jt&&(Jt.style.display="none",((Jm=(Xm=n.voiceRecognition)==null?void 0:Xm.provider)==null?void 0:Jm.type)==="runtype"?W.isVoiceActive()&&W.toggleVoice():un&&Nn());if(((Qm=n.attachments)==null?void 0:Qm.enabled)===!0)if(!_t||!st){let re=(Ym=n.attachments)!=null?Ym:{},rr=(eg=((Zm=n.sendButton)!=null?Zm:{}).size)!=null?eg:"40px";ye||(ye=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ye.style.display="none",Ae.insertBefore(ye,ge)),de||(de=document.createElement("input"),de.type="file",de.accept=((tg=re.allowedTypes)!=null?tg:mo).join(","),de.multiple=((rg=re.maxFiles)!=null?rg:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Ae.insertBefore(de,ge)),_t=v("div","persona-send-button-wrapper"),st=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),st.type="button",st.setAttribute("aria-label",(ng=re.buttonTooltipText)!=null?ng:"Attach file");let At=(og=re.buttonIconName)!=null?og:"paperclip",Ut=rr,Mr=parseFloat(Ut)||40,$r=Math.round(Mr*.6);st.style.width=Ut,st.style.height=Ut,st.style.minWidth=Ut,st.style.minHeight=Ut,st.style.fontSize="18px",st.style.lineHeight="1",st.style.backgroundColor="transparent",st.style.color="var(--persona-primary, #111827)",st.style.border="none",st.style.borderRadius="6px",st.style.transition="background-color 0.15s ease",st.addEventListener("mouseenter",()=>{st.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),st.addEventListener("mouseleave",()=>{st.style.backgroundColor="transparent"});let _n=Ie(At,$r,"currentColor",1.5);_n?st.appendChild(_n):st.textContent="\u{1F4CE}",st.addEventListener("click",mn=>{mn.preventDefault(),de==null||de.click()}),_t.appendChild(st);let Xr=(ag=re.buttonTooltipText)!=null?ag:"Attach file",br=v("div","persona-send-button-tooltip");br.textContent=Xr,_t.appendChild(br),at.append(_t),!ft&&de&&ye&&(ft=ca.fromConfig(re),ft.setPreviewsContainer(ye),de.addEventListener("change",async()=>{ft&&(de!=null&&de.files)&&(await ft.handleFileSelect(de.files),de.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(ty(re.dropOverlay))}else{_t.style.display="";let re=(sg=n.attachments)!=null?sg:{};de&&(de.accept=((ig=re.allowedTypes)!=null?ig:mo).join(","),de.multiple=((lg=re.maxFiles)!=null?lg:4)>1),ft&&ft.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else _t&&(_t.style.display="none"),ft&&ft.clearAttachments(),(dg=me.querySelector(".persona-attachment-drop-overlay"))==null||dg.remove();let cr=(cg=n.sendButton)!=null?cg:{},Xo=(pg=cr.useIcon)!=null?pg:!1,Po=(ug=cr.iconText)!=null?ug:"\u2191",Bt=cr.iconName,rn=(fg=cr.tooltipText)!=null?fg:"Send message",io=(mg=cr.showTooltip)!=null?mg:!1,Kr=(gg=cr.size)!=null?gg:"40px",nn=cr.backgroundColor,Yt=cr.textColor;if(Xo){if(z.style.width=Kr,z.style.height=Kr,z.style.minWidth=Kr,z.style.minHeight=Kr,z.style.fontSize="18px",z.style.lineHeight="1",z.innerHTML="",Yt?z.style.color=Yt:z.style.color="var(--persona-button-primary-fg, #ffffff)",Bt){let re=parseFloat(Kr)||24,Dt=(Yt==null?void 0:Yt.trim())||"currentColor",rr=Ie(Bt,re,Dt,2);rr?z.appendChild(rr):z.textContent=Po}else z.textContent=Po;z.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nn?(z.style.backgroundColor=nn,z.classList.remove("persona-bg-persona-primary")):(z.style.backgroundColor="",z.classList.add("persona-bg-persona-primary"))}else z.textContent=(xg=(hg=n.copy)==null?void 0:hg.sendButtonLabel)!=null?xg:"Send",z.style.width="",z.style.height="",z.style.minWidth="",z.style.minHeight="",z.style.fontSize="",z.style.lineHeight="",z.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?(z.style.backgroundColor=nn,z.classList.remove("persona-bg-persona-accent")):z.classList.add("persona-bg-persona-accent"),Yt?z.style.color=Yt:z.classList.add("persona-text-white");cr.borderWidth?(z.style.borderWidth=cr.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),cr.borderColor?z.style.borderColor=cr.borderColor:z.style.borderColor="",cr.paddingX?(z.style.paddingLeft=cr.paddingX,z.style.paddingRight=cr.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),cr.paddingY?(z.style.paddingTop=cr.paddingY,z.style.paddingBottom=cr.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let ir=Re==null?void 0:Re.querySelector(".persona-send-button-tooltip");if(io&&rn)if(ir)ir.textContent=rn,ir.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=rn,Re==null||Re.insertBefore(re,z)}else ir&&(ir.style.display="none");let Zt=(Cg=(yg=n.layout)==null?void 0:yg.contentMaxWidth)!=null?Cg:B()?(vg=(wg=(bg=n.launcher)==null?void 0:bg.composerBar)==null?void 0:wg.contentMaxWidth)!=null?vg:"720px":void 0;Zt?(ze.style.maxWidth=Zt,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%",Ae&&(Ae.style.maxWidth=Zt,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Z&&(Z.style.maxWidth=Zt,Z.style.marginLeft="auto",Z.style.marginRight="auto")):(ze.style.maxWidth="",ze.style.marginLeft="",ze.style.marginRight="",ze.style.width="",Ae&&(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight=""),Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight=""));let pr=(Ag=n.statusIndicator)!=null?Ag:{},on=(Sg=pr.visible)!=null?Sg:!0;if(fe.style.display=on?"":"none",W){let re=W.getStatus();ut(fe,(rr=>{var At,Ut,Mr,$r;return rr==="idle"?(At=pr.idleText)!=null?At:Ur.idle:rr==="connecting"?(Ut=pr.connectingText)!=null?Ut:Ur.connecting:rr==="connected"?(Mr=pr.connectedText)!=null?Mr:Ur.connected:rr==="error"?($r=pr.errorText)!=null?$r:Ur.error:Ur[rr]})(re),pr,re)}fe.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=pr.align==="left"?"persona-text-left":pr.align==="center"?"persona-text-center":"persona-text-right";fe.classList.add(fn)},open(){P()&&Kt(!0,"api")},close(){P()&&Kt(!1,"api")},toggle(){P()&&Kt(!R,"api")},clearChat(){Se=!1,W.clearMessages(),Bn.clear(),Co();try{localStorage.removeItem(Ka),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ka}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ka)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={},S.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),oe==null||oe.update()},setMessage(c){return!ge||W.isStreaming()?!1:(!R&&P()&&Kt(!0,"system"),ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(W.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ge.value.trim();return g?(!R&&P()&&Kt(!0,"system"),ge.value="",ge.style.height="auto",W.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return W.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(W.isVoiceActive()||(!R&&P()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),An("user"),W.isVoiceActive()&&q()})),!0):un?!0:ps()?(!R&&P()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),Vo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?W.isVoiceActive()?(W.toggleVoice().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),ie()}),!0):!1:un?(Lt.manuallyDeactivated=!0,tn(),Nn("user"),!0):!1},injectMessage(c){return!R&&P()&&Kt(!0,"system"),W.injectMessage(c)},injectAssistantMessage(c){!R&&P()&&Kt(!0,"system");let g=W.injectAssistantMessage(c);return O&&(O=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)),g},injectUserMessage(c){return!R&&P()&&Kt(!0,"system"),W.injectUserMessage(c)},injectSystemMessage(c){return!R&&P()&&Kt(!0,"system"),W.injectSystemMessage(c)},injectMessageBatch(c){return!R&&P()&&Kt(!0,"system"),W.injectMessageBatch(c)},injectComponentDirective(c){return!R&&P()&&Kt(!0,"system"),W.injectComponentDirective(c)},injectTestMessage(c){!R&&P()&&Kt(!0,"system"),W.injectTestEvent(c)},async connectStream(c,g){return W.connectStream(c,g)},__pushEventStreamEvent(c){K&&(Te==null||Te.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ve||!K||Lr()},hideEventStream(){xe&&Or()},isEventStreamVisible(){return xe},showArtifacts(){Ln(n)&&(Se=!1,ln(),ue==null||ue.setMobileOpen(!0))},hideArtifacts(){Ln(n)&&(Se=!0,ln())},upsertArtifact(c){return Ln(n)?(Se=!1,W.upsertArtifact(c)):null},selectArtifact(c){Ln(n)&&W.selectArtifact(c)},clearArtifacts(){Ln(n)&&W.clearArtifacts()},getArtifacts(){var c;return(c=W==null?void 0:W.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=W==null?void 0:W.getSelectedArtifactId())!=null?c:null},focusInput(){return k&&!R&&!B()||!ge?!1:(ge.focus(),!0)},async resolveApproval(c,g){let A=W.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===c});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${c}`);if(A.approval.toolType==="webmcp"){W.resolveWebMcpApproval(A.id,g);return}return W.resolveApproval(A.approval,g)},getMessages(){return W.getMessages()},getStatus(){return W.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 P()&&R},isVoiceActive(){return Lt.active},getState(){return{open:P()&&R,launcherEnabled:k,voiceActive:Lt.active,streaming:W.isStreaming()}},showCSATFeedback(c){!R&&P()&&Kt(!0,"system");let g=ze.querySelector(".persona-feedback-container");g&&g.remove();let b=Ql({onSubmit:async(A,D)=>{var $;W.isClientTokenMode()&&await W.submitCSATFeedback(A,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,A,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ze.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&P()&&Kt(!0,"system");let g=ze.querySelector(".persona-feedback-container");g&&g.remove();let b=Yl({onSubmit:async(A,D)=>{var $;W.isClientTokenMode()&&await W.submitNPSFeedback(A,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,A,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ze.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return W.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return W.submitNPSFeedback(c,g)},destroy(){Vn!=null&&(clearInterval(Vn),Vn=null),Pt.forEach(c=>c()),Ce.remove(),rt==null||rt.remove(),Fe==null||Fe.destroy(),dt==null||dt.remove(),cn&&Q.removeEventListener("click",cn)}};if((((Af=r==null?void 0:r.debugTools)!=null?Af:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:vr,getMessages:vr.getMessages,getStatus:vr.getStatus,getMetadata:vr.getPersistentMetadata,updateMetadata:vr.updatePersistentMetadata,clearHistory:()=>vr.clearChat(),setVoiceActive:b=>b?vr.startVoiceRecognition():vr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Pt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.focusInput()};if(window.addEventListener("persona:focusInput",g),Pt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ve){let j=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.showEventStream()},F=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",F),Pt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",F)})}let b=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.showArtifacts()},A=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.hideArtifacts()},D=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&vr.upsertArtifact(F.artifact)},$=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&vr.selectArtifact(F.id)},U=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),Pt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Tn=uC(n.persistState);if(Tn&&P()){let c=fC(Tn.storage),g=`${Tn.keyPrefix}widget-open`,b=`${Tn.keyPrefix}widget-voice`,A=`${Tn.keyPrefix}widget-voice-mode`;if(c){let D=((Sf=Tn.persist)==null?void 0:Sf.openState)&&c.getItem(g)==="true",$=((Tf=Tn.persist)==null?void 0:Tf.voiceState)&&c.getItem(b)==="true",U=((Mf=Tn.persist)==null?void 0:Mf.voiceState)&&c.getItem(A)==="true";if(D&&setTimeout(()=>{vr.open(),setTimeout(()=>{var j;if($||U)vr.startVoiceRecognition();else if((j=Tn.persist)!=null&&j.focusInput){let F=t.querySelector("textarea");F&&F.focus()}},100)},0),(kf=Tn.persist)!=null&&kf.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Ef=Tn.persist)!=null&&Ef.voiceState&&(s.on("voice:state",j=>{c.setItem(b,j.active?"true":"false")}),s.on("user:message",j=>{c.setItem(A,j.viaVoice?"true":"false")})),Tn.clearOnChatClear){let j=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(A)},F=()=>j();window.addEventListener("persona:clear-chat",F),Pt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return p&&P()&&setTimeout(()=>{vr.open()},0),ao(),vr};var mC=(t,e)=>{let r=t.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,e*parseFloat(o[1])/100):420},ry=(t,e)=>{var n,o;let r=(o=(n=e==null?void 0:e.launcher)==null?void 0:n.enabled)!=null?o:!0;t.className="persona-host",t.style.height=r?"":"100%",t.style.display=r?"":"flex",t.style.flexDirection=r?"":"column",t.style.flex=r?"":"1 1 auto",t.style.minHeight=r?"":"0"},gu=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},ny=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.minWidth="",gu(t)},uu=t=>{t.style.transition=""},fu=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform=""},mu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},td=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},gC=(t,e,r,n,o)=>{o?r.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(r,n),t.appendChild(e)):r.parentElement===e&&(e.replaceChildren(),t.appendChild(r),t.appendChild(n))},hC=(t,e,r,n,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==n&&a.replaceChildren(n,r):a.lastElementChild!==n&&a.replaceChildren(r,n)},oy=(t,e,r,n,o,s,a)=>{var x,C,S,k,T,M;let i=kn(s),d=i.reveal==="push";gC(t,e,r,n,d),hC(t,e,r,n,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=t.ownerDocument.defaultView,p=(C=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,m=(k=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?k:640,u=l!=null?l.innerWidth<=m:!1;if(p&&u&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),fu(e),uu(n),ny(n),mu(r),td(o,n),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((M=(T=s==null?void 0:s.launcher)==null?void 0:T.zIndex)!=null?M:qr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),ny(n),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",fu(e),uu(n),mu(r),td(o,n);let h=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",y=a?"translateX(0)":w;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=h,n.style.transform=y,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",uu(n),gu(n),td(o,n);let h=mC(i.width,t.clientWidth),w=Math.max(0,t.clientWidth),y=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${h}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${h}px)`;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${w+h}px`,e.style.transition=y,e.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=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",fu(e),gu(n),mu(r),td(o,n);let h=i.reveal==="emerge";h?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let w=a?i.width:"0px",y=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 ${w}`,n.style.width=w,n.style.maxWidth=w,n.style.minWidth=w,n.style.minHeight="0",n.style.position="relative",n.style.overflow=h||E?"hidden":"visible",n.style.transition=y,h&&(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")}},xC=(t,e)=>{let r=t.ownerDocument.createElement("div");return ry(r,e),t.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){ry(r,n)},destroy(){r.remove()}}},yC=(t,e)=>{var T,M,h,w;let{ownerDocument:r}=t,n=t.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=t.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=r.createElement("div"),i=r.createElement("div"),d=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),m=(M=(T=e==null?void 0:e.launcher)==null?void 0:T.enabled)==null||M?(w=(h=e==null?void 0:e.launcher)==null?void 0:h.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),n.insertBefore(a,t),d.appendChild(t);let u=null,f=()=>{u==null||u.disconnect(),u=null},x=()=>{f(),kn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{oy(a,i,d,l,p,e,m)}),u.observe(a))},C=()=>{oy(a,i,d,l,p,e,m),x()},S=a.ownerDocument.defaultView,k=()=>{C()};return S==null||S.addEventListener("resize",k),kn(e).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(y){let E=y.launcherEnabled?y.open:!0;m!==E&&(m=E,C())},updateConfig(y){var E,B;e=y,((B=(E=e==null?void 0:e.launcher)==null?void 0:E.enabled)!=null?B:!0)===!1&&(m=!0),C()},destroy(){S==null||S.removeEventListener("resize",k),f(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(t,s):n.appendChild(t)),a.remove()}}},ti=(t,e)=>Ar(e)?yC(t,e):xC(t,e);var hu={},ay=!1,bC=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let e=document.querySelector(t);if(!e)throw new Error(`Chat widget target "${t}" was not found`);return e}return t},wC=()=>{try{if(typeof hu!="undefined"&&hu.url)return new URL("../widget.css",hu.url).href}catch{}return null},sy=(t,e)=>{let r=wC(),n=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let o=e.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);t.insertBefore(s,t.firstChild)};if(t instanceof ShadowRoot)if(r){let o=e.createElement("link");o.rel="stylesheet",o.href=r,o.setAttribute("data-persona","true"),t.insertBefore(o,t.firstChild)}else n();else if(!e.head.querySelector("link[data-persona]")&&r){let s=e.createElement("link");s.rel="stylesheet",s.href=r,s.setAttribute("data-persona","true"),e.head.appendChild(s)}},iy=t=>{let e=bC(t.target),r=t.useShadowDom===!0,n=e.ownerDocument,o=t.config,s=ti(e,o),a,i=[],d=(S,k)=>{var w,y;let M=!((y=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?y:!0)||Ar(k),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),M&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),r){let E=S.attachShadow({mode:"open"});E.appendChild(h),sy(E,n)}else S.appendChild(h),sy(S,n);return e.id&&h.setAttribute("data-persona-instance",e.id),h},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let S=d(s.host,o);a=ed(S,o,{debugTools:t.debugTools}),p()},u=()=>{i.forEach(S=>S()),i=[],a.destroy()};m(),t.onChatReady?t.onChatReady():t.onReady&&(ay||(ay=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),t.onReady());let f=S=>{u(),s.destroy(),s=ti(e,S),o=S,m()},x={update(S){var y,E,B,P,R,O;let k={...o,...S,launcher:{...(y=o==null?void 0:o.launcher)!=null?y:{},...(E=S==null?void 0:S.launcher)!=null?E:{},dock:{...(P=(B=o==null?void 0:o.launcher)==null?void 0:B.dock)!=null?P:{},...(O=(R=S==null?void 0:S.launcher)==null?void 0:R.dock)!=null?O:{}}}},T=Ar(o),M=Ar(k),h=Ho(o),w=Ho(k);if(T!==M||h!==w){f(k);return}o=k,s.updateConfig(o),a.update(S),l()},destroy(){u(),s.destroy(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}},C=new Proxy(x,{get(S,k,T){if(k==="host")return s.host;if(k in S)return Reflect.get(S,k,T);let M=a[k];return typeof M=="function"?M.bind(a):M}});return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=C),C};var uy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),vC=new Set(["button","a","input","select","textarea","details","summary"]),CC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xu=/\b(product|card|item|listing|result)\b/i,bu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,AC=3e3,SC=100;function fy(t){let e=typeof t.className=="string"?t.className:"";if(xu.test(e)||t.id&&xu.test(t.id))return!0;for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];if(n.name.startsWith("data-")&&xu.test(n.value))return!0}return!1}function my(t){var e;return bu.test(((e=t.textContent)!=null?e:"").trim())}function gy(t){var r;let e=t.querySelectorAll("a[href]");for(let n=0;n<e.length;n++){let o=(r=e[n].getAttribute("href"))!=null?r:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function TC(t){return!!t.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ly(t){let e=t.match(bu);return e?e[0]:null}function dy(t){var n,o,s;let e=(n=t.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:t.querySelector("a[href]");if(e&&((o=e.textContent)!=null&&o.trim())){let a=e.getAttribute("href");return{title:e.textContent.trim(),href:a&&a!=="#"?a:null}}let r=t.querySelector("h1, h2, h3, h4, h5, h6");return(s=r==null?void 0:r.textContent)!=null&&s.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function MC(t){let e=[],r=n=>{let o=n.trim();o&&!e.includes(o)&&e.push(o)};return t.querySelectorAll("button").forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('[role="button"]').forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;r((o=n.value)!=null?o:"")}),e.slice(0,6)}var kC="commerce-card",EC="result-card";function cy(t){return!fy(t)||!my(t)||!gy(t)&&!TC(t)?0:5200}function py(t){var n;return!fy(t)||my(t)||!gy(t)||((n=t.textContent)!=null?n:"").trim().length<20||!(!!t.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!t.querySelector(".snippet, .description, p"))?0:2800}var wu=[{id:kC,scoreElement(t){return cy(t)},shouldSuppressDescendant(t,e,r){if(e===t||!t.contains(e))return!1;if(r.interactivity==="static"){let n=r.text.trim();return!!(n.length===0||bu.test(n)&&n.length<32)}return!0},formatSummary(t,e){var d,l,p;if(cy(t)===0)return null;let{title:r,href:n}=dy(t),o=(p=(l=ly(((d=t.textContent)!=null?d:"").trim()))!=null?l:ly(e.text))!=null?p:"",s=MC(t);return[n&&r?`[${r}](${n})${o?` \u2014 ${o}`:""}`:r?`${r}${o?` \u2014 ${o}`:""}`:o||e.text.trim().slice(0,120),`selector: ${e.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
158
|
+
`)}},{id:EC,scoreElement(t){return py(t)},formatSummary(t,e){if(py(t)===0)return null;let{title:r,href:n}=dy(t);return[n&&r?`[${r}](${n})`:r||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
|
|
159
|
+
`)}}];function LC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function PC(t){var p,m,u,f,x,C,S,k,T,M,h,w,y;let e=(p=t.options)!=null?p:{},r=(u=(m=e.maxElements)!=null?m:t.maxElements)!=null?u:80,n=(x=(f=e.excludeSelector)!=null?f:t.excludeSelector)!=null?x:".persona-host",o=(S=(C=e.maxTextLength)!=null?C:t.maxTextLength)!=null?S:200,s=(T=(k=e.visibleOnly)!=null?k:t.visibleOnly)!=null?T:!0,a=(M=e.root)!=null?M:t.root,i=(h=e.mode)!=null?h:"structured",d=(w=e.maxCandidates)!=null?w:Math.max(500,r*10),l=(y=t.rules)!=null?y:wu;return i==="simple"&&t.rules&&t.rules.length>0?(LC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function yu(t){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/([^\w-])/g,"\\$1")}var IC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function RC(t){let e=t.tagName.toLowerCase(),r=t.getAttribute("role");return e==="a"&&t.hasAttribute("href")?"navigable":e==="input"||e==="select"||e==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":e==="button"||r==="button"||vC.has(e)||r&&CC.has(r)||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||t.getAttribute("contenteditable")==="true"?"clickable":"static"}function hy(t){if(t.hidden)return!1;try{let e=getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden")return!1}catch{}return!(t.style.display==="none"||t.style.visibility==="hidden")}function WC(t){let e={},r=t.id;r&&(e.id=r);let n=t.getAttribute("href");n&&(e.href=n);let o=t.getAttribute("aria-label");o&&(e["aria-label"]=o);let s=t.getAttribute("type");s&&(e.type=s);let a=t.getAttribute("value");a&&(e.value=a);let i=t.getAttribute("name");i&&(e.name=i);let d=t.getAttribute("role");d&&(e.role=d);for(let l=0;l<t.attributes.length;l++){let p=t.attributes[l];p.name.startsWith("data-")&&(e[p.name]=p.value)}return e}function vu(t){let e=t.tagName.toLowerCase();if(t.id){let o=`#${yu(t.id)}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of IC){let s=t.getAttribute(o);if(s){let a=`${e}[${o}="${yu(s)}"]`;try{if(t.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let r=Array.from(t.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${e}.${r.map(a=>yu(a)).join(".")}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=t.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${e}`)).indexOf(t);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(t.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=t.parentElement;if(n){let s=Array.from(n.querySelectorAll(`:scope > ${e}`)).indexOf(t);if(s>=0)return`${e}:nth-of-type(${s+1})`}return e}function BC(t){return t==="static"?SC:AC}function xy(t,e){var o;let r=t.tagName.toLowerCase(),n=((o=t.textContent)!=null?o:"").trim().substring(0,e);return{selector:vu(t),tagName:r,text:n,role:t.getAttribute("role"),interactivity:RC(t),attributes:WC(t)}}function HC(t,e,r,n){let o=BC(e.interactivity),s=null;for(let a of r){let i=a.scoreElement(t,e,n);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function DC(t,e){var r;for(let n of t)if(e.el!==n.el&&(r=n.formattingRule)!=null&&r.shouldSuppressDescendant&&n.el.contains(e.el)&&n.formattingRule.shouldSuppressDescendant(n.el,e.el,e.enriched))return!0;return!1}function OC(t,e){let r={doc:e.ownerDocument,maxTextLength:t.maxTextLength},n=new Set,o=[],s=0,a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<t.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(uy.has(p)){i=a.nextNode();continue}if(t.excludeSelector)try{if(l.closest(t.excludeSelector)){i=a.nextNode();continue}}catch{}if(t.visibleOnly&&!hy(l)){i=a.nextNode();continue}let m=xy(l,t.maxTextLength),u=m.text.length>0,f=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(S=>S==="role");if(!u&&!f){i=a.nextNode();continue}if(n.has(m.selector)){i=a.nextNode();continue}n.add(m.selector);let{score:x,formattingRule:C}=HC(l,m,t.rules,r);o.push({el:l,domIndex:s,enriched:m,score:x,formattingRule:C}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return m!==u?m-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=t.maxElements)break;DC(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return m!==u?m-u:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var u;let p;if((u=l.formattingRule)!=null&&u.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,r);f&&(p=f)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function NC(t,e){let r=[],n=new Set,o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&r.length<t.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(uy.has(l)){s=o.nextNode();continue}if(t.excludeSelector)try{if(d.closest(t.excludeSelector)){s=o.nextNode();continue}}catch{}if(t.visibleOnly&&!hy(d)){s=o.nextNode();continue}let p=xy(d,t.maxTextLength),m=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!m&&!u){s=o.nextNode();continue}n.has(p.selector)||(n.add(p.selector),r.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of r)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,t.maxElements)}function yy(t={}){var n;let e=PC(t),r=(n=e.root)!=null?n:document.body;return r?e.mode==="simple"?NC(e,r):OC(e,r):[]}var rd=100;function by(t,e={}){var s;if(t.length===0)return"No page elements found.";let r=(s=e.mode)!=null?s:"structured",n=[];if(r==="structured"){let a=t.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
|
|
160
160
|
${a.map(i=>`- ${i.split(`
|
|
161
161
|
`).join(`
|
|
162
162
|
`)}`).join(`
|
|
163
|
-
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of t)r==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
163
|
+
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of t)r==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,rd)}" (clickable)`);n.push(`Interactive elements:
|
|
164
164
|
${a.join(`
|
|
165
|
-
`)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
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,rd)}" (navigable)`);n.push(`Navigation links:
|
|
166
166
|
${a.join(`
|
|
167
|
-
`)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
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,rd)}" (input)`);n.push(`Form inputs:
|
|
168
168
|
${a.join(`
|
|
169
|
-
`)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
169
|
+
`)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,rd)}"`);n.push(`Content:
|
|
170
170
|
${a.join(`
|
|
171
171
|
`)}`)}return n.join(`
|
|
172
172
|
|
|
173
|
-
`)}var
|
|
173
|
+
`)}var wy={name:"@runtypelabs/persona",version:"3.29.1",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"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.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:launcher && pnpm run build:theme-ref && pnpm run build:codegen && 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:codegen":"tsup src/codegen.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","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},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 vy=wy.version;function Cy(){return{name:"@persona/accessibility",version:"1.0.0",transform(t){return{...t,semantic:{...t.semantic,colors:{...t.semantic.colors,interactive:{...t.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Ay(){return{name:"@persona/animations",version:"1.0.0",transform(t){return{...t,palette:{...t.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Sy(t){return{name:"@persona/brand",version:"1.0.0",transform(e){var n;let r={...e.palette};return(n=t.colors)!=null&&n.primary&&(r.colors={...r.colors,primary:{50:Yn(t.colors.primary,.95),100:Yn(t.colors.primary,.9),200:Yn(t.colors.primary,.8),300:Yn(t.colors.primary,.7),400:Yn(t.colors.primary,.6),500:t.colors.primary,600:Yn(t.colors.primary,.8),700:Yn(t.colors.primary,.7),800:Yn(t.colors.primary,.6),900:Yn(t.colors.primary,.5),950:Yn(t.colors.primary,.45)}}),{...e,palette:r}}}}function Ty(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(t){return{...t,palette:{...t.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(t){return{...t,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function My(){return{name:"@persona/high-contrast",version:"1.0.0",transform(t){return{...t,semantic:{...t.semantic,colors:{...t.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Yn(t,e){let r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16),s=Math.round(r+(255-r)*(1-e)),a=Math.round(n+(255-n)*(1-e)),i=Math.round(o+(255-o)*(1-e));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function ky(t){return{name:t.name,version:t.version,transform:t.transform||(e=>e),cssVariables:t.cssVariables,afterResolve:t.afterResolve}}var FC={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"}}},Ey={components:{panel:{borderRadius:"0",shadow:"none"}}},Cu={id:"shop",label:"Shopping Assistant",config:{theme:FC,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?"]}},Au={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ey}},Su={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ey}},Tu={shop:Cu,minimal:Au,fullscreen:Su};function Ly(t){return Tu[t]}var $C=`
|
|
174
174
|
@keyframes persona-stream-wipe {
|
|
175
175
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
176
176
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -206,7 +206,7 @@ ${a.join(`
|
|
|
206
206
|
mask-image: none !important;
|
|
207
207
|
}
|
|
208
208
|
}
|
|
209
|
-
`.trim(),
|
|
209
|
+
`.trim(),UC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:$C};pa(UC);var qC=`
|
|
210
210
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
211
211
|
animation: persona-stream-glyph-cycle-fade
|
|
212
212
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -224,7 +224,7 @@ ${a.join(`
|
|
|
224
224
|
opacity: 1 !important;
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`.trim(),
|
|
227
|
+
`.trim(),ri="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",zC=10,VC=120,Mu=120,jC=.4,GC=50,KC=t=>{var n;if(!t)return Mu;let r=((n=t.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Mu},Oy=t=>{let e=t.closest(".persona-stream-glyph-cycle"),r=KC(e);return VC*r/Mu},ku=t=>{let e=ri[Math.floor(Math.random()*ri.length)];return t&&e===t&&(e=ri[(ri.indexOf(e)+1)%ri.length]),e},XC=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let r=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let o of Array.from(r)){if(o===t){n=!0;continue}n&&Math.random()<jC&&(o.textContent=ku())}},Py=new WeakMap,Iy=25,Ry=.5,JC=6,Wy=.25,By=new WeakMap,Hy=new WeakMap,QC=(t,e)=>{var o;if(!t)return Iy*Ry;let r=By.get(t);By.set(t,e);let n=(o=Hy.get(t))!=null?o:Iy;if(r!==void 0){let s=e-r;s>1&&(n=n*(1-Wy)+s*Wy,Hy.set(t,n))}return Math.max(JC,n*Ry)},Xa=new Map,YC=t=>{var r;let e=t.closest("[data-message-id]");return(r=e==null?void 0:e.dataset.messageId)!=null?r:null},ZC=t=>{var e;t&&Xa.set(t,((e=Xa.get(t))!=null?e:0)+1)},eA=t=>{var r;if(!t)return;let e=(r=Xa.get(t))!=null?r:0;e<=1?Xa.delete(t):Xa.set(t,e-1)},Ny=t=>{var l;if(t.dataset.glyphCycleScheduled==="true")return;let e=(l=t.textContent)!=null?l:"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=ku();let r=YC(t);r&&(t.dataset.glyphCycleMessageId=r),ZC(r);let n=t.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=QC(n,o),a=Oy(t),i=zC*a,d=o+i;if(n){let p=Py.get(n);p!==void 0&&(d=Math.max(d,p)),Py.set(n,d+s)}tA(t,e,d)},tA=(t,e,r)=>{var a;if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let n=Oy(t),o=(a=t.textContent)!=null?a:void 0,s=()=>{var d;if(!t.isConnected)return;if(Date.now()>=r){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,eA((d=t.dataset.glyphCycleMessageId)!=null?d:null),delete t.dataset.glyphCycleMessageId;return}let i=ku(o);t.textContent=i,o=i,XC(t),setTimeout(s,n)};setTimeout(s,n)},Dy=t=>{var r;let e=(r=t.querySelectorAll)==null?void 0:r.call(t,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))Ny(n)},rA=t=>t.nodeType===1,nA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:qC,bufferContent(t){if(t.length<GC)return"";let e=0,r=-1,n=0;for(;n<t.length;){if(t[n]==="*"&&t[n+1]==="*"){e+=1,n+=2;continue}/\s/.test(t[n])&&e%2===0&&(r=n),n+=1}return r<0?"":t.slice(0,r)},isAnimating(t){var e;return((e=Xa.get(t.id))!=null?e:0)>0},onAttach(t){Dy(t);let e=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")?Ny(o):Dy(o))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};pa(nA);return Vy(oA);})();
|
|
228
228
|
/*! Bundled license information:
|
|
229
229
|
|
|
230
230
|
dompurify/dist/purify.es.mjs:
|