@runtypelabs/persona 3.30.0 → 3.31.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.
Files changed (50) hide show
  1. package/README.md +15 -2602
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
  5. package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +4 -4
  9. package/dist/codegen.js +3 -3
  10. package/dist/index.cjs +46 -46
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +52 -0
  13. package/dist/index.d.ts +52 -0
  14. package/dist/index.global.js +77 -80
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +45 -45
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +2 -2
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/smart-dom-reader.d.cts +50 -0
  21. package/dist/smart-dom-reader.d.ts +50 -0
  22. package/dist/theme-editor.cjs +39 -39
  23. package/dist/theme-editor.d.cts +50 -0
  24. package/dist/theme-editor.d.ts +50 -0
  25. package/dist/theme-editor.js +39 -39
  26. package/dist/theme-reference.cjs +1 -1
  27. package/dist/theme-reference.js +1 -1
  28. package/dist/webmcp-polyfill.js +4 -0
  29. package/dist/widget.css +19 -0
  30. package/package.json +4 -3
  31. package/src/client.ts +6 -0
  32. package/src/components/approval-bubble.test.ts +52 -0
  33. package/src/components/approval-bubble.ts +20 -0
  34. package/src/components/panel.ts +7 -1
  35. package/src/defaults.ts +14 -0
  36. package/src/generated/runtype-openapi-contract.ts +4 -0
  37. package/src/index-global.ts +39 -0
  38. package/src/session.test.ts +62 -0
  39. package/src/session.ts +27 -0
  40. package/src/styles/widget.css +19 -0
  41. package/src/theme-reference.ts +1 -1
  42. package/src/types.ts +50 -0
  43. package/src/ui.scroll.test.ts +383 -0
  44. package/src/ui.ts +390 -40
  45. package/src/utils/auto-follow.test.ts +91 -0
  46. package/src/utils/auto-follow.ts +68 -0
  47. package/src/version.ts +5 -2
  48. package/src/webmcp-bridge.test.ts +60 -0
  49. package/src/webmcp-bridge.ts +34 -1
  50. package/src/webmcp-polyfill.ts +16 -0
@@ -1,68 +1,65 @@
1
- "use strict";var AgentWidget=(()=>{var Ky=Object.create;var vs=Object.defineProperty;var Xy=Object.getOwnPropertyDescriptor;var Jy=Object.getOwnPropertyNames;var Qy=Object.getPrototypeOf,Yy=Object.prototype.hasOwnProperty;var Lg=t=>{throw TypeError(t)};var Zy=(t,e,r)=>e in t?vs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Yn=(t,e)=>()=>(t&&(e=t(t=0)),e);var Pg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ig=(t,e)=>{for(var r in e)vs(t,r,{get:e[r],enumerable:!0})},Rg=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jy(e))!Yy.call(t,o)&&o!==r&&vs(t,o,{get:()=>e[o],enumerable:!(n=Xy(e,o))||n.enumerable});return t};var ld=(t,e,r)=>(r=t!=null?Ky(Qy(t)):{},Rg(e||!t||!t.__esModule?vs(r,"default",{value:t,enumerable:!0}):r,t)),eb=t=>Rg(vs({},"__esModule",{value:!0}),t);var Ft=(t,e,r)=>Zy(t,typeof e!="symbol"?e+"":e,r),tb=(t,e,r)=>e.has(t)||Lg("Cannot "+r);var Wg=(t,e,r)=>e.has(t)?Lg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Si=(t,e,r)=>(tb(t,e,"access private method"),r);function Ba(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(!Ba(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(!Ba(t[a],e[a]))return!1;return!0}return t===e}var kd=Yn(()=>{"use strict"});function bn(t){return encodeURI(i0(t))}function i0(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Wi=Yn(()=>{"use strict"});function go(t,e=Object.create(null),r=p0,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:go(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(c0[s])continue;let a=`${n}/${bn(s)}`,i=t[s];if(Array.isArray(i)){if(l0[s]){let d=i.length;for(let l=0;l<d;l++)go(i[l],e,r,`${a}/${l}`)}}else if(d0[s])for(let d in i)go(i[d],e,r,`${a}/${bn(d)}`);else go(i,e,r,a)}return e}var l0,d0,c0,p0,Bi=Yn(()=>{"use strict";Wi();l0={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},d0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},c0={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},p0=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 eo(t){return t.test.bind(t)}function k0(t){return t%4===0&&(t%100!==0||t%400===0)}function mh(t){let e=t.match(u0);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&k0(r)?29:f0[n])}function gh(t,e){let r=e.match(m0);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 L0(t){let e=t.split(E0);return e.length==2&&mh(e[0])&&gh(!0,e[1])}function R0(t){return P0.test(t)&&I0.test(t)}function B0(t){if(W0.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var u0,f0,m0,g0,h0,x0,y0,b0,w0,v0,C0,A0,S0,T0,M0,Ed,E0,P0,I0,W0,Ld=Yn(()=>{"use strict";u0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,f0=[0,31,28,31,30,31,30,31,31,30,31,30,31],m0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,g0=/^(?=.{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,h0=/^(?:[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,x0=/^(?:(?:[^\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,y0=/^(?:(?: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,b0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,w0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,v0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,C0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,A0=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))},S0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,T0=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,M0=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));Ed={date:mh,time:gh.bind(void 0,!1),"date-time":L0,duration:M0,uri:R0,"uri-reference":eo(h0),"uri-template":eo(x0),url:eo(y0),email:A0,hostname:eo(g0),ipv4:eo(S0),ipv6:eo(T0),regex:B0,uuid:eo(b0),"json-pointer":eo(w0),"json-pointer-uri-fragment":eo(v0),"relative-json-pointer":eo(C0)};E0=/t|\s/i;P0=/\/|:/,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;W0=/[^\\]\\Z/});var hh,xh=Yn(()=>{"use strict";(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(hh||(hh={}))});function yh(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 Pd=Yn(()=>{"use strict"});function mr(t,e,r="2019-09",n=go(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:u,$recursiveRef:f,$recursiveAnchor:m,type:y,const:x,enum:S,required:M,not:k,anyOf:T,allOf:h,oneOf:C,if:w,then:E,else:W,format:P,properties:R,patternProperties:N,additionalProperties:j,unevaluatedProperties:oe,minProperties:ve,maxProperties:nt,propertyNames:Te,dependentRequired:$e,dependentSchemas:Se,dependencies:Xe,prefixItems:He,items:V,additionalItems:be,unevaluatedItems:G,contains:Ae,minContains:J,maxContains:ie,minItems:Me,maxItems:Ge,uniqueItems:ce,minimum:re,maximum:le,exclusiveMinimum:gt,exclusiveMaximum:ke,multipleOf:ye,minLength:tt,maxLength:Ue,pattern:he,__absolute_ref__:Q,__absolute_recursive_ref__:Ve}=e,ee=[];if(m===!0&&s===null&&(s=e),f==="#"){let z=s===null?n[Ve]:s,De=`${i}/$recursiveRef`,Le=mr(t,s===null?e:s,r,n,o,z,a,De,d);Le.valid||ee.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:De,error:"A subschema had errors."},...Le.errors)}if(u!==void 0){let De=n[Q||u];if(De===void 0){let ue=`Unresolved $ref "${u}".`;throw Q&&Q!==u&&(ue+=` Absolute URI "${Q}".`),ue+=`
2
- Known schemas:
3
- - ${Object.keys(n).join(`
4
- - `)}`,new Error(ue)}let Le=`${i}/$ref`,ge=mr(t,De,r,n,o,s,a,Le,d);if(ge.valid||ee.push({instanceLocation:a,keyword:"$ref",keywordLocation:Le,error:"A subschema had errors."},...ge.errors),r==="4"||r==="7")return{valid:ee.length===0,errors:ee}}if(Array.isArray(y)){let z=y.length,De=!1;for(let Le=0;Le<z;Le++)if(p===y[Le]||y[Le]==="integer"&&p==="number"&&t%1===0&&t===t){De=!0;break}De||ee.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)&&ee.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`}):y!==void 0&&p!==y&&ee.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`});if(x!==void 0&&(p==="object"||p==="array"?Ba(t,x)||ee.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(x)}.`}):t!==x&&ee.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(x)}.`})),S!==void 0&&(p==="object"||p==="array"?S.some(z=>Ba(t,z))||ee.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(z=>t===z)||ee.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`;mr(t,k,r,n,o,s,a,z).valid&&ee.push({instanceLocation:a,keyword:"not",keywordLocation:z,error:'Instance matched "not" schema.'})}let xe=[];if(T!==void 0){let z=`${i}/anyOf`,De=ee.length,Le=!1;for(let ge=0;ge<T.length;ge++){let ue=T[ge],Oe=Object.create(d),Z=mr(t,ue,r,n,o,m===!0?s:null,a,`${z}/${ge}`,Oe);ee.push(...Z.errors),Le=Le||Z.valid,Z.valid&&xe.push(Oe)}Le?ee.length=De:ee.splice(De,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:z,error:"Instance does not match any subschemas."})}if(h!==void 0){let z=`${i}/allOf`,De=ee.length,Le=!0;for(let ge=0;ge<h.length;ge++){let ue=h[ge],Oe=Object.create(d),Z=mr(t,ue,r,n,o,m===!0?s:null,a,`${z}/${ge}`,Oe);ee.push(...Z.errors),Le=Le&&Z.valid,Z.valid&&xe.push(Oe)}Le?ee.length=De:ee.splice(De,0,{instanceLocation:a,keyword:"allOf",keywordLocation:z,error:"Instance does not match every subschema."})}if(C!==void 0){let z=`${i}/oneOf`,De=ee.length,Le=C.filter((ge,ue)=>{let Oe=Object.create(d),Z=mr(t,ge,r,n,o,m===!0?s:null,a,`${z}/${ue}`,Oe);return ee.push(...Z.errors),Z.valid&&xe.push(Oe),Z.valid}).length;Le===1?ee.length=De:ee.splice(De,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:z,error:`Instance does not match exactly one subschema (${Le} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...xe),w!==void 0){let z=`${i}/if`;if(mr(t,w,r,n,o,s,a,z,d).valid){if(E!==void 0){let Le=mr(t,E,r,n,o,s,a,`${i}/then`,d);Le.valid||ee.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "then" schema.'},...Le.errors)}}else if(W!==void 0){let Le=mr(t,W,r,n,o,s,a,`${i}/else`,d);Le.valid||ee.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "else" schema.'},...Le.errors)}}if(p==="object"){if(M!==void 0)for(let ge of M)ge in t||ee.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${ge}".`});let z=Object.keys(t);if(ve!==void 0&&z.length<ve&&ee.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${ve} properties.`}),nt!==void 0&&z.length>nt&&ee.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${nt} properties.`}),Te!==void 0){let ge=`${i}/propertyNames`;for(let ue in t){let Oe=`${a}/${bn(ue)}`,Z=mr(ue,Te,r,n,o,s,Oe,ge);Z.valid||ee.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ge,error:`Property name "${ue}" does not match schema.`},...Z.errors)}}if($e!==void 0){let ge=`${i}/dependantRequired`;for(let ue in $e)if(ue in t){let Oe=$e[ue];for(let Z of Oe)Z in t||ee.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:ge,error:`Instance has "${ue}" but does not have "${Z}".`})}}if(Se!==void 0)for(let ge in Se){let ue=`${i}/dependentSchemas`;if(ge in t){let Oe=mr(t,Se[ge],r,n,o,s,a,`${ue}/${bn(ge)}`,d);Oe.valid||ee.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:ue,error:`Instance has "${ge}" but does not match dependant schema.`},...Oe.errors)}}if(Xe!==void 0){let ge=`${i}/dependencies`;for(let ue in Xe)if(ue in t){let Oe=Xe[ue];if(Array.isArray(Oe))for(let Z of Oe)Z in t||ee.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ge,error:`Instance has "${ue}" but does not have "${Z}".`});else{let Z=mr(t,Oe,r,n,o,s,a,`${ge}/${bn(ue)}`);Z.valid||ee.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ge,error:`Instance has "${ue}" but does not match dependant schema.`},...Z.errors)}}}let De=Object.create(null),Le=!1;if(R!==void 0){let ge=`${i}/properties`;for(let ue in R){if(!(ue in t))continue;let Oe=`${a}/${bn(ue)}`,Z=mr(t[ue],R[ue],r,n,o,s,Oe,`${ge}/${bn(ue)}`);if(Z.valid)d[ue]=De[ue]=!0;else if(Le=o,ee.push({instanceLocation:a,keyword:"properties",keywordLocation:ge,error:`Property "${ue}" does not match schema.`},...Z.errors),Le)break}}if(!Le&&N!==void 0){let ge=`${i}/patternProperties`;for(let ue in N){let Oe=new RegExp(ue,"u"),Z=N[ue];for(let O in t){if(!Oe.test(O))continue;let Ie=`${a}/${bn(O)}`,Ne=mr(t[O],Z,r,n,o,s,Ie,`${ge}/${bn(ue)}`);Ne.valid?d[O]=De[O]=!0:(Le=o,ee.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:ge,error:`Property "${O}" matches pattern "${ue}" but does not match associated schema.`},...Ne.errors))}}}if(!Le&&j!==void 0){let ge=`${i}/additionalProperties`;for(let ue in t){if(De[ue])continue;let Oe=`${a}/${bn(ue)}`,Z=mr(t[ue],j,r,n,o,s,Oe,ge);Z.valid?d[ue]=!0:(Le=o,ee.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:ge,error:`Property "${ue}" does not match additional properties schema.`},...Z.errors))}}else if(!Le&&oe!==void 0){let ge=`${i}/unevaluatedProperties`;for(let ue in t)if(!d[ue]){let Oe=`${a}/${bn(ue)}`,Z=mr(t[ue],oe,r,n,o,s,Oe,ge);Z.valid?d[ue]=!0:ee.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:ge,error:`Property "${ue}" does not match unevaluated properties schema.`},...Z.errors)}}}else if(p==="array"){Ge!==void 0&&t.length>Ge&&ee.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${t.length} > ${Ge}).`}),Me!==void 0&&t.length<Me&&ee.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${t.length} < ${Me}).`});let z=t.length,De=0,Le=!1;if(He!==void 0){let ge=`${i}/prefixItems`,ue=Math.min(He.length,z);for(;De<ue;De++){let Oe=mr(t[De],He[De],r,n,o,s,`${a}/${De}`,`${ge}/${De}`);if(d[De]=!0,!Oe.valid&&(Le=o,ee.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:ge,error:"Items did not match schema."},...Oe.errors),Le))break}}if(V!==void 0){let ge=`${i}/items`;if(Array.isArray(V)){let ue=Math.min(V.length,z);for(;De<ue;De++){let Oe=mr(t[De],V[De],r,n,o,s,`${a}/${De}`,`${ge}/${De}`);if(d[De]=!0,!Oe.valid&&(Le=o,ee.push({instanceLocation:a,keyword:"items",keywordLocation:ge,error:"Items did not match schema."},...Oe.errors),Le))break}}else for(;De<z;De++){let ue=mr(t[De],V,r,n,o,s,`${a}/${De}`,ge);if(d[De]=!0,!ue.valid&&(Le=o,ee.push({instanceLocation:a,keyword:"items",keywordLocation:ge,error:"Items did not match schema."},...ue.errors),Le))break}if(!Le&&be!==void 0){let ue=`${i}/additionalItems`;for(;De<z;De++){let Oe=mr(t[De],be,r,n,o,s,`${a}/${De}`,ue);d[De]=!0,Oe.valid||(Le=o,ee.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:ue,error:"Items did not match additional items schema."},...Oe.errors))}}}if(Ae!==void 0)if(z===0&&J===void 0)ee.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(J!==void 0&&z<J)ee.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${z}) than minContains (${J}).`});else{let ge=`${i}/contains`,ue=ee.length,Oe=0;for(let Z=0;Z<z;Z++){let O=mr(t[Z],Ae,r,n,o,s,`${a}/${Z}`,ge);O.valid?(d[Z]=!0,Oe++):ee.push(...O.errors)}Oe>=(J||0)&&(ee.length=ue),J===void 0&&ie===void 0&&Oe===0?ee.splice(ue,0,{instanceLocation:a,keyword:"contains",keywordLocation:ge,error:"Array does not contain item matching schema."}):J!==void 0&&Oe<J?ee.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${J} items matching schema. Only ${Oe} items were found.`}):ie!==void 0&&Oe>ie&&ee.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${ie} items matching schema. ${Oe} items were found.`})}if(!Le&&G!==void 0){let ge=`${i}/unevaluatedItems`;for(De;De<z;De++){if(d[De])continue;let ue=mr(t[De],G,r,n,o,s,`${a}/${De}`,ge);d[De]=!0,ue.valid||ee.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:ge,error:"Items did not match unevaluated items schema."},...ue.errors)}}if(ce)for(let ge=0;ge<z;ge++){let ue=t[ge],Oe=typeof ue=="object"&&ue!==null;for(let Z=0;Z<z;Z++){if(ge===Z)continue;let O=t[Z];(ue===O||Oe&&(typeof O=="object"&&O!==null)&&Ba(ue,O))&&(ee.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${ge} and ${Z}.`}),ge=Number.MAX_SAFE_INTEGER,Z=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(re!==void 0&&(gt===!0&&t<=re||t<re)&&ee.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${gt?"or equal to ":""} ${re}.`}),le!==void 0&&(ke===!0&&t>=le||t>le)&&ee.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${ke?"or equal to ":""} ${le}.`})):(re!==void 0&&t<re&&ee.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${re}.`}),le!==void 0&&t>le&&ee.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${le}.`}),gt!==void 0&&t<=gt&&ee.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${t} is less than ${gt}.`}),ke!==void 0&&t>=ke&&ee.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${t} is greater than or equal to ${ke}.`})),ye!==void 0){let z=t%ye;Math.abs(0-z)>=11920929e-14&&Math.abs(ye-z)>=11920929e-14&&ee.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${t} is not a multiple of ${ye}.`})}}else if(p==="string"){let z=tt===void 0&&Ue===void 0?0:yh(t);tt!==void 0&&z<tt&&ee.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${z} < ${tt}).`}),Ue!==void 0&&z>Ue&&ee.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${z} > ${Ue}).`}),he!==void 0&&!new RegExp(he,"u").test(t)&&ee.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),P!==void 0&&Ed[P]&&!Ed[P](t)&&ee.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${P}".`})}return{valid:ee.length===0,errors:ee}}var Id=Yn(()=>{"use strict";kd();Bi();Ld();Wi();Pd()});var Hi,bh=Yn(()=>{"use strict";Bi();Id();Hi=class{constructor(e,r="2019-09",n=!0){Ft(this,"schema");Ft(this,"draft");Ft(this,"shortCircuit");Ft(this,"lookup");this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=go(e)}validate(e){return mr(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),go(e,this.lookup)}}});var wh=Yn(()=>{"use strict";kd();Bi();Ld();Wi();xh();Pd();Id();bh()});var Ih={};Ig(Ih,{cleanupWebMCPPolyfill:()=>Ph,initializeWebMCPPolyfill:()=>Lh,initializeWebModelContextPolyfill:()=>Lh,isPlainObject:()=>Fr,validateArgsWithSchema:()=>Mh});function to(t){try{return new DOMException(t,"UnknownError")}catch{let e=new Error(t);return e.name="UnknownError",e}}function _0(t){let e;try{e=JSON.parse(t)}catch{throw to(vh)}if(!e||typeof e!="object"||Array.isArray(e))throw to(vh);return e}function F0(t){if(typeof t=="string")return t;if(Fr(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 Fr(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Sh(t){if(!Fr(t))return null;let e=t["~standard"];return Fr(e)?e:null}function $0(t){let e=Sh(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function U0(t){let e=Sh(t);return!e||e.version!==1||!Fr(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(!Fr(e))return{issues:[{message:"expected object arguments"}]};let r=Mh(e,t);return r?{issues:[r]}:{value:e}}}}}function q0(t){for(let e of H0)try{let r=t["~standard"].jsonSchema.input({target:e});return Th(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 z0(t){if(t===void 0){let r=Di;return{inputSchema:r,standardValidator:Oi(r)}}if(U0(t)){let r=q0(t);return{inputSchema:r,standardValidator:Oi(r)}}if($0(t))return{inputSchema:Di,standardValidator:t};if(Th(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 Th(t){if(!Fr(t))throw new Error("inputSchema must be a JSON Schema object");Ha(t,"$")}function Ha(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(!Fr(o))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Fr(d))throw new Error(`Invalid JSON Schema at ${e}.properties.${i}: expected object schema`);Ha(d,`${e}.properties.${i}`)}}let s=t.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Fr(d))throw new Error(`Invalid JSON Schema at ${e}.items[${i}]: expected object schema`);Ha(d,`${e}.items[${i}]`)}else if(Fr(s))Ha(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(!Fr(p))throw new Error(`Invalid JSON Schema at ${e}.${i}[${l}]: expected object schema`);Ha(p,`${e}.${i}[${l}]`)}}}let a=t.not;if(a!==void 0){if(!Fr(a))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);Ha(a,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function V0(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=z0(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,[Ah]:r.standardValidator}}function Mh(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 j0(t){if(!t||t.length===0)return null;let e=t.map(r=>Fr(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 G0(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=j0(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function K0(t,e){return G0(t,e[Ah])}function X0(t){return Fr(t)&&Array.isArray(t.content)}function J0(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Wd(t){return J0(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>Wd(e)):Fr(t)?Object.values(t).every(e=>Wd(e)):!1}function Q0(t){if(!(!Fr(t)||!Wd(t)))return t}function Y0(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(X0(t))return t;let e=Q0(t);return{content:[{type:"text",text:Y0(t)}],...e?{structuredContent:e}:{},isError:!1}}function ew(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 tw(t){var r;if(t.isError)throw to(((r=ew(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 to(Ni)}}function rw(t,e){return e?e.aborted?Promise.reject(to(Rd)):new Promise((r,n)=>{let o=()=>{s(),n(to(Rd))},s=()=>{e.removeEventListener("abort",o)};e.addEventListener("abort",o,{once:!0}),t.then(a=>{s(),r(a)},a=>{s(),n(a)})}):t}function kh(){return typeof navigator!="undefined"?navigator:null}function Eh(){return typeof document!="undefined"?document:null}function nw(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function Ch(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}function ow(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 Lh(t){var d;let e=kh(),r=Eh();if(!e&&!r||(r==null?void 0:r.modelContext))return;let o=e==null?void 0:e.modelContext,s=!!o;if(pr.installed&&Ph(),r&&o){pr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),Ch(r,o),pr.installedDocumentModelContext=!0,pr.installed=!0;return}if(s)return;let a=new O0,i=a;if(i[D0]=!0,r&&(pr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),Ch(r,i),pr.installedDocumentModelContext=!0),e){pr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),pr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),_i=!1,ow(e,i),pr.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)&&(nw(e,"modelContextTesting",a.getTestingShim()),pr.installedNavigatorModelContextTesting=!0)}pr.installed=!0}function Ph(){if(!pr.installed)return;let t=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},e=kh(),r=Eh();r&&pr.installedDocumentModelContext&&t(r,"modelContext",pr.previousDocumentModelContextDescriptor),e&&pr.installedNavigatorModelContext&&t(e,"modelContext",pr.previousNavigatorModelContextDescriptor),e&&pr.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",pr.previousNavigatorModelContextTestingDescriptor),pr.installed=!1,pr.previousDocumentModelContextDescriptor=void 0,pr.previousNavigatorModelContextDescriptor=void 0,pr.previousNavigatorModelContextTestingDescriptor=void 0,pr.installedDocumentModelContext=!1,pr.installedNavigatorModelContext=!1,pr.installedNavigatorModelContextTesting=!1,_i=!1}var vh,Ni,Rd,Di,H0,D0,Ah,pr,O0,N0,_i,Rh=Yn(()=>{"use strict";wh();vh="Failed to parse input arguments",Ni="Tool was executed but the invocation failed. For example, the script function threw an error",Rd="Tool was cancelled",Di={type:"object",properties:{}},H0=["draft-2020-12","draft-07"],D0="__isWebMCPPolyfill",Ah=Symbol("standardValidator"),pr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},O0=class extends EventTarget{constructor(){super(...arguments);Ft(this,"tools",new Map);Ft(this,"testingShim",null);Ft(this,"_ontoolchange",null);Ft(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=V0(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=F0(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 N0(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 to(Rd);let s=this.tools.get(e);if(!s)throw to(`Tool not found: ${e}`);let a=_0(r),i=await K0(a,s);if(i)throw to(i);let d=!0,l={requestUserInteraction:async u=>{if(!d)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof u!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return u()}};try{let u=s.execute(a,l),f=await rw(Promise.resolve(u),n==null?void 0:n.signal);if(o)return tw(Z0(f));let m=JSON.stringify(f);return m===void 0?null:m}catch(u){throw to(u instanceof Error?`${Ni}: ${u.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."))}},N0=class extends EventTarget{constructor(e){super();Ft(this,"context");Ft(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{Lh(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}});var Dd=Pg(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.Allow=Qe.ALL=Qe.COLLECTION=Qe.ATOM=Qe.SPECIAL=Qe.INF=Qe._INFINITY=Qe.INFINITY=Qe.NAN=Qe.BOOL=Qe.NULL=Qe.OBJ=Qe.ARR=Qe.NUM=Qe.STR=void 0;Qe.STR=1;Qe.NUM=2;Qe.ARR=4;Qe.OBJ=8;Qe.NULL=16;Qe.BOOL=32;Qe.NAN=64;Qe.INFINITY=128;Qe._INFINITY=256;Qe.INF=Qe.INFINITY|Qe._INFINITY;Qe.SPECIAL=Qe.NULL|Qe.BOOL|Qe.INF|Qe.NAN;Qe.ATOM=Qe.STR|Qe.NUM|Qe.SPECIAL;Qe.COLLECTION=Qe.ARR|Qe.OBJ;Qe.ALL=Qe.ATOM|Qe.COLLECTION;Qe.Allow={STR:Qe.STR,NUM:Qe.NUM,ARR:Qe.ARR,OBJ:Qe.OBJ,NULL:Qe.NULL,BOOL:Qe.BOOL,NAN:Qe.NAN,INFINITY:Qe.INFINITY,_INFINITY:Qe._INFINITY,INF:Qe.INF,SPECIAL:Qe.SPECIAL,ATOM:Qe.ATOM,COLLECTION:Qe.COLLECTION,ALL:Qe.ALL};Qe.default=Qe.Allow});var zi=Pg($r=>{"use strict";var fw=$r&&$r.__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]})),mw=$r&&$r.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fw(e,t,r)};Object.defineProperty($r,"__esModule",{value:!0});$r.Allow=$r.MalformedJSON=$r.PartialJSON=$r.parseJSON=$r.parse=void 0;var tn=Dd();Object.defineProperty($r,"Allow",{enumerable:!0,get:function(){return tn.Allow}});mw(Dd(),$r);var Ui=class extends Error{};$r.PartialJSON=Ui;var qi=class extends Error{};$r.MalformedJSON=qi;function Dh(t,e=tn.Allow.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return gw(t.trim(),e)}$r.parseJSON=Dh;var gw=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Ui(`${f} at position ${n}`)},s=f=>{throw new qi(`${f} at position ${n}`)},a=()=>(u(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?d():t[n]==="["?l():t.substring(n,n+4)==="null"||tn.Allow.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||tn.Allow.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||tn.Allow.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||tn.Allow.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||tn.Allow._INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||tn.Allow.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):p()),i=()=>{let f=n,m=!1;for(n++;n<r&&(t[n]!=='"'||m&&t[n-1]==="\\");)m=t[n]==="\\"?!m:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(m)))}catch(y){s(String(y))}else if(tn.Allow.STR&e)try{return JSON.parse(t.substring(f,n-Number(m))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,u();let f={};try{for(;t[n]!=="}";){if(u(),n>=r&&tn.Allow.OBJ&e)return f;let m=i();u(),n++;try{let y=a();f[m]=y}catch(y){if(tn.Allow.OBJ&e)return f;throw y}u(),t[n]===","&&n++}}catch{if(tn.Allow.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(a()),u(),t[n]===","&&n++}catch{if(tn.Allow.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},p=()=>{if(n===0){t==="-"&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(m){if(tn.Allow.NUM&e)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(m))}}let f=n;for(t[n]==="-"&&n++;t[n]&&",]}".indexOf(t[n])===-1;)n++;n==r&&!(tn.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(y){s(String(y))}}},u=()=>{for(;n<r&&`
5
- \r `.includes(t[n]);)n++};return a()},hw=Dh;$r.parse=hw});var mA={};Ig(mA,{ASK_USER_QUESTION_TOOL_NAME:()=>ru,AgentWidgetClient:()=>ca,AgentWidgetSession:()=>_a,AttachmentManager:()=>ma,DEFAULT_COMPONENTS:()=>Dp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>xl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>wn,DEFAULT_PALETTE:()=>Bp,DEFAULT_SEMANTIC:()=>Hp,DEFAULT_WIDGET_CONFIG:()=>nr,PRESETS:()=>Eu,PRESET_FULLSCREEN:()=>ku,PRESET_MINIMAL:()=>Mu,PRESET_SHOP:()=>Tu,THEME_ZONES:()=>ox,VERSION:()=>Py,WEBMCP_TOOL_PREFIX:()=>ho,WebMcpBridge:()=>Da,accessibilityPlugin:()=>Iy,animationsPlugin:()=>Ry,applyThemeVariables:()=>Do,attachHeaderToContainer:()=>ha,brandPlugin:()=>Wy,buildComposer:()=>za,buildDefaultHeader:()=>jp,buildHeader:()=>bo,buildHeaderWithLayout:()=>qa,buildMinimalHeader:()=>Gp,collectEnrichedPageContext:()=>ky,componentRegistry:()=>Co,createActionManager:()=>oi,createAgentExperience:()=>nd,createAskUserQuestionBubble:()=>Nx,createBestAvailableVoiceProvider:()=>al,createBubbleWithLayout:()=>Ax,createCSATFeedback:()=>ed,createComboButton:()=>Wl,createComponentMiddleware:()=>sy,createComponentStreamParser:()=>Jl,createDefaultSanitizer:()=>Md,createDirectivePostprocessor:()=>Zg,createDropdownMenu:()=>Fo,createFlexibleJsonStreamParser:()=>_h,createIconButton:()=>Wr,createImagePart:()=>jh,createJsonStreamParser:()=>Qi,createLabelButton:()=>Qs,createLocalStorageAdapter:()=>Xl,createMarkdownProcessor:()=>Es,createMarkdownProcessorFromConfig:()=>ia,createMessageActions:()=>Yp,createNPSFeedback:()=>td,createPlainTextParser:()=>Xi,createPlugin:()=>Dy,createRegexJsonParser:()=>Ji,createStandardBubble:()=>Va,createTextPart:()=>Ds,createTheme:()=>$a,createThemeObserver:()=>vl,createToggleGroup:()=>hx,createTypingIndicator:()=>xa,createVoiceProvider:()=>fa,createWidgetHostLayout:()=>ai,createXmlParser:()=>Yi,defaultActionHandlers:()=>wa,defaultJsonActionParser:()=>ni,defaultParseRules:()=>Au,detectColorScheme:()=>$s,directivePostprocessor:()=>eh,ensureAskUserQuestionSheet:()=>Ja,escapeHtml:()=>la,extractComponentDirectiveFromMessage:()=>Zl,fileToImagePart:()=>Gh,formatEnrichedContext:()=>Ey,generateAssistantMessageId:()=>pa,generateMessageId:()=>$h,generateStableSelector:()=>Su,generateUserMessageId:()=>Na,getActiveTheme:()=>Ua,getColorScheme:()=>Np,getDisplayText:()=>qh,getHeaderLayout:()=>Kp,getImageParts:()=>Vh,getPreset:()=>Ny,hasComponentDirective:()=>Yl,hasImages:()=>zh,headerLayouts:()=>Bl,highContrastPlugin:()=>Hy,initAgentWidget:()=>hy,isAskUserQuestionMessage:()=>wo,isComponentDirectiveType:()=>ay,isDockedMountMode:()=>kr,isVoiceSupported:()=>Ns,isWebMcpToolName:()=>Ho,listRegisteredStreamAnimations:()=>Up,markdownPostprocessor:()=>xd,mergeWithDefaults:()=>yl,normalizeContent:()=>Uh,parseAskUserQuestionPayload:()=>vo,pluginRegistry:()=>ri,reducedMotionPlugin:()=>By,registerStreamAnimationPlugin:()=>ga,removeAskUserQuestionSheet:()=>qo,renderComponentDirective:()=>Ql,renderLoadingIndicatorWithFallback:()=>Qp,renderLucideIcon:()=>Be,resolveDockConfig:()=>Wn,resolveSanitizer:()=>Wa,resolveTokens:()=>bl,stripWebMcpPrefix:()=>$i,themeToCssVariables:()=>wl,unregisterStreamAnimationPlugin:()=>$p,validateImageFile:()=>Kh,validateTheme:()=>Op});function pd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var sa=pd();function _g(t){sa=t}var Fg=/[&<>"']/,rb=new RegExp(Fg.source,"g"),$g=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,nb=new RegExp($g.source,"g"),ob={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Bg=t=>ob[t];function xn(t,e){if(e){if(Fg.test(t))return t.replace(rb,Bg)}else if($g.test(t))return t.replace(nb,Bg);return t}var ab=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function sb(t){return t.replace(ab,(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 ib=/(^|[^\[])\^/g;function ir(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(ib,"$1"),r=r.replace(o,a),n},getRegex:()=>new RegExp(r,e)};return n}function Hg(t){try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}var As={exec:()=>null};function Dg(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 lb(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 Og(t,e,r,n){let o=e.href,s=e.title?xn(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:xn(a)}}function db(t,e){let r=t.match(/^(\s+)(?:```)/);if(r===null)return e;let n=r[1];return e.split(`
6
- `).map(o=>{let s=o.match(/^\s+/);if(s===null)return o;let[a]=s;return a.length>=n.length?o.slice(n.length):o}).join(`
7
- `)}var Ia=class{constructor(e){Ft(this,"options");Ft(this,"rules");Ft(this,"lexer");this.options=e||sa}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=db(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,`
1
+ "use strict";var AgentWidget=(()=>{var Ub=Object.create;var ws=Object.defineProperty;var qb=Object.getOwnPropertyDescriptor;var zb=Object.getOwnPropertyNames;var $b=Object.getPrototypeOf,Vb=Object.prototype.hasOwnProperty;var Rg=r=>{throw TypeError(r)};var jb=(r,e,t)=>e in r?ws(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Gb=(r=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(r,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):r)(function(r){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Ig=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Kb=(r,e)=>{for(var t in e)ws(r,t,{get:e[t],enumerable:!0})},Wg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zb(e))!Vb.call(r,o)&&o!==t&&ws(r,o,{get:()=>e[o],enumerable:!(n=qb(e,o))||n.enumerable});return r};var Ai=(r,e,t)=>(t=r!=null?Ub($b(r)):{},Wg(e||!r||!r.__esModule?ws(t,"default",{value:r,enumerable:!0}):t,r)),Xb=r=>Wg(ws({},"__esModule",{value:!0}),r);var pr=(r,e,t)=>jb(r,typeof e!="symbol"?e+"":e,t),Qb=(r,e,t)=>e.has(r)||Rg("Cannot "+t);var Hg=(r,e,t)=>e.has(r)?Rg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t);var Si=(r,e,t)=>(Qb(r,e,"access private method"),t);var Td=Ig(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 Fi=Ig(Or=>{"use strict";var c0=Or&&Or.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),p0=Or&&Or.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&c0(e,r,t)};Object.defineProperty(Or,"__esModule",{value:!0});Or.Allow=Or.MalformedJSON=Or.PartialJSON=Or.parseJSON=Or.parse=void 0;var tn=Td();Object.defineProperty(Or,"Allow",{enumerable:!0,get:function(){return tn.Allow}});p0(Td(),Or);var Bi=class extends Error{};Or.PartialJSON=Bi;var Di=class extends Error{};Or.MalformedJSON=Di;function yh(r,e=tn.Allow.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return u0(r.trim(),e)}Or.parseJSON=yh;var u0=(r,e)=>{let t=r.length,n=0,o=u=>{throw new Bi(`${u} at position ${n}`)},a=u=>{throw new Di(`${u} at position ${n}`)},s=()=>(f(),n>=t&&o("Unexpected end of input"),r[n]==='"'?i():r[n]==="{"?d():r[n]==="["?l():r.substring(n,n+4)==="null"||tn.Allow.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||tn.Allow.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||tn.Allow.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||tn.Allow.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||tn.Allow._INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||tn.Allow.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):p()),i=()=>{let u=n,m=!1;for(n++;n<t&&(r[n]!=='"'||m&&r[n-1]==="\\");)m=r[n]==="\\"?!m:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(u,++n-Number(m)))}catch(v){a(String(v))}else if(tn.Allow.STR&e)try{return JSON.parse(r.substring(u,n-Number(m))+'"')}catch{return JSON.parse(r.substring(u,r.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,f();let u={};try{for(;r[n]!=="}";){if(f(),n>=t&&tn.Allow.OBJ&e)return u;let m=i();f(),n++;try{let v=s();u[m]=v}catch(v){if(tn.Allow.OBJ&e)return u;throw v}f(),r[n]===","&&n++}}catch{if(tn.Allow.OBJ&e)return u;o("Expected '}' at end of object")}return n++,u},l=()=>{n++;let u=[];try{for(;r[n]!=="]";)u.push(s()),f(),r[n]===","&&n++}catch{if(tn.Allow.ARR&e)return u;o("Expected ']' at end of array")}return n++,u},p=()=>{if(n===0){r==="-"&&a("Not sure what '-' is");try{return JSON.parse(r)}catch(m){if(tn.Allow.NUM&e)try{return JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}a(String(m))}}let u=n;for(r[n]==="-"&&n++;r[n]&&",]}".indexOf(r[n])===-1;)n++;n==t&&!(tn.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(r.substring(u,n))}catch{r.substring(u,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(r.substring(u,r.lastIndexOf("e")))}catch(v){a(String(v))}}},f=()=>{for(;n<t&&`
2
+ \r `.includes(r[n]);)n++};return s()},f0=yh;Or.parse=f0});var pw={};Kb(pw,{ASK_USER_QUESTION_TOOL_NAME:()=>Vp,AgentWidgetClient:()=>da,AgentWidgetSession:()=>_a,AttachmentManager:()=>fa,DEFAULT_COMPONENTS:()=>Tp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>cl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Cn,DEFAULT_PALETTE:()=>Ap,DEFAULT_SEMANTIC:()=>Sp,DEFAULT_WIDGET_CONFIG:()=>Xt,PRESETS:()=>xu,PRESET_FULLSCREEN:()=>hu,PRESET_MINIMAL:()=>gu,PRESET_SHOP:()=>mu,THEME_ZONES:()=>Uh,VERSION:()=>hb,WEBMCP_TOOL_PREFIX:()=>mo,WebMcpBridge:()=>Fa,accessibilityPlugin:()=>xb,animationsPlugin:()=>bb,applyThemeVariables:()=>Do,attachHeaderToContainer:()=>ha,brandPlugin:()=>yb,buildComposer:()=>Va,buildDefaultHeader:()=>Bp,buildHeader:()=>bo,buildHeaderWithLayout:()=>$a,buildMinimalHeader:()=>Dp,collectEnrichedPageContext:()=>fb,componentRegistry:()=>Co,createActionManager:()=>ni,createAgentExperience:()=>Ql,createAskUserQuestionBubble:()=>Sx,createBestAvailableVoiceProvider:()=>Yi,createBubbleWithLayout:()=>dx,createCSATFeedback:()=>Gl,createComboButton:()=>Ml,createComponentMiddleware:()=>jx,createComponentStreamParser:()=>zl,createDefaultSanitizer:()=>Cd,createDirectivePostprocessor:()=>eh,createDropdownMenu:()=>_o,createFlexibleJsonStreamParser:()=>wh,createIconButton:()=>Dr,createImagePart:()=>Lh,createJsonStreamParser:()=>$i,createLabelButton:()=>Qs,createLocalStorageAdapter:()=>ql,createMarkdownProcessor:()=>Ls,createMarkdownProcessorFromConfig:()=>sa,createMessageActions:()=>Up,createNPSFeedback:()=>Kl,createPlainTextParser:()=>qi,createPlugin:()=>wb,createRegexJsonParser:()=>zi,createStandardBubble:()=>ja,createTextPart:()=>Fs,createTheme:()=>qa,createThemeObserver:()=>ml,createToggleGroup:()=>rx,createTypingIndicator:()=>xa,createVoiceProvider:()=>ua,createWidgetHostLayout:()=>oi,createXmlParser:()=>Vi,defaultActionHandlers:()=>va,defaultJsonActionParser:()=>ri,defaultParseRules:()=>uu,detectColorScheme:()=>qs,directivePostprocessor:()=>th,ensureAskUserQuestionSheet:()=>Ja,escapeHtml:()=>ia,extractComponentDirectiveFromMessage:()=>jl,fileToImagePart:()=>Ph,formatEnrichedContext:()=>mb,generateAssistantMessageId:()=>ca,generateMessageId:()=>Sh,generateStableSelector:()=>fu,generateUserMessageId:()=>Oa,getActiveTheme:()=>za,getColorScheme:()=>kp,getDisplayText:()=>Mh,getHeaderLayout:()=>Fp,getImageParts:()=>Eh,getPreset:()=>Sb,hasComponentDirective:()=>Vl,hasImages:()=>kh,headerLayouts:()=>kl,highContrastPlugin:()=>Cb,initAgentWidget:()=>rb,isAskUserQuestionMessage:()=>yo,isComponentDirectiveType:()=>Vx,isDockedMountMode:()=>Rr,isVoiceSupported:()=>Os,isWebMcpToolName:()=>Bo,listRegisteredStreamAnimations:()=>Rp,markdownPostprocessor:()=>ud,mergeWithDefaults:()=>pl,normalizeContent:()=>Th,parseAskUserQuestionPayload:()=>vo,pluginRegistry:()=>ti,reducedMotionPlugin:()=>vb,registerStreamAnimationPlugin:()=>ga,removeAskUserQuestionSheet:()=>zo,renderComponentDirective:()=>$l,renderLoadingIndicatorWithFallback:()=>_p,renderLucideIcon:()=>Me,resolveDockConfig:()=>Hn,resolveSanitizer:()=>Da,resolveTokens:()=>ul,stripWebMcpPrefix:()=>Hi,themeToCssVariables:()=>fl,unregisterStreamAnimationPlugin:()=>Pp,validateImageFile:()=>Rh,validateTheme:()=>Mp});function sd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var aa=sd();function _g(r){aa=r}var Ug=/[&<>"']/,Jb=new RegExp(Ug.source,"g"),qg=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Yb=new RegExp(qg.source,"g"),Zb={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Bg=r=>Zb[r];function yn(r,e){if(e){if(Ug.test(r))return r.replace(Jb,Bg)}else if(qg.test(r))return r.replace(Yb,Bg);return r}var ey=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function ty(r){return r.replace(ey,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}var ry=/(^|[^\[])\^/g;function or(r,e){let t=typeof r=="string"?r:r.source;e=e||"";let n={replace:(o,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(ry,"$1"),t=t.replace(o,s),n},getRegex:()=>new RegExp(t,e)};return n}function Dg(r){try{r=encodeURI(r).replace(/%25/g,"%")}catch{return null}return r}var Ss={exec:()=>null};function Fg(r,e){let t=r.replace(/\|/g,(a,s,i)=>{let d=!1,l=s;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=t.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(r,e,t){let n=r.length;if(n===0)return"";let o=0;for(;o<n;){let a=r.charAt(n-o-1);if(a===e&&!t)o++;else if(a!==e&&t)o++;else break}return r.slice(0,n-o)}function ny(r,e){if(r.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<r.length;n++)if(r[n]==="\\")n++;else if(r[n]===e[0])t++;else if(r[n]===e[1]&&(t--,t<0))return n;return-1}function Ng(r,e,t,n){let o=e.href,a=e.title?yn(e.title):null,s=r[1].replace(/\\([\[\]])/g,"$1");if(r[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:t,href:o,title:a,text:s,tokens:n.inlineTokens(s)};return n.state.inLink=!1,i}return{type:"image",raw:t,href:o,title:a,text:yn(s)}}function oy(r,e){let t=r.match(/^(\s+)(?:```)/);if(t===null)return e;let n=t[1];return e.split(`
3
+ `).map(o=>{let a=o.match(/^\s+/);if(a===null)return o;let[s]=a;return s.length>=n.length?o.slice(n.length):o}).join(`
4
+ `)}var Ha=class{constructor(e){pr(this,"options");pr(this,"rules");pr(this,"lexer");this.options=e||aa}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Ti(n,`
5
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],o=oy(n,t[3]||"");return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:o}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(/#$/.test(n)){let o=Ti(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
9
6
  $1`);n=Ti(n.replace(/^ *>[ \t]?/gm,""),`
10
- `);let o=this.lexer.state.top;this.lexer.state.top=!0;let s=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:r[0],tokens:s,text:n}}}list(e){let r=this.rules.block.list.exec(e);if(r){let n=r[1].trim(),o=n.length>1,s={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let a=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let p=!1;if(!(r=a.exec(e))||this.rules.block.hr.test(e))break;i=r[0],e=e.substring(i.length);let u=r[2].split(`
11
- `,1)[0].replace(/^\t+/,M=>" ".repeat(3*M.length)),f=e.split(`
12
- `,1)[0],m=0;this.options.pedantic?(m=2,d=u.trimStart()):(m=r[2].search(/[^ ]/),m=m>4?1:m,d=u.slice(m),m+=r[1].length);let y=!1;if(!u&&/^ *$/.test(f)&&(i+=f+`
13
- `,e=e.substring(f.length+1),p=!0),!p){let M=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),k=new RegExp(`^ {0,${Math.min(3,m-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),T=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:\`\`\`|~~~)`),h=new RegExp(`^ {0,${Math.min(3,m-1)}}#`);for(;e;){let C=e.split(`
14
- `,1)[0];if(f=C,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),T.test(f)||h.test(f)||M.test(f)||k.test(e))break;if(f.search(/[^ ]/)>=m||!f.trim())d+=`
15
- `+f.slice(m);else{if(y||u.search(/[^ ]/)>=4||T.test(u)||h.test(u)||k.test(u))break;d+=`
16
- `+f}!y&&!f.trim()&&(y=!0),i+=C+`
17
- `,e=e.substring(C.length+1),u=f.slice(m)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let x=null,S;this.options.gfm&&(x=/^\[[ xX]\] /.exec(d),x&&(S=x[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!x,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 u=s.items[p].tokens.filter(m=>m.type==="space"),f=u.length>0&&u.some(m=>/\n.*\n/.test(m.raw));s.loose=f}if(s.loose)for(let p=0;p<s.items.length;p++)s.items[p].loose=!0;return s}}html(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=Dg(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(Dg(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:xn(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=lb(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)),Og(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 Og(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,u=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,r=r.slice(-1*e.length+a);(o=u.exec(r))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&a%3&&!((a+d)%3)){p+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+p);let f=[...o[0]][0].length,m=e.slice(0,a+o.index+f+d);if(Math.min(a,d)%2){let x=m.slice(1,-1);return{type:"em",raw:m,text:x,tokens:this.lexer.inlineTokens(x)}}let y=m.slice(2,-2);return{type:"strong",raw:m,text:y,tokens:this.lexer.inlineTokens(y)}}}}codespan(e){let r=this.rules.inline.code.exec(e);if(r){let n=r[2].replace(/\n/g," "),o=/[^ ]/.test(n),s=/^ /.test(n)&&/ $/.test(n);return o&&s&&(n=n.substring(1,n.length-1)),n=xn(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=xn(r[1]),o="mailto:"+n):(n=xn(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=xn(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=xn(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=xn(r[0]),{type:"text",raw:r[0],text:n}}}},cb=/^(?: *(?:\n|$))+/,pb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,ub=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ms=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,fb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ug=/(?:[*+-]|\d{1,9}[.)])/,qg=ir(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Ug).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(),ud=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,mb=/^[^\n]+/,fd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,gb=ir(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",fd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),hb=ir(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ug).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",md=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,xb=ir("^ {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",md).replace("tag",Ei).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),zg=ir(ud).replace("hr",Ms).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(),yb=ir(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",zg).getRegex(),gd={blockquote:yb,code:pb,def:gb,fences:ub,heading:fb,hr:Ms,html:xb,lheading:qg,list:hb,newline:cb,paragraph:zg,table:As,text:mb},Ng=ir("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ms).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(),bb={...gd,table:Ng,paragraph:ir(ud).replace("hr",Ms).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ng).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()},wb={...gd,html:ir(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",md).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:As,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ir(ud).replace("hr",Ms).replace("heading",` *#{1,6} *[^
20
- ]`).replace("lheading",qg).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Vg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,vb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,jg=/^( {2,}|\\)\n(?!\s*$)/,Cb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ks="\\p{P}\\p{S}",Ab=ir(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,ks).getRegex(),Sb=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,Tb=ir(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,ks).getRegex(),Mb=ir("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,ks).getRegex(),kb=ir("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,ks).getRegex(),Eb=ir(/\\([punct])/,"gu").replace(/punct/g,ks).getRegex(),Lb=ir(/^<(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(),Pb=ir(md).replace("(?:-->|$)","-->").getRegex(),Ib=ir("^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",Pb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ki=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Rb=ir(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",ki).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Gg=ir(/^!?\[(label)\]\[(ref)\]/).replace("label",ki).replace("ref",fd).getRegex(),Kg=ir(/^!?\[(ref)\](?:\[\])?/).replace("ref",fd).getRegex(),Wb=ir("reflink|nolink(?!\\()","g").replace("reflink",Gg).replace("nolink",Kg).getRegex(),hd={_backpedal:As,anyPunctuation:Eb,autolink:Lb,blockSkip:Sb,br:jg,code:vb,del:As,emStrongLDelim:Tb,emStrongRDelimAst:Mb,emStrongRDelimUnd:kb,escape:Vg,link:Rb,nolink:Kg,punctuation:Ab,reflink:Gg,reflinkSearch:Wb,tag:Ib,text:Cb,url:As},Bb={...hd,link:ir(/^!?\[(label)\]\((.*?)\)/).replace("label",ki).getRegex(),reflink:ir(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ki).getRegex()},dd={...hd,escape:ir(Vg).replace("])","~|])").getRegex(),url:ir(/^((?: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.!#$%&'*+\/=?_`{\|}~-]+@)))/},Hb={...dd,br:ir(jg).replace("{2,}","*").getRegex(),text:ir(dd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mi={normal:gd,gfm:bb,pedantic:wb},Cs={normal:hd,gfm:dd,breaks:Hb,pedantic:Bb},fo=class t{constructor(e){Ft(this,"tokens");Ft(this,"options");Ft(this,"state");Ft(this,"tokenizer");Ft(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||sa,this.options.tokenizer=this.options.tokenizer||new Ia,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:Cs.normal};this.options.pedantic?(r.block=Mi.pedantic,r.inline=Cs.pedantic):this.options.gfm&&(r.block=Mi.gfm,this.options.breaks?r.inline=Cs.breaks:r.inline=Cs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Mi,inline:Cs}}static lex(e,r){return new t(r).lex(e)}static lexInline(e,r){return new t(r).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
21
- `),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,s,a;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=`
22
- `:r.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
7
+ `);let o=this.lexer.state.top;this.lexer.state.top=!0;let a=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:t[0],tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),o=n.length>1,a={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 s=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let p=!1;if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;i=t[0],e=e.substring(i.length);let f=t[2].split(`
8
+ `,1)[0].replace(/^\t+/,M=>" ".repeat(3*M.length)),u=e.split(`
9
+ `,1)[0],m=0;this.options.pedantic?(m=2,d=f.trimStart()):(m=t[2].search(/[^ ]/),m=m>4?1:m,d=f.slice(m),m+=t[1].length);let v=!1;if(!f&&/^ *$/.test(u)&&(i+=u+`
10
+ `,e=e.substring(u.length+1),p=!0),!p){let M=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),E=new RegExp(`^ {0,${Math.min(3,m-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),k=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:\`\`\`|~~~)`),h=new RegExp(`^ {0,${Math.min(3,m-1)}}#`);for(;e;){let w=e.split(`
11
+ `,1)[0];if(u=w,this.options.pedantic&&(u=u.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),k.test(u)||h.test(u)||M.test(u)||E.test(e))break;if(u.search(/[^ ]/)>=m||!u.trim())d+=`
12
+ `+u.slice(m);else{if(v||f.search(/[^ ]/)>=4||k.test(f)||h.test(f)||E.test(f))break;d+=`
13
+ `+u}!v&&!u.trim()&&(v=!0),i+=w+`
14
+ `,e=e.substring(w.length+1),f=u.slice(m)}}a.loose||(l?a.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let x=null,S;this.options.gfm&&(x=/^\[[ xX]\] /.exec(d),x&&(S=x[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),a.items.push({type:"list_item",raw:i,task:!!x,checked:S,loose:!1,text:d,tokens:[]}),a.raw+=i}a.items[a.items.length-1].raw=i.trimEnd(),a.items[a.items.length-1].text=d.trimEnd(),a.raw=a.raw.trimEnd();for(let p=0;p<a.items.length;p++)if(this.lexer.state.top=!1,a.items[p].tokens=this.lexer.blockTokens(a.items[p].text,[]),!a.loose){let f=a.items[p].tokens.filter(m=>m.type==="space"),u=f.length>0&&f.some(m=>/\n.*\n/.test(m.raw));a.loose=u}if(a.loose)for(let p=0;p<a.items.length;p++)a.items[p].loose=!0;return a}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(/\s+/g," "),o=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:a}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!/[:|]/.test(t[2]))return;let n=Fg(t[1]),o=t[2].replace(/^\||\| *$/g,"").split("|"),a=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(`
15
+ `):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let i of o)/^ *-+: *$/.test(i)?s.align.push("right"):/^ *:-+: *$/.test(i)?s.align.push("center"):/^ *:-+ *$/.test(i)?s.align.push("left"):s.align.push(null);for(let i of n)s.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of a)s.rows.push(Fg(i,s.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
16
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:yn(t[1])}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let s=Ti(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=ny(t[2],"()");if(s>-1){let d=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,d).trim(),t[3]=""}}let o=t[2],a="";if(this.options.pedantic){let s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);s&&(o=s[1],a=s[3])}else a=t[3]?t[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(n)?o=o.slice(1):o=o.slice(1,-1)),Ng(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer)}}reflink(e,t){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," "),a=t[o.toLowerCase()];if(!a){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Ng(n,a,n[0],this.lexer)}}emStrong(e,t,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 s=[...o[0]].length-1,i,d,l=s,p=0,f=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+s);(o=f.exec(t))!=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])&&s%3&&!((s+d)%3)){p+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+p);let u=[...o[0]][0].length,m=e.slice(0,s+o.index+u+d);if(Math.min(s,d)%2){let x=m.slice(1,-1);return{type:"em",raw:m,text:x,tokens:this.lexer.inlineTokens(x)}}let v=m.slice(2,-2);return{type:"strong",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(/\n/g," "),o=/[^ ]/.test(n),a=/^ /.test(n)&&/ $/.test(n);return o&&a&&(n=n.substring(1,n.length-1)),n=yn(n,!0),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,o;return t[2]==="@"?(n=yn(t[1]),o="mailto:"+n):(n=yn(t[1]),o=n),{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,o;let t;if(t=this.rules.inline.url.exec(e)){let a,s;if(t[2]==="@")a=yn(t[0]),s="mailto:"+a;else{let i;do i=t[0],t[0]=(o=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?o:"";while(i!==t[0]);a=yn(t[0]),t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:a,href:s,tokens:[{type:"text",raw:a,text:a}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n;return this.lexer.state.inRawBlock?n=t[0]:n=yn(t[0]),{type:"text",raw:t[0],text:n}}}},ay=/^(?: *(?:\n|$))+/,sy=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,iy=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ks=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ly=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,zg=/(?:[*+-]|\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,zg).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(),id=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,dy=/^[^\n]+/,ld=/(?!\s*\])(?:\\.|[^\[\]\\])+/,cy=or(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",ld).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),py=or(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,zg).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",dd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,uy=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",dd).replace("tag",Ei).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Vg=or(id).replace("hr",ks).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(),fy=or(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Vg).getRegex(),cd={blockquote:fy,code:sy,def:cy,fences:iy,heading:ly,hr:ks,html:uy,lheading:$g,list:py,newline:ay,paragraph:Vg,table:Ss,text:dy},Og=or("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ks).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(),my={...cd,table:Og,paragraph:or(id).replace("hr",ks).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Og).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()},gy={...cd,html:or(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",dd).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:Ss,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:or(id).replace("hr",ks).replace("heading",` *#{1,6} *[^
17
+ ]`).replace("lheading",$g).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,hy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Gg=/^( {2,}|\\)\n(?!\s*$)/,xy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Es="\\p{P}\\p{S}",by=or(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Es).getRegex(),yy=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,vy=or(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Es).getRegex(),Cy=or("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Es).getRegex(),wy=or("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Es).getRegex(),Ay=or(/\\([punct])/,"gu").replace(/punct/g,Es).getRegex(),Sy=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(),Ty=or(dd).replace("(?:-->|$)","-->").getRegex(),My=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",Ty).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ki=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,ky=or(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",ki).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Kg=or(/^!?\[(label)\]\[(ref)\]/).replace("label",ki).replace("ref",ld).getRegex(),Xg=or(/^!?\[(ref)\](?:\[\])?/).replace("ref",ld).getRegex(),Ey=or("reflink|nolink(?!\\()","g").replace("reflink",Kg).replace("nolink",Xg).getRegex(),pd={_backpedal:Ss,anyPunctuation:Ay,autolink:Sy,blockSkip:yy,br:Gg,code:hy,del:Ss,emStrongLDelim:vy,emStrongRDelimAst:Cy,emStrongRDelimUnd:wy,escape:jg,link:ky,nolink:Xg,punctuation:by,reflink:Kg,reflinkSearch:Ey,tag:My,text:xy,url:Ss},Ly={...pd,link:or(/^!?\[(label)\]\((.*?)\)/).replace("label",ki).getRegex(),reflink:or(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ki).getRegex()},od={...pd,escape:or(jg).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.!#$%&'*+\/=?_`{\|}~-]+@)))/},Py={...od,br:or(Gg).replace("{2,}","*").getRegex(),text:or(od.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mi={normal:cd,gfm:my,pedantic:gy},As={normal:pd,gfm:od,breaks:Py,pedantic:Ly},uo=class r{constructor(e){pr(this,"tokens");pr(this,"options");pr(this,"state");pr(this,"tokenizer");pr(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||aa,this.options.tokenizer=this.options.tokenizer||new Ha,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 t={block:Mi.normal,inline:As.normal};this.options.pedantic?(t.block=Mi.pedantic,t.inline=As.pedantic):this.options.gfm&&(t.block=Mi.gfm,this.options.breaks?t.inline=As.breaks:t.inline=As.gfm),this.tokenizer.rules=t}static get rules(){return{block:Mi,inline:As}}static lex(e,t){return new r(t).lex(e)}static lexInline(e,t){return new r(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
18
+ `),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){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,a,s;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,t))?(e=e.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&t.length>0?t[t.length-1].raw+=`
19
+ `:t.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
23
20
  `+n.raw,o.text+=`
24
- `+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.list(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.html(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.def(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
21
+ `+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.list(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.html(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.def(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
25
22
  `+n.raw,o.text+=`
26
- `+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.lheading(e)){e=e.substring(n.raw.length),r.push(n);continue}if(s=e,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=e.slice(1),l;this.options.extensions.startBlock.forEach(p=>{l=p.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(s=e.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(s))){o=r[r.length-1],a&&o.type==="paragraph"?(o.raw+=`
23
+ `+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.lheading(e)){e=e.substring(n.raw.length),t.push(n);continue}if(a=e,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=e.slice(1),l;this.options.extensions.startBlock.forEach(p=>{l=p.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(a=e.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(a))){o=t[t.length-1],s&&o.type==="paragraph"?(o.raw+=`
27
24
  `+n.raw,o.text+=`
28
- `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n),a=s.length!==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+=`
25
+ `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n),s=a.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&o.type==="text"?(o.raw+=`
29
26
  `+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,u=e.slice(1),f;this.options.extensions.startInline.forEach(m=>{f=m.call({lexer:this},u),typeof f=="number"&&f>=0&&(p=Math.min(p,f))}),p<1/0&&p>=0&&(s=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}},Ra=class{constructor(e){Ft(this,"options");this.options=e||sa}code(e,r,n){var s;let o=(s=(r||"").match(/^\S*/))==null?void 0:s[0];return e=e.replace(/\n$/,"")+`
31
- `,o?'<pre><code class="language-'+xn(o)+'">'+(n?e:xn(e,!0))+`</code></pre>
32
- `:"<pre><code>"+(n?e:xn(e,!0))+`</code></pre>
27
+ `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.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,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,o,a,s=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(s))!=null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.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,t))?(e=e.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length),o=t[t.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(n=this.tokenizer.emStrong(e,s,l)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),t.push(n);continue}if(a=e,this.options.extensions&&this.options.extensions.startInline){let p=1/0,f=e.slice(1),u;this.options.extensions.startInline.forEach(m=>{u=m.call({lexer:this},f),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(a=e.substring(0,p+1))}if(n=this.tokenizer.inlineText(a)){e=e.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=t[t.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.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 t}},Ba=class{constructor(e){pr(this,"options");this.options=e||aa}code(e,t,n){var a;let o=(a=(t||"").match(/^\S*/))==null?void 0:a[0];return e=e.replace(/\n$/,"")+`
28
+ `,o?'<pre><code class="language-'+yn(o)+'">'+(n?e:yn(e,!0))+`</code></pre>
29
+ `:"<pre><code>"+(n?e:yn(e,!0))+`</code></pre>
33
30
  `}blockquote(e){return`<blockquote>
34
31
  ${e}</blockquote>
35
- `}html(e,r){return e}heading(e,r,n){return`<h${r}>${e}</h${r}>
32
+ `}html(e,t){return e}heading(e,t,n){return`<h${t}>${e}</h${t}>
36
33
  `}hr(){return`<hr>
37
- `}list(e,r,n){let o=r?"ol":"ul",s=r&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
34
+ `}list(e,t,n){let o=t?"ol":"ul",a=t&&n!==1?' start="'+n+'"':"";return"<"+o+a+`>
38
35
  `+e+"</"+o+`>
39
- `}listitem(e,r,n){return`<li>${e}</li>
36
+ `}listitem(e,t,n){return`<li>${e}</li>
40
37
  `}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>
41
- `}table(e,r){return r&&(r=`<tbody>${r}</tbody>`),`<table>
38
+ `}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),`<table>
42
39
  <thead>
43
40
  `+e+`</thead>
44
- `+r+`</table>
41
+ `+t+`</table>
45
42
  `}tablerow(e){return`<tr>
46
43
  ${e}</tr>
47
- `}tablecell(e,r){let n=r.header?"th":"td";return(r.align?`<${n} align="${r.align}">`:`<${n}>`)+e+`</${n}>
48
- `}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,r,n){let o=Hg(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=Hg(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}},Ss=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""}},mo=class t{constructor(e){Ft(this,"options");Ft(this,"renderer");Ft(this,"textRenderer");this.options=e||sa,this.options.renderer=this.options.renderer||new Ra,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ss}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,sb(this.parseInline(a.tokens,this.textRenderer)));continue}case"code":{let a=s;n+=this.renderer.code(a.text,a.lang,!!a.escaped);continue}case"table":{let a=s,i="",d="";for(let p=0;p<a.header.length;p++)d+=this.renderer.tablecell(this.parseInline(a.header[p].tokens),{header:!0,align:a.align[p]});i+=this.renderer.tablerow(d);let l="";for(let p=0;p<a.rows.length;p++){let u=a.rows[p];d="";for(let f=0;f<u.length;f++)d+=this.renderer.tablecell(this.parseInline(u[f].tokens),{header:!1,align:a.align[f]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let a=s,i=this.parse(a.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let a=s,i=a.ordered,d=a.start,l=a.loose,p="";for(let u=0;u<a.items.length;u++){let f=a.items[u],m=f.checked,y=f.task,x="";if(f.task){let S=this.renderer.checkbox(!!m);l?f.tokens.length>0&&f.tokens[0].type==="paragraph"?(f.tokens[0].text=S+" "+f.tokens[0].text,f.tokens[0].tokens&&f.tokens[0].tokens.length>0&&f.tokens[0].tokens[0].type==="text"&&(f.tokens[0].tokens[0].text=S+" "+f.tokens[0].tokens[0].text)):f.tokens.unshift({type:"text",text:S+" "}):x+=S+" "}x+=this.parse(f.tokens,l),p+=this.renderer.listitem(x,y,!!m)}n+=this.renderer.list(p,i,d);continue}case"html":{let a=s;n+=this.renderer.html(a.text,a.block);continue}case"paragraph":{let a=s;n+=this.renderer.paragraph(this.parseInline(a.tokens));continue}case"text":{let a=s,i=a.tokens?this.parseInline(a.tokens):a.text;for(;o+1<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}},na=class{constructor(e){Ft(this,"options");this.options=e||sa}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};Ft(na,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var aa,cd,Xg,Ts=class{constructor(...e){Wg(this,aa);Ft(this,"defaults",pd());Ft(this,"options",this.setOptions);Ft(this,"parse",Si(this,aa,cd).call(this,fo.lex,mo.parse));Ft(this,"parseInline",Si(this,aa,cd).call(this,fo.lexInline,mo.parseInline));Ft(this,"Parser",mo);Ft(this,"Renderer",Ra);Ft(this,"TextRenderer",Ss);Ft(this,"Lexer",fo);Ft(this,"Tokenizer",Ia);Ft(this,"Hooks",na);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 Ra(this.defaults);for(let a in n.renderer){if(!(a in s))throw new Error(`renderer '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.renderer[i],l=s[i];s[i]=(...p)=>{let u=d.apply(s,p);return u===!1&&(u=l.apply(s,p)),u||""}}o.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Ia(this.defaults);for(let a in n.tokenizer){if(!(a in s))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let i=a,d=n.tokenizer[i],l=s[i];s[i]=(...p)=>{let u=d.apply(s,p);return u===!1&&(u=l.apply(s,p)),u}}o.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new na;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];na.passThroughHooks.has(a)?s[i]=p=>{if(this.defaults.async)return Promise.resolve(d.call(s,p)).then(f=>l.call(s,f));let u=d.call(s,p);return l.call(s,u)}:s[i]=(...p)=>{let u=d.apply(s,p);return u===!1&&(u=l.apply(s,p)),u}}o.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,a=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(a.call(this,i)),s&&(d=d.concat(s.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,r){return fo.lex(e,r!=null?r:this.defaults)}parser(e,r){return mo.parse(e,r!=null?r:this.defaults)}};aa=new WeakSet,cd=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,aa,Xg).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)}}},Xg=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>"+xn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var oa=new Ts;function sr(t,e){return oa.parse(t,e)}sr.options=sr.setOptions=function(t){return oa.setOptions(t),sr.defaults=oa.defaults,_g(sr.defaults),sr};sr.getDefaults=pd;sr.defaults=sa;sr.use=function(...t){return oa.use(...t),sr.defaults=oa.defaults,_g(sr.defaults),sr};sr.walkTokens=function(t,e){return oa.walkTokens(t,e)};sr.parseInline=oa.parseInline;sr.Parser=mo;sr.parser=mo.parse;sr.Renderer=Ra;sr.TextRenderer=Ss;sr.Lexer=fo;sr.lexer=fo.lex;sr.Tokenizer=Ia;sr.Hooks=na;sr.parse=sr;var xA=sr.options,yA=sr.setOptions,bA=sr.use,wA=sr.walkTokens,vA=sr.parseInline;var CA=mo.parse,AA=fo.lex;var Db=t=>{if(t)return t},Es=t=>{var o,s;let e=t==null?void 0:t.markedOptions,r=new Ts({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=Db(t==null?void 0:t.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},ia=t=>t?Es({markedOptions:t.options,renderer:t.renderer}):Es(),Ob=Es(),xd=t=>Ob(t),la=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Qg=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Jg=t=>`%%FORM_PLACEHOLDER_${t}%%`,Yg=(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},Zg=t=>{let e=ia(t);return r=>{let n=[],o=Yg(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="${Qg(i)}"></div>`;s=s.replace(d,p)}),s}},eh=t=>{let e=[],r=Yg(t,e),n=xd(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="${Qg(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:dh,setPrototypeOf:th,isFrozen:Nb,getPrototypeOf:_b,getOwnPropertyDescriptor:Fb}=Object,{freeze:Zr,seal:Rn,create:Ii}=Object,{apply:Sd,construct:Td}=typeof Reflect!="undefined"&&Reflect;Zr||(Zr=function(e){return e});Rn||(Rn=function(e){return e});Sd||(Sd=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)});Td||(Td=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=en(Array.prototype.forEach),$b=en(Array.prototype.lastIndexOf),rh=en(Array.prototype.pop),Ls=en(Array.prototype.push),Ub=en(Array.prototype.splice),Ri=en(String.prototype.toLowerCase),yd=en(String.prototype.toString),bd=en(String.prototype.match),Ps=en(String.prototype.replace),qb=en(String.prototype.indexOf),zb=en(String.prototype.trim),yn=en(Object.prototype.hasOwnProperty),Yr=en(RegExp.prototype.test),Is=Vb(TypeError);function en(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 Sd(t,e,n)}}function Vb(t){return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return Td(t,r)}}function Dt(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ri;th&&th(t,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let s=r(o);s!==o&&(Nb(e)||(e[n]=s),o=s)}t[o]=!0}return t}function jb(t){for(let e=0;e<t.length;e++)yn(t,e)||(t[e]=null);return t}function Zn(t){let e=Ii(null);for(let[r,n]of dh(t))yn(t,r)&&(Array.isArray(n)?e[r]=jb(n):n&&typeof n=="object"&&n.constructor===Object?e[r]=Zn(n):e[r]=n);return e}function Rs(t,e){for(;t!==null;){let n=Fb(t,e);if(n){if(n.get)return en(n.get);if(typeof n.value=="function")return en(n.value)}t=_b(t)}function r(){return null}return r}var nh=Zr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),wd=Zr(["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"]),vd=Zr(["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"]),Gb=Zr(["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"]),Cd=Zr(["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"]),Kb=Zr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),oh=Zr(["#text"]),ah=Zr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ad=Zr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),sh=Zr(["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=Zr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Xb=Rn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Jb=Rn(/<%[\w\W]*|[\w\W]*%>/gm),Qb=Rn(/\$\{[\w\W]*/gm),Yb=Rn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Zb=Rn(/^aria-[\-\w]+$/),ch=Rn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),e0=Rn(/^(?:\w+script|data):/i),t0=Rn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ph=Rn(/^html$/i),r0=Rn(/^[a-z][.\w]*(-[.\w]+)+$/i),ih=Object.freeze({__proto__:null,ARIA_ATTR:Zb,ATTR_WHITESPACE:t0,CUSTOM_ELEMENT:r0,DATA_ATTR:Yb,DOCTYPE_NAME:ph,ERB_EXPR:Jb,IS_ALLOWED_URI:ch,IS_SCRIPT_OR_DATA:e0,MUSTACHE_EXPR:Xb,TMPLIT_EXPR:Qb}),Ws={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},n0=function(){return typeof window=="undefined"?null:window},o0=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}},lh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function uh(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:n0(),e=fe=>uh(fe);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Ws.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:u,DOMParser:f,trustedTypes:m}=t,y=d.prototype,x=Rs(y,"cloneNode"),S=Rs(y,"remove"),M=Rs(y,"nextSibling"),k=Rs(y,"childNodes"),T=Rs(y,"parentNode");if(typeof a=="function"){let fe=r.createElement("template");fe.content&&fe.content.ownerDocument&&(r=fe.content.ownerDocument)}let h,C="",{implementation:w,createNodeIterator:E,createDocumentFragment:W,getElementsByTagName:P}=r,{importNode:R}=n,N=lh();e.isSupported=typeof dh=="function"&&typeof T=="function"&&w&&w.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:j,ERB_EXPR:oe,TMPLIT_EXPR:ve,DATA_ATTR:nt,ARIA_ATTR:Te,IS_SCRIPT_OR_DATA:$e,ATTR_WHITESPACE:Se,CUSTOM_ELEMENT:Xe}=ih,{IS_ALLOWED_URI:He}=ih,V=null,be=Dt({},[...nh,...wd,...vd,...Cd,...oh]),G=null,Ae=Dt({},[...ah,...Ad,...sh,...Pi]),J=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}})),ie=null,Me=null,Ge=Object.seal(Ii(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,gt=!0,ke=!1,ye=!0,tt=!1,Ue=!1,he=!1,Q=!1,Ve=!1,ee=!1,xe=!0,z=!1,De="user-content-",Le=!0,ge=!1,ue={},Oe=null,Z=Dt({},["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"]),O=null,Ie=Dt({},["audio","video","img","source","image","track"]),Ne=null,je=Dt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ke="http://www.w3.org/1998/Math/MathML",xt="http://www.w3.org/2000/svg",st="http://www.w3.org/1999/xhtml",Pt=st,Zt=!1,X=null,er=Dt({},[Ke,xt,st],yd),it=Dt({},["mi","mo","mn","ms","mtext"]),Vt=Dt({},["annotation-xml"]),de=Dt({},["title","style","font","a","script"]),we=null,Ot=["application/xhtml+xml","text/html"],lr="text/html",It=null,hr=null,Ut=r.createElement("form"),Nt=function(I){return I instanceof RegExp||I instanceof Function},Mt=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(hr&&hr===I)){if((!I||typeof I!="object")&&(I={}),I=Zn(I),we=Ot.indexOf(I.PARSER_MEDIA_TYPE)===-1?lr:I.PARSER_MEDIA_TYPE,It=we==="application/xhtml+xml"?yd:Ri,V=yn(I,"ALLOWED_TAGS")?Dt({},I.ALLOWED_TAGS,It):be,G=yn(I,"ALLOWED_ATTR")?Dt({},I.ALLOWED_ATTR,It):Ae,X=yn(I,"ALLOWED_NAMESPACES")?Dt({},I.ALLOWED_NAMESPACES,yd):er,Ne=yn(I,"ADD_URI_SAFE_ATTR")?Dt(Zn(je),I.ADD_URI_SAFE_ATTR,It):je,O=yn(I,"ADD_DATA_URI_TAGS")?Dt(Zn(Ie),I.ADD_DATA_URI_TAGS,It):Ie,Oe=yn(I,"FORBID_CONTENTS")?Dt({},I.FORBID_CONTENTS,It):Z,ie=yn(I,"FORBID_TAGS")?Dt({},I.FORBID_TAGS,It):Zn({}),Me=yn(I,"FORBID_ATTR")?Dt({},I.FORBID_ATTR,It):Zn({}),ue=yn(I,"USE_PROFILES")?I.USE_PROFILES:!1,ce=I.ALLOW_ARIA_ATTR!==!1,re=I.ALLOW_DATA_ATTR!==!1,le=I.ALLOW_UNKNOWN_PROTOCOLS||!1,gt=I.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ke=I.SAFE_FOR_TEMPLATES||!1,ye=I.SAFE_FOR_XML!==!1,tt=I.WHOLE_DOCUMENT||!1,Q=I.RETURN_DOM||!1,Ve=I.RETURN_DOM_FRAGMENT||!1,ee=I.RETURN_TRUSTED_TYPE||!1,he=I.FORCE_BODY||!1,xe=I.SANITIZE_DOM!==!1,z=I.SANITIZE_NAMED_PROPS||!1,Le=I.KEEP_CONTENT!==!1,ge=I.IN_PLACE||!1,He=I.ALLOWED_URI_REGEXP||ch,Pt=I.NAMESPACE||st,it=I.MATHML_TEXT_INTEGRATION_POINTS||it,Vt=I.HTML_INTEGRATION_POINTS||Vt,J=I.CUSTOM_ELEMENT_HANDLING||{},I.CUSTOM_ELEMENT_HANDLING&&Nt(I.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=I.CUSTOM_ELEMENT_HANDLING.tagNameCheck),I.CUSTOM_ELEMENT_HANDLING&&Nt(I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),I.CUSTOM_ELEMENT_HANDLING&&typeof I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ke&&(re=!1),Ve&&(Q=!0),ue&&(V=Dt({},oh),G=Ii(null),ue.html===!0&&(Dt(V,nh),Dt(G,ah)),ue.svg===!0&&(Dt(V,wd),Dt(G,Ad),Dt(G,Pi)),ue.svgFilters===!0&&(Dt(V,vd),Dt(G,Ad),Dt(G,Pi)),ue.mathMl===!0&&(Dt(V,Cd),Dt(G,sh),Dt(G,Pi))),yn(I,"ADD_TAGS")||(Ge.tagCheck=null),yn(I,"ADD_ATTR")||(Ge.attributeCheck=null),I.ADD_TAGS&&(typeof I.ADD_TAGS=="function"?Ge.tagCheck=I.ADD_TAGS:(V===be&&(V=Zn(V)),Dt(V,I.ADD_TAGS,It))),I.ADD_ATTR&&(typeof I.ADD_ATTR=="function"?Ge.attributeCheck=I.ADD_ATTR:(G===Ae&&(G=Zn(G)),Dt(G,I.ADD_ATTR,It))),I.ADD_URI_SAFE_ATTR&&Dt(Ne,I.ADD_URI_SAFE_ATTR,It),I.FORBID_CONTENTS&&(Oe===Z&&(Oe=Zn(Oe)),Dt(Oe,I.FORBID_CONTENTS,It)),I.ADD_FORBID_CONTENTS&&(Oe===Z&&(Oe=Zn(Oe)),Dt(Oe,I.ADD_FORBID_CONTENTS,It)),Le&&(V["#text"]=!0),tt&&Dt(V,["html","head","body"]),V.table&&(Dt(V,["tbody"]),delete ie.tbody),I.TRUSTED_TYPES_POLICY){if(typeof I.TRUSTED_TYPES_POLICY.createHTML!="function")throw Is('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof I.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Is('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');h=I.TRUSTED_TYPES_POLICY,C=h.createHTML("")}else h===void 0&&(h=o0(m,o)),h!==null&&typeof C=="string"&&(C=h.createHTML(""));Zr&&Zr(I),hr=I}},Rt=Dt({},[...wd,...vd,...Gb]),dr=Dt({},[...Cd,...Kb]),ht=function(I){let te=T(I);(!te||!te.tagName)&&(te={namespaceURI:Pt,tagName:"template"});let Pe=Ri(I.tagName),Ze=Ri(te.tagName);return X[I.namespaceURI]?I.namespaceURI===xt?te.namespaceURI===st?Pe==="svg":te.namespaceURI===Ke?Pe==="svg"&&(Ze==="annotation-xml"||it[Ze]):!!Rt[Pe]:I.namespaceURI===Ke?te.namespaceURI===st?Pe==="math":te.namespaceURI===xt?Pe==="math"&&Vt[Ze]:!!dr[Pe]:I.namespaceURI===st?te.namespaceURI===xt&&!Vt[Ze]||te.namespaceURI===Ke&&!it[Ze]?!1:!dr[Pe]&&(de[Pe]||!Rt[Pe]):!!(we==="application/xhtml+xml"&&X[I.namespaceURI]):!1},ur=function(I){Ls(e.removed,{element:I});try{T(I).removeChild(I)}catch{S(I)}},Cr=function(I,te){try{Ls(e.removed,{attribute:te.getAttributeNode(I),from:te})}catch{Ls(e.removed,{attribute:null,from:te})}if(te.removeAttribute(I),I==="is")if(Q||Ve)try{ur(te)}catch{}else try{te.setAttribute(I,"")}catch{}},Br=function(I){let te=null,Pe=null;if(he)I="<remove></remove>"+I;else{let jt=bd(I,/^[\r\n\t ]+/);Pe=jt&&jt[0]}we==="application/xhtml+xml"&&Pt===st&&(I='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+I+"</body></html>");let Ze=h?h.createHTML(I):I;if(Pt===st)try{te=new f().parseFromString(Ze,we)}catch{}if(!te||!te.documentElement){te=w.createDocument(Pt,"template",null);try{te.documentElement.innerHTML=Zt?C:Ze}catch{}}let tr=te.body||te.documentElement;return I&&Pe&&tr.insertBefore(r.createTextNode(Pe),tr.childNodes[0]||null),Pt===st?P.call(te,tt?"html":"body")[0]:tt?te.documentElement:tr},Ur=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)},bt=function(I){return I instanceof u&&(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 gr(fe,I,te){Li(fe,Pe=>{Pe.call(e,I,te,hr)})}let Kn=function(I){let te=null;if(gr(N.beforeSanitizeElements,I,null),bt(I))return ur(I),!0;let Pe=It(I.nodeName);if(gr(N.uponSanitizeElement,I,{tagName:Pe,allowedTags:V}),ye&&I.hasChildNodes()&&!sn(I.firstElementChild)&&Yr(/<[/\w!]/g,I.innerHTML)&&Yr(/<[/\w!]/g,I.textContent)||I.nodeType===Ws.progressingInstruction||ye&&I.nodeType===Ws.comment&&Yr(/<[/\w]/g,I.data))return ur(I),!0;if(!(Ge.tagCheck instanceof Function&&Ge.tagCheck(Pe))&&(!V[Pe]||ie[Pe])){if(!ie[Pe]&&oo(Pe)&&(J.tagNameCheck instanceof RegExp&&Yr(J.tagNameCheck,Pe)||J.tagNameCheck instanceof Function&&J.tagNameCheck(Pe)))return!1;if(Le&&!Oe[Pe]){let Ze=T(I)||I.parentNode,tr=k(I)||I.childNodes;if(tr&&Ze){let jt=tr.length;for(let or=jt-1;or>=0;--or){let Hr=x(tr[or],!0);Hr.__removalCount=(I.__removalCount||0)+1,Ze.insertBefore(Hr,M(I))}}}return ur(I),!0}return I instanceof d&&!ht(I)||(Pe==="noscript"||Pe==="noembed"||Pe==="noframes")&&Yr(/<\/no(script|embed|frames)/i,I.innerHTML)?(ur(I),!0):(ke&&I.nodeType===Ws.text&&(te=I.textContent,Li([j,oe,ve],Ze=>{te=Ps(te,Ze," ")}),I.textContent!==te&&(Ls(e.removed,{element:I.cloneNode()}),I.textContent=te)),gr(N.afterSanitizeElements,I,null),!1)},Nr=function(I,te,Pe){if(Me[te]||xe&&(te==="id"||te==="name")&&(Pe in r||Pe in Ut))return!1;if(!(re&&!Me[te]&&Yr(nt,te))){if(!(ce&&Yr(Te,te))){if(!(Ge.attributeCheck instanceof Function&&Ge.attributeCheck(te,I))){if(!G[te]||Me[te]){if(!(oo(I)&&(J.tagNameCheck instanceof RegExp&&Yr(J.tagNameCheck,I)||J.tagNameCheck instanceof Function&&J.tagNameCheck(I))&&(J.attributeNameCheck instanceof RegExp&&Yr(J.attributeNameCheck,te)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(te,I))||te==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&Yr(J.tagNameCheck,Pe)||J.tagNameCheck instanceof Function&&J.tagNameCheck(Pe))))return!1}else if(!Ne[te]){if(!Yr(He,Ps(Pe,Se,""))){if(!((te==="src"||te==="xlink:href"||te==="href")&&I!=="script"&&qb(Pe,"data:")===0&&O[I])){if(!(le&&!Yr($e,Ps(Pe,Se,"")))){if(Pe)return!1}}}}}}}return!0},oo=function(I){return I!=="annotation-xml"&&bd(I,Xe)},Dn=function(I){gr(N.beforeSanitizeAttributes,I,null);let{attributes:te}=I;if(!te||bt(I))return;let Pe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0},Ze=te.length;for(;Ze--;){let tr=te[Ze],{name:jt,namespaceURI:or,value:Hr}=tr,qr=It(jt),Cn=Hr,Jt=jt==="value"?Cn:zb(Cn);if(Pe.attrName=qr,Pe.attrValue=Jt,Pe.keepAttr=!0,Pe.forceKeepAttr=void 0,gr(N.uponSanitizeAttribute,I,Pe),Jt=Pe.attrValue,z&&(qr==="id"||qr==="name")&&(Cr(jt,I),Jt=De+Jt),ye&&Yr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Jt)){Cr(jt,I);continue}if(qr==="attributename"&&bd(Jt,"href")){Cr(jt,I);continue}if(Pe.forceKeepAttr)continue;if(!Pe.keepAttr){Cr(jt,I);continue}if(!gt&&Yr(/\/>/i,Jt)){Cr(jt,I);continue}ke&&Li([j,oe,ve],Dr=>{Jt=Ps(Jt,Dr," ")});let Gt=It(I.nodeName);if(!Nr(Gt,qr,Jt)){Cr(jt,I);continue}if(h&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!or)switch(m.getAttributeType(Gt,qr)){case"TrustedHTML":{Jt=h.createHTML(Jt);break}case"TrustedScriptURL":{Jt=h.createScriptURL(Jt);break}}if(Jt!==Cn)try{or?I.setAttributeNS(or,jt,Jt):I.setAttribute(jt,Jt),bt(I)?ur(I):rh(e.removed)}catch{Cr(jt,I)}}gr(N.afterSanitizeAttributes,I,null)},On=function fe(I){let te=null,Pe=Ur(I);for(gr(N.beforeSanitizeShadowDOM,I,null);te=Pe.nextNode();)gr(N.uponSanitizeShadowNode,te,null),Kn(te),Dn(te),te.content instanceof s&&fe(te.content);gr(N.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(fe){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},te=null,Pe=null,Ze=null,tr=null;if(Zt=!fe,Zt&&(fe="<!-->"),typeof fe!="string"&&!sn(fe))if(typeof fe.toString=="function"){if(fe=fe.toString(),typeof fe!="string")throw Is("dirty is not a string, aborting")}else throw Is("toString is not a function");if(!e.isSupported)return fe;if(Ue||Mt(I),e.removed=[],typeof fe=="string"&&(ge=!1),ge){if(fe.nodeName){let Hr=It(fe.nodeName);if(!V[Hr]||ie[Hr])throw Is("root node is forbidden and cannot be sanitized in-place")}}else if(fe instanceof i)te=Br("<!---->"),Pe=te.ownerDocument.importNode(fe,!0),Pe.nodeType===Ws.element&&Pe.nodeName==="BODY"||Pe.nodeName==="HTML"?te=Pe:te.appendChild(Pe);else{if(!Q&&!ke&&!tt&&fe.indexOf("<")===-1)return h&&ee?h.createHTML(fe):fe;if(te=Br(fe),!te)return Q?null:ee?C:""}te&&he&&ur(te.firstChild);let jt=Ur(ge?fe:te);for(;Ze=jt.nextNode();)Kn(Ze),Dn(Ze),Ze.content instanceof s&&On(Ze.content);if(ge)return fe;if(Q){if(Ve)for(tr=W.call(te.ownerDocument);te.firstChild;)tr.appendChild(te.firstChild);else tr=te;return(G.shadowroot||G.shadowrootmode)&&(tr=R.call(n,tr,!0)),tr}let or=tt?te.outerHTML:te.innerHTML;return tt&&V["!doctype"]&&te.ownerDocument&&te.ownerDocument.doctype&&te.ownerDocument.doctype.name&&Yr(ph,te.ownerDocument.doctype.name)&&(or="<!DOCTYPE "+te.ownerDocument.doctype.name+`>
51
- `+or),ke&&Li([j,oe,ve],Hr=>{or=Ps(or,Hr," ")}),h&&ee?h.createHTML(or):or},e.setConfig=function(){let fe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Mt(fe),Ue=!0},e.clearConfig=function(){hr=null,Ue=!1},e.isValidAttribute=function(fe,I,te){hr||Mt({});let Pe=It(fe),Ze=It(I);return Nr(Pe,Ze,te)},e.addHook=function(fe,I){typeof I=="function"&&Ls(N[fe],I)},e.removeHook=function(fe,I){if(I!==void 0){let te=$b(N[fe],I);return te===-1?void 0:Ub(N[fe],te,1)[0]}return rh(N[fe])},e.removeHooks=function(fe){N[fe]=[]},e.removeAllHooks=function(){N=lh()},e}var fh=uh();var a0={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"]},s0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Md=()=>{let t=fh(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:")&&!s0.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),e=>t.sanitize(e,a0)},Wa=t=>t===!1?null:typeof t=="function"?t:Md();var ho="webmcp:",Bd=new Map,Wh=t=>{var e;Bd.clear();for(let r of t){let n=(e=r.title)==null?void 0:e.trim();n&&Bd.set(r.name,n)}},Hd=t=>Bd.get($i(t)),Fi={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}};function Hh(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}:${aw(e.join(""))}`}function Bh(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 aw(t){let e=Bh(t,0).toString(36),r=Bh(t,2654435761).toString(36);return`${e}.${r}`}var Da=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),[]}Wh(r);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=iw(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,r,n){if(await this.ensureReady(),this.config.enabled!==!0)return jn("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let y=typeof document!="undefined"&&!!document.modelContext;return jn(y?"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=$i(e),a;try{a=await o.getTools()}catch(y){let x=y instanceof Error?y.message:String(y);return jn(`Failed to read WebMCP registry: ${x}`)}Wh(a);let i=a.find(y=>y.name===s);if(!i)return jn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return jn(`WebMCP tool not allowed by client allowlist: ${s}`);if(n!=null&&n.aborted)return jn("Aborted by cancel()");let d=Hd(s),l={toolName:s,args:r,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return jn("User declined the tool call.");if(n!=null&&n.aborted)return jn("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),m=()=>p.abort();n&&(n.aborted?p.abort():n.addEventListener("abort",m,{once:!0}));try{let y=await o.executeTool(i,pw(r),{signal:p.signal});return lw(y)}catch(y){if(u)return jn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return jn("Aborted by cancel()");let x=y instanceof Error?y.message:String(y);return jn(x)}finally{clearTimeout(f),n&&n.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await Promise.resolve().then(()=>(Rh(),Ih))).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:dw;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=>sw(e,n))}},$i=t=>t.startsWith(ho)?t.slice(ho.length):t,Ho=t=>t.startsWith(ho),sw=(t,e)=>{if(e==="*")return!0;let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(t)},iw=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},lw=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:uw(e)}]}},jn=t=>({isError:!0,content:[{type:"text",text:t}]}),dw=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=cw(t.args),r=`Allow the AI to call ${t.toolName}`+(e?`
44
+ `}tablecell(e,t){let n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
45
+ `}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,t,n){let o=Dg(e);if(o===null)return n;e=o;let a='<a href="'+e+'"';return t&&(a+=' title="'+t+'"'),a+=">"+n+"</a>",a}image(e,t,n){let o=Dg(e);if(o===null)return n;e=o;let a=`<img src="${e}" alt="${n}"`;return t&&(a+=` title="${t}"`),a+=">",a}text(e){return e}},Ts=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,t,n){return""+n}image(e,t,n){return""+n}br(){return""}},fo=class r{constructor(e){pr(this,"options");pr(this,"renderer");pr(this,"textRenderer");this.options=e||aa,this.options.renderer=this.options.renderer||new Ba,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ts}static parse(e,t){return new r(t).parse(e)}static parseInline(e,t){return new r(t).parseInline(e)}parse(e,t=!0){let n="";for(let o=0;o<e.length;o++){let a=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=a,i=this.options.extensions.renderers[s.type].call({parser:this},s);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(s.type)){n+=i||"";continue}}switch(a.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let s=a;n+=this.renderer.heading(this.parseInline(s.tokens),s.depth,ty(this.parseInline(s.tokens,this.textRenderer)));continue}case"code":{let s=a;n+=this.renderer.code(s.text,s.lang,!!s.escaped);continue}case"table":{let s=a,i="",d="";for(let p=0;p<s.header.length;p++)d+=this.renderer.tablecell(this.parseInline(s.header[p].tokens),{header:!0,align:s.align[p]});i+=this.renderer.tablerow(d);let l="";for(let p=0;p<s.rows.length;p++){let f=s.rows[p];d="";for(let u=0;u<f.length;u++)d+=this.renderer.tablecell(this.parseInline(f[u].tokens),{header:!1,align:s.align[u]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let s=a,i=this.parse(s.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let s=a,i=s.ordered,d=s.start,l=s.loose,p="";for(let f=0;f<s.items.length;f++){let u=s.items[f],m=u.checked,v=u.task,x="";if(u.task){let S=this.renderer.checkbox(!!m);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+" "}):x+=S+" "}x+=this.parse(u.tokens,l),p+=this.renderer.listitem(x,v,!!m)}n+=this.renderer.list(p,i,d);continue}case"html":{let s=a;n+=this.renderer.html(s.text,s.block);continue}case"paragraph":{let s=a;n+=this.renderer.paragraph(this.parseInline(s.tokens));continue}case"text":{let s=a,i=s.tokens?this.parseInline(s.tokens):s.text;for(;o+1<e.length&&e[o+1].type==="text";)s=e[++o],i+=`
46
+ `+(s.tokens?this.parseInline(s.tokens):s.text);n+=t?this.renderer.paragraph(i):i;continue}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let o=0;o<e.length;o++){let a=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){n+=s||"";continue}}switch(a.type){case"escape":{let s=a;n+=t.text(s.text);break}case"html":{let s=a;n+=t.html(s.text);break}case"link":{let s=a;n+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break}case"image":{let s=a;n+=t.image(s.href,s.title,s.text);break}case"strong":{let s=a;n+=t.strong(this.parseInline(s.tokens,t));break}case"em":{let s=a;n+=t.em(this.parseInline(s.tokens,t));break}case"codespan":{let s=a;n+=t.codespan(s.text);break}case"br":{n+=t.br();break}case"del":{let s=a;n+=t.del(this.parseInline(s.tokens,t));break}case"text":{let s=a;n+=t.text(s.text);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},ra=class{constructor(e){pr(this,"options");this.options=e||aa}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};pr(ra,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var oa,ad,Qg,Ms=class{constructor(...e){Hg(this,oa);pr(this,"defaults",sd());pr(this,"options",this.setOptions);pr(this,"parse",Si(this,oa,ad).call(this,uo.lex,fo.parse));pr(this,"parseInline",Si(this,oa,ad).call(this,uo.lexInline,fo.parseInline));pr(this,"Parser",fo);pr(this,"Renderer",Ba);pr(this,"TextRenderer",Ts);pr(this,"Lexer",uo);pr(this,"Tokenizer",Ha);pr(this,"Hooks",ra);this.use(...e)}walkTokens(e,t){var o,a;let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let i=s;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,t));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,t));break}case"list":{let i=s;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=s;(a=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&a[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=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(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let s=t.renderers[a.name];s?t.renderers[a.name]=function(...i){let d=a.renderer.apply(this,i);return d===!1&&(d=s.apply(this,i)),d}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[a.level];s?s.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),o.extensions=t),n.renderer){let a=this.defaults.renderer||new Ba(this.defaults);for(let s in n.renderer){if(!(s in a))throw new Error(`renderer '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.renderer[i],l=a[i];a[i]=(...p)=>{let f=d.apply(a,p);return f===!1&&(f=l.apply(a,p)),f||""}}o.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new Ha(this.defaults);for(let s in n.tokenizer){if(!(s in a))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=n.tokenizer[i],l=a[i];a[i]=(...p)=>{let f=d.apply(a,p);return f===!1&&(f=l.apply(a,p)),f}}o.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new ra;for(let s in n.hooks){if(!(s in a))throw new Error(`hook '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.hooks[i],l=a[i];ra.passThroughHooks.has(s)?a[i]=p=>{if(this.defaults.async)return Promise.resolve(d.call(a,p)).then(u=>l.call(a,u));let f=d.call(a,p);return l.call(a,f)}:a[i]=(...p)=>{let f=d.apply(a,p);return f===!1&&(f=l.apply(a,p)),f}}o.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,s=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(s.call(this,i)),a&&(d=d.concat(a.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return uo.lex(e,t!=null?t:this.defaults)}parser(e,t){return fo.parse(e,t!=null?t:this.defaults)}};oa=new WeakSet,ad=function(e,t){return(n,o)=>{let a={...o},s={...this.defaults,...a};this.defaults.async===!0&&a.async===!1&&(s.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),s.async=!0);let i=Si(this,oa,Qg).call(this,!!s.silent,!!s.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(s.hooks&&(s.hooks.options=s),s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(n):n).then(d=>e(d,s)).then(d=>s.hooks?s.hooks.processAllTokens(d):d).then(d=>s.walkTokens?Promise.all(this.walkTokens(d,s.walkTokens)).then(()=>d):d).then(d=>t(d,s)).then(d=>s.hooks?s.hooks.postprocess(d):d).catch(i);try{s.hooks&&(n=s.hooks.preprocess(n));let d=e(n,s);s.hooks&&(d=s.hooks.processAllTokens(d)),s.walkTokens&&this.walkTokens(d,s.walkTokens);let l=t(d,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(d){return i(d)}}},Qg=function(e,t){return n=>{if(n.message+=`
47
+ Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+yn(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}};var na=new Ms;function nr(r,e){return na.parse(r,e)}nr.options=nr.setOptions=function(r){return na.setOptions(r),nr.defaults=na.defaults,_g(nr.defaults),nr};nr.getDefaults=sd;nr.defaults=aa;nr.use=function(...r){return na.use(...r),nr.defaults=na.defaults,_g(nr.defaults),nr};nr.walkTokens=function(r,e){return na.walkTokens(r,e)};nr.parseInline=na.parseInline;nr.Parser=fo;nr.parser=fo.parse;nr.Renderer=Ba;nr.TextRenderer=Ts;nr.Lexer=uo;nr.lexer=uo.lex;nr.Tokenizer=Ha;nr.Hooks=ra;nr.parse=nr;var gw=nr.options,hw=nr.setOptions,xw=nr.use,bw=nr.walkTokens,yw=nr.parseInline;var vw=fo.parse,Cw=uo.lex;var Ry=r=>{if(r)return r},Ls=r=>{var o,a;let e=r==null?void 0:r.markedOptions,t=new Ms({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(a=e==null?void 0:e.breaks)!=null?a:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=Ry(r==null?void 0:r.renderer);return n&&t.use({renderer:n}),s=>t.parse(s)},sa=r=>r?Ls({markedOptions:r.options,renderer:r.renderer}):Ls(),Iy=Ls(),ud=r=>Iy(r),ia=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Yg=r=>r.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Jg=r=>`%%FORM_PLACEHOLDER_${r}%%`,Zg=(r,e)=>{let t=r;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let a=JSON.parse(o.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=Jg(e.length);return e.push({token:s,type:String(a.type)}),s}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let a=Jg(e.length);return e.push({token:a,type:o}),a}),t},eh=r=>{let e=sa(r);return t=>{let n=[],o=Zg(t,n),a=e(o);return n.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Yg(i)}"></div>`;a=a.replace(d,p)}),a}},th=r=>{let e=[],t=Zg(r,e),n=ud(t);return e.forEach(({token:o,type:a})=>{let s=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Yg(a)}"></div>`;n=n.replace(s,d)}),n};var{entries:ch,setPrototypeOf:rh,isFrozen:Wy,getPrototypeOf:Hy,getOwnPropertyDescriptor:By}=Object,{freeze:Zr,seal:Wn,create:Ri}=Object,{apply:yd,construct:vd}=typeof Reflect!="undefined"&&Reflect;Zr||(Zr=function(e){return e});Wn||(Wn=function(e){return e});yd||(yd=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),a=2;a<n;a++)o[a-2]=arguments[a];return e.apply(t,o)});vd||(vd=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return new e(...n)});var Li=en(Array.prototype.forEach),Dy=en(Array.prototype.lastIndexOf),nh=en(Array.prototype.pop),Ps=en(Array.prototype.push),Fy=en(Array.prototype.splice),Ii=en(String.prototype.toLowerCase),fd=en(String.prototype.toString),md=en(String.prototype.match),Rs=en(String.prototype.replace),Ny=en(String.prototype.indexOf),Oy=en(String.prototype.trim),vn=en(Object.prototype.hasOwnProperty),Yr=en(RegExp.prototype.test),Is=_y(TypeError);function en(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return yd(r,e,n)}}function _y(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return vd(r,t)}}function Ht(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ii;rh&&rh(r,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let a=t(o);a!==o&&(Wy(e)||(e[n]=a),o=a)}r[o]=!0}return r}function Uy(r){for(let e=0;e<r.length;e++)vn(r,e)||(r[e]=null);return r}function eo(r){let e=Ri(null);for(let[t,n]of ch(r))vn(r,t)&&(Array.isArray(n)?e[t]=Uy(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=eo(n):e[t]=n);return e}function Ws(r,e){for(;r!==null;){let n=By(r,e);if(n){if(n.get)return en(n.get);if(typeof n.value=="function")return en(n.value)}r=Hy(r)}function t(){return null}return t}var oh=Zr(["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"]),gd=Zr(["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"]),hd=Zr(["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"]),qy=Zr(["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"]),xd=Zr(["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"]),zy=Zr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ah=Zr(["#text"]),sh=Zr(["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=Zr(["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"]),ih=Zr(["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=Zr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),$y=Wn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Vy=Wn(/<%[\w\W]*|[\w\W]*%>/gm),jy=Wn(/\$\{[\w\W]*/gm),Gy=Wn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ky=Wn(/^aria-[\-\w]+$/),ph=Wn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Xy=Wn(/^(?:\w+script|data):/i),Qy=Wn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),uh=Wn(/^html$/i),Jy=Wn(/^[a-z][.\w]*(-[.\w]+)+$/i),lh=Object.freeze({__proto__:null,ARIA_ATTR:Ky,ATTR_WHITESPACE:Qy,CUSTOM_ELEMENT:Jy,DATA_ATTR:Gy,DOCTYPE_NAME:uh,ERB_EXPR:Vy,IS_ALLOWED_URI:ph,IS_SCRIPT_OR_DATA:Xy,MUSTACHE_EXPR:$y,TMPLIT_EXPR:jy}),Hs={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Yy=function(){return typeof window=="undefined"?null:window},Zy=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));let a="dompurify"+(n?"#"+n:"");try{return e.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},dh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function fh(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Yy(),e=_e=>fh(_e);if(e.version="3.3.3",e.removed=[],!r||!r.document||r.document.nodeType!==Hs.document||!r.Element)return e.isSupported=!1,e;let{document:t}=r,n=t,o=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:f,DOMParser:u,trustedTypes:m}=r,v=d.prototype,x=Ws(v,"cloneNode"),S=Ws(v,"remove"),M=Ws(v,"nextSibling"),E=Ws(v,"childNodes"),k=Ws(v,"parentNode");if(typeof s=="function"){let _e=t.createElement("template");_e.content&&_e.content.ownerDocument&&(t=_e.content.ownerDocument)}let h,w="",{implementation:C,createNodeIterator:T,createDocumentFragment:W,getElementsByTagName:R}=t,{importNode:I}=n,N=dh();e.isSupported=typeof ch=="function"&&typeof k=="function"&&C&&C.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:ie,TMPLIT_EXPR:xe,DATA_ATTR:Je,ARIA_ATTR:we,IS_SCRIPT_OR_DATA:De,ATTR_WHITESPACE:Ae,CUSTOM_ELEMENT:qe}=lh,{IS_ALLOWED_URI:Ie}=lh,J=null,re=Ht({},[...oh,...gd,...hd,...xd,...ah]),Q=null,ge=Ht({},[...sh,...bd,...ih,...Pi]),Z=Object.seal(Ri(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}})),G=null,pe=null,ke=Object.seal(Ri(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),le=!0,ne=!0,de=!1,Lt=!0,St=!1,We=!0,he=!1,at=!1,Pe=!1,j=!1,ue=!1,nt=!1,It=!0,ee=!1,je="user-content-",Fr=!0,Dt=!1,ar={},gr=null,nn=Ht({},["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"]),F=null,fe=Ht({},["audio","video","img","source","image","track"]),Re=null,Xe=Ht({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Fe="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Ye="http://www.w3.org/1999/xhtml",Tt=Ye,Qt=!1,sr=null,K=Ht({},[Fe,Oe,Ye],fd),ft=Ht({},["mi","mo","mn","ms","mtext"]),it=Ht({},["annotation-xml"]),ye=Ht({},["title","style","font","a","script"]),se=null,st=["application/xhtml+xml","text/html"],ur="text/html",ct=null,xr=null,Ir=t.createElement("form"),pt=function(P){return P instanceof RegExp||P instanceof Function},Pt=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(xr&&xr===P)){if((!P||typeof P!="object")&&(P={}),P=eo(P),se=st.indexOf(P.PARSER_MEDIA_TYPE)===-1?ur:P.PARSER_MEDIA_TYPE,ct=se==="application/xhtml+xml"?fd:Ii,J=vn(P,"ALLOWED_TAGS")?Ht({},P.ALLOWED_TAGS,ct):re,Q=vn(P,"ALLOWED_ATTR")?Ht({},P.ALLOWED_ATTR,ct):ge,sr=vn(P,"ALLOWED_NAMESPACES")?Ht({},P.ALLOWED_NAMESPACES,fd):K,Re=vn(P,"ADD_URI_SAFE_ATTR")?Ht(eo(Xe),P.ADD_URI_SAFE_ATTR,ct):Xe,F=vn(P,"ADD_DATA_URI_TAGS")?Ht(eo(fe),P.ADD_DATA_URI_TAGS,ct):fe,gr=vn(P,"FORBID_CONTENTS")?Ht({},P.FORBID_CONTENTS,ct):nn,G=vn(P,"FORBID_TAGS")?Ht({},P.FORBID_TAGS,ct):eo({}),pe=vn(P,"FORBID_ATTR")?Ht({},P.FORBID_ATTR,ct):eo({}),ar=vn(P,"USE_PROFILES")?P.USE_PROFILES:!1,le=P.ALLOW_ARIA_ATTR!==!1,ne=P.ALLOW_DATA_ATTR!==!1,de=P.ALLOW_UNKNOWN_PROTOCOLS||!1,Lt=P.ALLOW_SELF_CLOSE_IN_ATTR!==!1,St=P.SAFE_FOR_TEMPLATES||!1,We=P.SAFE_FOR_XML!==!1,he=P.WHOLE_DOCUMENT||!1,j=P.RETURN_DOM||!1,ue=P.RETURN_DOM_FRAGMENT||!1,nt=P.RETURN_TRUSTED_TYPE||!1,Pe=P.FORCE_BODY||!1,It=P.SANITIZE_DOM!==!1,ee=P.SANITIZE_NAMED_PROPS||!1,Fr=P.KEEP_CONTENT!==!1,Dt=P.IN_PLACE||!1,Ie=P.ALLOWED_URI_REGEXP||ph,Tt=P.NAMESPACE||Ye,ft=P.MATHML_TEXT_INTEGRATION_POINTS||ft,it=P.HTML_INTEGRATION_POINTS||it,Z=P.CUSTOM_ELEMENT_HANDLING||{},P.CUSTOM_ELEMENT_HANDLING&&pt(P.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=P.CUSTOM_ELEMENT_HANDLING.tagNameCheck),P.CUSTOM_ELEMENT_HANDLING&&pt(P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=P.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),P.CUSTOM_ELEMENT_HANDLING&&typeof P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=P.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),St&&(ne=!1),ue&&(j=!0),ar&&(J=Ht({},ah),Q=Ri(null),ar.html===!0&&(Ht(J,oh),Ht(Q,sh)),ar.svg===!0&&(Ht(J,gd),Ht(Q,bd),Ht(Q,Pi)),ar.svgFilters===!0&&(Ht(J,hd),Ht(Q,bd),Ht(Q,Pi)),ar.mathMl===!0&&(Ht(J,xd),Ht(Q,ih),Ht(Q,Pi))),vn(P,"ADD_TAGS")||(ke.tagCheck=null),vn(P,"ADD_ATTR")||(ke.attributeCheck=null),P.ADD_TAGS&&(typeof P.ADD_TAGS=="function"?ke.tagCheck=P.ADD_TAGS:(J===re&&(J=eo(J)),Ht(J,P.ADD_TAGS,ct))),P.ADD_ATTR&&(typeof P.ADD_ATTR=="function"?ke.attributeCheck=P.ADD_ATTR:(Q===ge&&(Q=eo(Q)),Ht(Q,P.ADD_ATTR,ct))),P.ADD_URI_SAFE_ATTR&&Ht(Re,P.ADD_URI_SAFE_ATTR,ct),P.FORBID_CONTENTS&&(gr===nn&&(gr=eo(gr)),Ht(gr,P.FORBID_CONTENTS,ct)),P.ADD_FORBID_CONTENTS&&(gr===nn&&(gr=eo(gr)),Ht(gr,P.ADD_FORBID_CONTENTS,ct)),Fr&&(J["#text"]=!0),he&&Ht(J,["html","head","body"]),J.table&&(Ht(J,["tbody"]),delete G.tbody),P.TRUSTED_TYPES_POLICY){if(typeof P.TRUSTED_TYPES_POLICY.createHTML!="function")throw Is('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof P.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Is('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');h=P.TRUSTED_TYPES_POLICY,w=h.createHTML("")}else h===void 0&&(h=Zy(m,o)),h!==null&&typeof w=="string"&&(w=h.createHTML(""));Zr&&Zr(P),xr=P}},et=Ht({},[...gd,...hd,...qy]),$t=Ht({},[...xd,...zy]),br=function(P){let ae=k(P);(!ae||!ae.tagName)&&(ae={namespaceURI:Tt,tagName:"template"});let Ee=Ii(P.tagName),Ot=Ii(ae.tagName);return sr[P.namespaceURI]?P.namespaceURI===Oe?ae.namespaceURI===Ye?Ee==="svg":ae.namespaceURI===Fe?Ee==="svg"&&(Ot==="annotation-xml"||ft[Ot]):!!et[Ee]:P.namespaceURI===Fe?ae.namespaceURI===Ye?Ee==="math":ae.namespaceURI===Oe?Ee==="math"&&it[Ot]:!!$t[Ee]:P.namespaceURI===Ye?ae.namespaceURI===Oe&&!it[Ot]||ae.namespaceURI===Fe&&!ft[Ot]?!1:!$t[Ee]&&(ye[Ee]||!et[Ee]):!!(se==="application/xhtml+xml"&&sr[P.namespaceURI]):!1},ir=function(P){Ps(e.removed,{element:P});try{k(P).removeChild(P)}catch{S(P)}},fr=function(P,ae){try{Ps(e.removed,{attribute:ae.getAttributeNode(P),from:ae})}catch{Ps(e.removed,{attribute:null,from:ae})}if(ae.removeAttribute(P),P==="is")if(j||ue)try{ir(ae)}catch{}else try{ae.setAttribute(P,"")}catch{}},Sr=function(P){let ae=null,Ee=null;if(Pe)P="<remove></remove>"+P;else{let _t=md(P,/^[\r\n\t ]+/);Ee=_t&&_t[0]}se==="application/xhtml+xml"&&Tt===Ye&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");let Ot=h?h.createHTML(P):P;if(Tt===Ye)try{ae=new u().parseFromString(Ot,se)}catch{}if(!ae||!ae.documentElement){ae=C.createDocument(Tt,"template",null);try{ae.documentElement.innerHTML=Qt?w:Ot}catch{}}let Ze=ae.body||ae.documentElement;return P&&Ee&&Ze.insertBefore(t.createTextNode(Ee),Ze.childNodes[0]||null),Tt===Ye?R.call(ae,he?"html":"body")[0]:he?ae.documentElement:Ze},cn=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)},Mt=function(P){return P instanceof f&&(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")},_r=function(P){return typeof i=="function"&&P instanceof i};function hr(_e,P,ae){Li(_e,Ee=>{Ee.call(e,P,ae,xr)})}let An=function(P){let ae=null;if(hr(N.beforeSanitizeElements,P,null),Mt(P))return ir(P),!0;let Ee=ct(P.nodeName);if(hr(N.uponSanitizeElement,P,{tagName:Ee,allowedTags:J}),We&&P.hasChildNodes()&&!_r(P.firstElementChild)&&Yr(/<[/\w!]/g,P.innerHTML)&&Yr(/<[/\w!]/g,P.textContent)||P.nodeType===Hs.progressingInstruction||We&&P.nodeType===Hs.comment&&Yr(/<[/\w]/g,P.data))return ir(P),!0;if(!(ke.tagCheck instanceof Function&&ke.tagCheck(Ee))&&(!J[Ee]||G[Ee])){if(!G[Ee]&&Ct(Ee)&&(Z.tagNameCheck instanceof RegExp&&Yr(Z.tagNameCheck,Ee)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Ee)))return!1;if(Fr&&!gr[Ee]){let Ot=k(P)||P.parentNode,Ze=E(P)||P.childNodes;if(Ze&&Ot){let _t=Ze.length;for(let Zt=_t-1;Zt>=0;--Zt){let dr=x(Ze[Zt],!0);dr.__removalCount=(P.__removalCount||0)+1,Ot.insertBefore(dr,M(P))}}}return ir(P),!0}return P instanceof d&&!br(P)||(Ee==="noscript"||Ee==="noembed"||Ee==="noframes")&&Yr(/<\/no(script|embed|frames)/i,P.innerHTML)?(ir(P),!0):(St&&P.nodeType===Hs.text&&(ae=P.textContent,Li([V,ie,xe],Ot=>{ae=Rs(ae,Ot," ")}),P.textContent!==ae&&(Ps(e.removed,{element:P.cloneNode()}),P.textContent=ae)),hr(N.afterSanitizeElements,P,null),!1)},on=function(P,ae,Ee){if(pe[ae]||It&&(ae==="id"||ae==="name")&&(Ee in t||Ee in Ir))return!1;if(!(ne&&!pe[ae]&&Yr(Je,ae))){if(!(le&&Yr(we,ae))){if(!(ke.attributeCheck instanceof Function&&ke.attributeCheck(ae,P))){if(!Q[ae]||pe[ae]){if(!(Ct(P)&&(Z.tagNameCheck instanceof RegExp&&Yr(Z.tagNameCheck,P)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(P))&&(Z.attributeNameCheck instanceof RegExp&&Yr(Z.attributeNameCheck,ae)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(ae,P))||ae==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&Yr(Z.tagNameCheck,Ee)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Ee))))return!1}else if(!Re[ae]){if(!Yr(Ie,Rs(Ee,Ae,""))){if(!((ae==="src"||ae==="xlink:href"||ae==="href")&&P!=="script"&&Ny(Ee,"data:")===0&&F[P])){if(!(de&&!Yr(De,Rs(Ee,Ae,"")))){if(Ee)return!1}}}}}}}return!0},Ct=function(P){return P!=="annotation-xml"&&md(P,qe)},jn=function(P){hr(N.beforeSanitizeAttributes,P,null);let{attributes:ae}=P;if(!ae||Mt(P))return;let Ee={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Q,forceKeepAttr:void 0},Ot=ae.length;for(;Ot--;){let Ze=ae[Ot],{name:_t,namespaceURI:Zt,value:dr}=Ze,wt=ct(_t),Ur=dr,Vt=_t==="value"?Ur:Oy(Ur);if(Ee.attrName=wt,Ee.attrValue=Vt,Ee.keepAttr=!0,Ee.forceKeepAttr=void 0,hr(N.uponSanitizeAttribute,P,Ee),Vt=Ee.attrValue,ee&&(wt==="id"||wt==="name")&&(fr(_t,P),Vt=je+Vt),We&&Yr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){fr(_t,P);continue}if(wt==="attributename"&&md(Vt,"href")){fr(_t,P);continue}if(Ee.forceKeepAttr)continue;if(!Ee.keepAttr){fr(_t,P);continue}if(!Lt&&Yr(/\/>/i,Vt)){fr(_t,P);continue}St&&Li([V,ie,xe],Fn=>{Vt=Rs(Vt,Fn," ")});let qr=ct(P.nodeName);if(!on(qr,wt,Vt)){fr(_t,P);continue}if(h&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Zt)switch(m.getAttributeType(qr,wt)){case"TrustedHTML":{Vt=h.createHTML(Vt);break}case"TrustedScriptURL":{Vt=h.createScriptURL(Vt);break}}if(Vt!==Ur)try{Zt?P.setAttributeNS(Zt,_t,Vt):P.setAttribute(_t,Vt),Mt(P)?ir(P):nh(e.removed)}catch{fr(_t,P)}}hr(N.afterSanitizeAttributes,P,null)},Sn=function _e(P){let ae=null,Ee=cn(P);for(hr(N.beforeSanitizeShadowDOM,P,null);ae=Ee.nextNode();)hr(N.uponSanitizeShadowNode,ae,null),An(ae),jn(ae),ae.content instanceof a&&_e(ae.content);hr(N.afterSanitizeShadowDOM,P,null)};return e.sanitize=function(_e){let P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=null,Ee=null,Ot=null,Ze=null;if(Qt=!_e,Qt&&(_e="<!-->"),typeof _e!="string"&&!_r(_e))if(typeof _e.toString=="function"){if(_e=_e.toString(),typeof _e!="string")throw Is("dirty is not a string, aborting")}else throw Is("toString is not a function");if(!e.isSupported)return _e;if(at||Pt(P),e.removed=[],typeof _e=="string"&&(Dt=!1),Dt){if(_e.nodeName){let dr=ct(_e.nodeName);if(!J[dr]||G[dr])throw Is("root node is forbidden and cannot be sanitized in-place")}}else if(_e instanceof i)ae=Sr("<!---->"),Ee=ae.ownerDocument.importNode(_e,!0),Ee.nodeType===Hs.element&&Ee.nodeName==="BODY"||Ee.nodeName==="HTML"?ae=Ee:ae.appendChild(Ee);else{if(!j&&!St&&!he&&_e.indexOf("<")===-1)return h&&nt?h.createHTML(_e):_e;if(ae=Sr(_e),!ae)return j?null:nt?w:""}ae&&Pe&&ir(ae.firstChild);let _t=cn(Dt?_e:ae);for(;Ot=_t.nextNode();)An(Ot),jn(Ot),Ot.content instanceof a&&Sn(Ot.content);if(Dt)return _e;if(j){if(ue)for(Ze=W.call(ae.ownerDocument);ae.firstChild;)Ze.appendChild(ae.firstChild);else Ze=ae;return(Q.shadowroot||Q.shadowrootmode)&&(Ze=I.call(n,Ze,!0)),Ze}let Zt=he?ae.outerHTML:ae.innerHTML;return he&&J["!doctype"]&&ae.ownerDocument&&ae.ownerDocument.doctype&&ae.ownerDocument.doctype.name&&Yr(uh,ae.ownerDocument.doctype.name)&&(Zt="<!DOCTYPE "+ae.ownerDocument.doctype.name+`>
48
+ `+Zt),St&&Li([V,ie,xe],dr=>{Zt=Rs(Zt,dr," ")}),h&&nt?h.createHTML(Zt):Zt},e.setConfig=function(){let _e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Pt(_e),at=!0},e.clearConfig=function(){xr=null,at=!1},e.isValidAttribute=function(_e,P,ae){xr||Pt({});let Ee=ct(_e),Ot=ct(P);return on(Ee,Ot,ae)},e.addHook=function(_e,P){typeof P=="function"&&Ps(N[_e],P)},e.removeHook=function(_e,P){if(P!==void 0){let ae=Dy(N[_e],P);return ae===-1?void 0:Fy(N[_e],ae,1)[0]}return nh(N[_e])},e.removeHooks=function(_e){N[_e]=[]},e.removeAllHooks=function(){N=dh()},e}var mh=fh();var e0={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"]},t0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Cd=()=>{let r=mh(typeof window!="undefined"?window:void 0);return r.addHook("uponSanitizeAttribute",(e,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!t0.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),e=>r.sanitize(e,e0)},Da=r=>r===!1?null:typeof r=="function"?r:Cd();var mo="webmcp:",wd=new Map,gh=r=>{var e;wd.clear();for(let t of r){let n=(e=t.title)==null?void 0:e.trim();n&&wd.set(t.name,n)}},Sd=r=>wd.get(Hi(r)),Wi={warn(r,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${r}`,...e)}},Ad=null,xh=r=>{Ad=r};function bh(r){if(r.length===0)return"0:empty";let e=r.map(t=>{var n,o;return[t.name,(n=t.description)!=null?n:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${r.length}:${r0(e.join(""))}`}function hh(r,e){let t=3735928559^e,n=1103547991^e;for(let o=0;o<r.length;o++){let a=r.charCodeAt(o);t=Math.imul(t^a,2654435761),n=Math.imul(n^a,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&n)+(t>>>0)}function r0(r){let e=hh(r,0).toString(36),t=hh(r,2654435761).toString(36);return`${e}.${t}`}var Fa=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t: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 t;try{t=await e.getTools()}catch(o){return Wi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}gh(t);let n=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let a={name:o.name,description:o.description,origin:"webmcp",...n?{pageOrigin:n}:{}},s=o0(o.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(e,t,n){if(await this.ensureReady(),this.config.enabled!==!0)return $n("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return $n(v?"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 a=Hi(e),s;try{s=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return $n(`Failed to read WebMCP registry: ${x}`)}gh(s);let i=s.find(v=>v.name===a);if(!i)return $n(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return $n(`WebMCP tool not allowed by client allowlist: ${a}`);if(n!=null&&n.aborted)return $n("Aborted by cancel()");let d=Sd(a),l={toolName:a,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return $n("User declined the tool call.");if(n!=null&&n.aborted)return $n("Aborted by cancel()");let p=new AbortController,f=!1,u=setTimeout(()=>{f=!0,p.abort()},this.timeoutMs),m=()=>p.abort();n&&(n.aborted?p.abort():n.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,l0(t),{signal:p.signal});return a0(v)}catch(v){if(f)return $n(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return $n("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return $n(x)}finally{clearTimeout(u),n&&n.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Ad?await Ad():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Wi.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 t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Wi.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 t=(n=this.confirmHandler)!=null?n:s0;try{return await t(e)}catch(o){return Wi.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(n=>n0(e,n))}},Hi=r=>r.startsWith(mo)?r.slice(mo.length):r,Bo=r=>r.startsWith(mo),n0=(r,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(r)},o0=r=>{if(!(r===void 0||r===""))try{let e=JSON.parse(r);return e!==null&&typeof e=="object"?e:void 0}catch{return}},a0=r=>{if(r==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(r)}catch{return{content:[{type:"text",text:r}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:d0(e)}]}},$n=r=>({isError:!0,content:[{type:"text",text:r}]}),s0=async r=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=i0(r.args),t=`Allow the AI to call ${r.toolName}`+(e?`
52
49
 
53
50
  Arguments:
54
- ${e}`:"")+(t.description?`
51
+ ${e}`:"")+(r.description?`
55
52
 
56
- ${t.description}`:"");return window.confirm(r)},cw=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)}},pw=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},uw=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var xo=ld(zi(),1),Vi=t=>t.replace(/\\n/g,`
57
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Oa=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)}},xw=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`},Oh=t=>t.status==="complete"?xw(t):t.status==="pending"?"Waiting":"",yw=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 Nh=t=>t.status==="complete"?yw(t):"Using tool...",ji=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Hs=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 ji(e)},Gi=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 ji(e)},Od=(t,e,r)=>{var s;if(!e)return r;let n=((s=t.name)==null?void 0:s.trim())||"tool",o=Hs(t);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Ki=(t,e)=>{let r=t.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(r))!==null;)a.index>s&&Bs(n,r.slice(s,a.index),[]),a[1]!==void 0?Bs(n,a[1],["bold"]):a[2]!==void 0?Bs(n,a[2],["italic"]):a[3]!==void 0&&Bs(n,a[3],["dim"]),s=a.index+a[0].length;return s<r.length&&Bs(n,r.slice(s),[]),n},Bs=(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})},bw=()=>{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
- `).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()=>{}}},da=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Xi=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Ji=()=>{var e;let t=bw();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)}},Qi=()=>{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,xo.parse)(r,xo.STR|xo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?Vi(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=Vi(o.text)))}catch{}return e=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},_h=t=>{let e=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Vi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Vi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>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,xo.parse)(s,xo.STR|xo.OBJ),d=o(i);d!==null&&(e=d)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Yi=()=>{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 Zi=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 ww="https://api.runtype.com/v1/dispatch",el="https://api.runtype.com";function vw(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 Nd=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Cw(t){switch(t){case"json":return Qi;case"regex-json":return Ji;case"xml":return Yi;default:return Xi}}var Fh=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Aw(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=Fh(r);if(!Fh(n))return t;if(!o||n===r||n.startsWith(r))return e;let a=da(t);return da(e)!==null&&a===null?e:t}var ca=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:ww,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:Cw(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Da(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$/,""))||el}/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$/,""))||el}/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,u={sessionId:d.sessionId,messages:e.messages.filter(Nd).map(h=>{var C,w,E;return{id:h.id,role:h.role,content:(E=(w=(C=h.contentParts)!=null?C:h.llmContent)!=null?w: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}},f=l.clientTools,m=!!(f&&f.length>0),y=m?Hh(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,S=m&&x&&this.lastSentClientToolsFingerprint===y,M=!1,k=null,T;for(let h=0;;h++){let w={...u,...m&&(M||!S)&&f?{clientTools:f}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:n.signal}),T.status===409&&h===0&&m){let E=await T.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}k=E!=null?E:{error:"Chat request failed"}}break}if(!T.ok){let h=k!=null?k:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}if(T.status===429){let w=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:w}),w}let C=new Error(h.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!T.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(T.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$/,""))||el}/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(/\/+$/,""))||el}/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(Nd).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(Nd).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 u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return n.current=u,o(u),u},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),a.current=null,r({type:"status",status:"idle"})),i.error&&(a.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r,n){var ge,ue,Oe,Z;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=O=>{let Ie=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Ne=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,je=O.tools?O.tools.map(Ke=>({...Ke,chunks:Ke.chunks?[...Ke.chunks]:void 0})):void 0;return{...O,reasoning:Ie,toolCall:Ne,tools:je}},u=O=>{if(O.role!=="assistant"||O.variant)return!0;let Ie=Array.isArray(O.contentParts)&&O.contentParts.length>0,Ne=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||Ie||Ne||!!O.stopReason},f=O=>{u(O)&&r({type:"message",message:p(O)})},m=null,y=null,x={current:null},S={current:null},M=!1,k=new Map,T=new Map,h=new Map,C=new Map,w={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},W=(O,Ie,Ne="")=>`${O}::${Ie}::${Ne}`,P=(O,Ie)=>`${O}::${Ie}::`,R=(O,Ie,Ne,je)=>{let Ke=W(O,Ie,Ne),xt=h.get(Ke);if(xt)return xt;let st=Ne?`-${Ne}`:"",Pt={id:`nested-${O}-${Ie}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ne?{partId:Ne}:{},agentMetadata:{executionId:je,parentToolId:O,parentStepId:Ie}};return h.set(Ke,Pt),f(Pt),Pt},N=O=>{if(O==null)return null;try{return String(O)}catch{return null}},j=O=>{var Ie,Ne,je,Ke,xt;return N((xt=(Ke=(je=(Ne=(Ie=O.stepId)!=null?Ie:O.step_id)!=null?Ne:O.step)!=null?je:O.parentId)!=null?Ke:O.flowStepId)!=null?xt:O.flow_step_id)},oe=O=>{var Ie,Ne,je,Ke,xt,st,Pt;return N((Pt=(st=(xt=(Ke=(je=(Ne=(Ie=O.callId)!=null?Ie:O.call_id)!=null?Ne:O.requestId)!=null?je:O.request_id)!=null?Ke:O.toolCallId)!=null?xt:O.tool_call_id)!=null?st:O.stepId)!=null?Pt:O.step_id)},ve=n,nt=!1,Te=()=>{if(m)return m;let O;return!nt&&ve?(O=ve,nt=!0):ve&&S.current?O=`${ve}_${S.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},$e=(O,Ie)=>{w.lastId=Ie,O&&w.byStep.set(O,Ie)},Se=(O,Ie)=>{var xt;let Ne=(xt=O.reasoningId)!=null?xt:O.id,je=j(O);if(Ne){let st=String(Ne);return $e(je,st),st}if(je){let st=w.byStep.get(je);if(st)return w.lastId=st,st}if(w.lastId&&!Ie)return w.lastId;if(!Ie)return null;let Ke=`reason-${l()}`;return $e(je,Ke),Ke},Xe=O=>{let Ie=k.get(O);if(Ie)return Ie;let Ne={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return k.set(O,Ne),f(Ne),Ne},He=(O,Ie)=>{E.lastId=Ie,O&&E.byCall.set(O,Ie)},V=new Set,be=new Map,G=new Set,Ae=new Map,J=O=>{if(!O)return!1;let Ie=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ie==="emit_artifact_markdown"||Ie==="emit_artifact_component"},ie=(O,Ie)=>{var xt;let Ne=(xt=O.toolId)!=null?xt:O.id,je=oe(O);if(Ne){let st=String(Ne);return He(je,st),st}if(je){let st=E.byCall.get(je);if(st)return E.lastId=st,st}if(E.lastId&&!Ie)return E.lastId;if(!Ie)return null;let Ke=`tool-${l()}`;return He(je,Ke),Ke},Me=O=>{let Ie=T.get(O);if(Ie)return Ie;let Ne={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return T.set(O,Ne),f(Ne),Ne},Ge=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let Ie=Number(O);if(!Number.isNaN(Ie)&&Number.isFinite(Ie))return Ie;let Ne=Date.parse(O);if(!Number.isNaN(Ne))return Ne}return Date.now()},ce=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},re=new Map,le=new Map,gt=new Map,ke=new Map,ye=null,tt=(O,Ie,Ne)=>{var Pt;let je=gt.get(O);je||(je=[],gt.set(O,je));let Ke=0,xt=je.length;for(;Ke<xt;){let Zt=Ke+xt>>>1;je[Zt].seq<Ie?Ke=Zt+1:xt=Zt}((Pt=je[Ke])==null?void 0:Pt.seq)===Ie?je[Ke]={seq:Ie,text:Ne}:je.splice(Ke,0,{seq:Ie,text:Ne});let st="";for(let Zt=0;Zt<je.length;Zt++)st+=je[Zt].text;return st},Ue=(O,Ie)=>{let Ne=ce(Ie),je=le.get(O.id),Ke=Aw(je,Ne);O.rawContent=Ke;let xt=re.get(O.id),st=it=>{var de;let Vt=(de=O.content)!=null?de:"";it.trim()!==""&&(Vt.trim().length===0||it.startsWith(Vt)||it.trimStart().startsWith(Vt.trim()))&&(O.content=it)},Pt=()=>{var it;if(xt){let Vt=(it=xt.close)==null?void 0:it.call(xt);Vt instanceof Promise&&Vt.catch(()=>{})}re.delete(O.id),le.delete(O.id),O.streaming=!1,f(O)};if(!xt){st(Ne),Pt();return}let Zt=da(Ke);if(Zt!==null&&Zt.trim()!==""){st(Zt),Pt();return}let X=it=>{var we;let Vt=typeof it=="string"?it:(we=it==null?void 0:it.text)!=null?we:null;if(Vt!==null&&Vt.trim()!=="")return Vt;let de=xt.getExtractedText();return de!==null&&de.trim()!==""?de:Ne},er;try{er=xt.processChunk(Ke)}catch{st(Ne),Pt();return}if(er instanceof Promise){er.then(it=>{st(X(it)),Pt()}).catch(()=>{st(Ne),Pt()});return}st(X(er)),Pt()},he=[],Q=!1,Ve,ee=()=>{Q||(Q=!0,queueMicrotask(()=>{Q=!1,Ve()}))},xe=new Zi((O,Ie)=>{he.push({payloadType:O,payload:Ie}),ee()}),z=null,De=new Map,Le=(ge=this.config.iterationDisplay)!=null?ge:"separate";for(Ve=()=>{var O,Ie,Ne,je,Ke,xt,st,Pt,Zt,X,er,it,Vt,de,we,Ot,lr,It,hr,Ut,Nt,Mt,Rt,dr,ht,ur,Cr,Br,Ur,bt,sn,gr,Kn,Nr,oo,Dn,On,fe,I,te,Pe,Ze,tr,jt,or,Hr,qr,Cn,Jt,Gt,Dr,An,Ao,ao,So,Xn,ln,Nn,Bt,xr,yr,dn,To,Sn,_n,cn,U,Tn,Ee,pn,Mn,Fn,ts,$n,Un,qn,so,Vo,ii,rs,li,va,Wt,ns,kn,nn,di,ci,Ca,io,pi,jo,os,lo,as,Mo,ko,ui,fi,sd,Go,Eo,mi,ss,Lo,gi,is,Po,ls,hi,co,xi,Io,Qt,Aa,Sa,ds,Jn,yi,cs,ps,bi,Ta,Ma,Ko,wi,vi,us,fs,ms,gs,Xr,un,po,Ct,hs,Xo,zn;for(let ka=0;ka<he.length;ka++){let lt=he[ka].payloadType,L=he[ka].payload;if(lt==="reason_start"){let q=(O=Se(L,!0))!=null?O:`reason-${l()}`,H=Xe(q);H.reasoning=(Ie=H.reasoning)!=null?Ie:{id:q,status:"streaming",chunks:[]},H.reasoning.startedAt=(je=H.reasoning.startedAt)!=null?je:Ge((Ne=L.startedAt)!=null?Ne:L.timestamp),H.reasoning.completedAt=void 0,H.reasoning.durationMs=void 0,H.streaming=!0,H.reasoning.status="streaming",f(H)}else if(lt==="reason_delta"||lt==="reason_chunk"){let q=(xt=(Ke=Se(L,!1))!=null?Ke:Se(L,!0))!=null?xt:`reason-${l()}`,H=Xe(q);H.reasoning=(st=H.reasoning)!=null?st:{id:q,status:"streaming",chunks:[]},H.reasoning.startedAt=(Zt=H.reasoning.startedAt)!=null?Zt:Ge((Pt=L.startedAt)!=null?Pt:L.timestamp);let ae=(it=(er=(X=L.reasoningText)!=null?X:L.text)!=null?er:L.delta)!=null?it:"";if(ae&&L.hidden!==!0){let me=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(me!==void 0){let Y=tt(q,me,String(ae));H.reasoning.chunks=[Y]}else H.reasoning.chunks.push(String(ae))}if(H.reasoning.status=L.done?"complete":"streaming",L.done){H.reasoning.completedAt=Ge((Vt=L.completedAt)!=null?Vt:L.timestamp);let me=(de=H.reasoning.startedAt)!=null?de:Date.now();H.reasoning.durationMs=Math.max(0,((we=H.reasoning.completedAt)!=null?we:Date.now())-me)}H.streaming=H.reasoning.status!=="complete",f(H)}else if(lt==="reason_complete"){let q=(lr=(Ot=Se(L,!1))!=null?Ot:Se(L,!0))!=null?lr:`reason-${l()}`,H=k.get(q);if(H!=null&&H.reasoning){H.reasoning.status="complete",H.reasoning.completedAt=Ge((It=L.completedAt)!=null?It:L.timestamp);let me=(hr=H.reasoning.startedAt)!=null?hr:Date.now();H.reasoning.durationMs=Math.max(0,((Ut=H.reasoning.completedAt)!=null?Ut:Date.now())-me),H.streaming=!1,f(H)}let ae=j(L);ae&&w.byStep.delete(ae)}else if(lt==="tool_start"){let q=(Nt=ie(L,!0))!=null?Nt:`tool-${l()}`,H=(Mt=L.toolName)!=null?Mt:L.name;if(J(H)){V.add(q);continue}let ae=Me(q),me=(Rt=ae.toolCall)!=null?Rt:{id:q,status:"pending"};me.name=H!=null?H:me.name,me.status="running",L.args!==void 0?me.args=L.args:L.parameters!==void 0&&(me.args=L.parameters),me.startedAt=(ht=me.startedAt)!=null?ht:Ge((dr=L.startedAt)!=null?dr:L.timestamp),me.completedAt=void 0,me.durationMs=void 0,ae.toolCall=me,ae.streaming=!0;let Y=L.agentContext;(Y||L.executionId)&&(ae.agentMetadata={executionId:(ur=Y==null?void 0:Y.executionId)!=null?ur:L.executionId,iteration:(Cr=Y==null?void 0:Y.iteration)!=null?Cr:L.iteration}),f(ae)}else if(lt==="tool_chunk"||lt==="tool_delta"){let q=(Ur=(Br=ie(L,!1))!=null?Br:ie(L,!0))!=null?Ur:`tool-${l()}`;if(V.has(q))continue;let H=Me(q),ae=(bt=H.toolCall)!=null?bt:{id:q,status:"running"};ae.startedAt=(gr=ae.startedAt)!=null?gr:Ge((sn=L.startedAt)!=null?sn:L.timestamp);let me=(oo=(Nr=(Kn=L.text)!=null?Kn:L.delta)!=null?Nr:L.message)!=null?oo:"";me&&(ae.chunks=(Dn=ae.chunks)!=null?Dn:[],ae.chunks.push(String(me))),ae.status="running",H.toolCall=ae,H.streaming=!0;let Y=L.agentContext;(Y||L.executionId)&&(H.agentMetadata=(I=H.agentMetadata)!=null?I:{executionId:(On=Y==null?void 0:Y.executionId)!=null?On:L.executionId,iteration:(fe=Y==null?void 0:Y.iteration)!=null?fe:L.iteration}),f(H)}else if(lt==="tool_complete"){let q=(Pe=(te=ie(L,!1))!=null?te:ie(L,!0))!=null?Pe:`tool-${l()}`;if(V.has(q)){V.delete(q);continue}let H=Me(q),ae=(Ze=H.toolCall)!=null?Ze:{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=Ge((tr=L.completedAt)!=null?tr:L.timestamp);let me=(jt=L.duration)!=null?jt:L.executionTime;if(typeof me=="number")ae.durationMs=me;else{let Ye=(or=ae.startedAt)!=null?or:Date.now();ae.durationMs=Math.max(0,((Hr=ae.completedAt)!=null?Hr:Date.now())-Ye)}H.toolCall=ae,H.streaming=!1;let Y=L.agentContext;(Y||L.executionId)&&(H.agentMetadata=(Jt=H.agentMetadata)!=null?Jt:{executionId:(qr=Y==null?void 0:Y.executionId)!=null?qr:L.executionId,iteration:(Cn=Y==null?void 0:Y.iteration)!=null?Cn:L.iteration}),f(H);let Fe=oe(L);Fe&&E.byCall.delete(Fe)}else if(lt==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let q=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,H=(Gt=q!=null?q:L.toolId)!=null?Gt:`local-${l()}`,ae=Me(H),me=L.toolName,Y=Ho(me),Fe=(Dr=ae.toolCall)!=null?Dr:{id:H,status:"pending"};Fe.name=me,Fe.args=L.parameters,Fe.status=Y?"running":"complete",Fe.chunks=(An=Fe.chunks)!=null?An:[],Fe.startedAt=(ao=Fe.startedAt)!=null?ao:Ge((Ao=L.startedAt)!=null?Ao:L.timestamp),Y?(Fe.completedAt=void 0,Fe.duration=void 0,Fe.durationMs=void 0):Fe.completedAt=(So=Fe.completedAt)!=null?So:Fe.startedAt,ae.toolCall=Fe,ae.streaming=!1,ae.agentMetadata={...ae.agentMetadata,executionId:(ln=L.executionId)!=null?ln:(Xn=ae.agentMetadata)==null?void 0:Xn.executionId,awaitingLocalTool:!0,...q?{webMcpToolCallId:q}:{}},f(ae)}else if(lt==="text_start"){if((Nn=L.toolContext)!=null&&Nn.toolId)continue;let q=L.partId;if(q!==void 0&&S.current!==null&&q!==S.current){let H=m;H&&(H.streaming=!1,f(H),ye=H,m=null,M=!0)}q!==void 0&&(S.current=q)}else if(lt==="text_end"){if((Bt=L.toolContext)!=null&&Bt.toolId)continue;let q=m;q&&(q.streaming=!1,f(q),ye=q,m=null,M=!0)}else if(lt==="step_chunk"||lt==="step_delta"){let q=L.stepType,H=L.executionType;if(q==="tool"||H==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let Ye=String((yr=(xr=L.id)!=null?xr:ae.stepId)!=null?yr:`step-${l()}`),At=L.partId!==void 0&&L.partId!==null?String(L.partId):"",dt=`${ae.toolId}::${Ye}`,ct=C.get(dt);if(At!==""&&ct!==void 0&&ct!==""&&ct!==At){let zt=h.get(W(ae.toolId,Ye,ct));zt&&zt.streaming!==!1&&(zt.streaming=!1,f(zt))}At!==""&&C.set(dt,At);let ut=R(ae.toolId,Ye,At,ae.executionId),br=(_n=(Sn=(To=(dn=L.text)!=null?dn:L.delta)!=null?To:L.content)!=null?Sn:L.chunk)!=null?_n:"";br&&(ut.content+=String(br),ut.streaming=!0,f(ut)),L.isComplete&&(ut.streaming=!1,f(ut));continue}let me=L.partId;if(me!==void 0&&S.current!==null&&me!==S.current){let Ye=m;Ye&&(Ye.streaming=!1,f(Ye),ye=Ye,m=null,M=!0)}me!==void 0&&(S.current=me);let Y=me!==void 0&&(cn=ke.get(me))!=null?cn:Te();me!==void 0&&(Y.partId||(Y.partId=me),ke.set(me,Y));let Fe=(pn=(Ee=(Tn=(U=L.text)!=null?U:L.delta)!=null?Tn:L.content)!=null?Ee:L.chunk)!=null?pn:"";if(Fe){let Ye=typeof L.seq=="number"?L.seq:void 0,At=me!=null?me:Y.id,dt=Ye!==void 0?tt(At,Ye,String(Fe)):((Mn=le.get(Y.id))!=null?Mn:"")+Fe;Y.rawContent=dt,re.has(Y.id)||re.set(Y.id,this.createStreamParser());let ct=re.get(Y.id),ut=dt.trim().startsWith("{")||dt.trim().startsWith("[");if(ut&&le.set(Y.id,dt),ct.__isPlainTextParser===!0){Y.content=Ye!==void 0?dt:Y.content+Fe,le.delete(Y.id),re.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let zt=ct.processChunk(dt);if(zt instanceof Promise)zt.then(Xt=>{var zr;let Er=typeof Xt=="string"?Xt:(zr=Xt==null?void 0:Xt.text)!=null?zr:null;if(Er!==null&&Er.trim()!=="")Y.content=Er,f(Y);else if(!ut&&!dt.trim().startsWith("<")){let _r=m,Ar=_r&&_r.id===Y.id?_r:Y;Ar.id===Y.id&&(Ar.content=Ye!==void 0?dt:Ar.content+Fe,le.delete(Ar.id),re.delete(Ar.id),Ar.rawContent=void 0,f(Ar))}}).catch(()=>{Y.content=Ye!==void 0?dt:Y.content+Fe,le.delete(Y.id),re.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let Xt=typeof zt=="string"?zt:(Fn=zt==null?void 0:zt.text)!=null?Fn:null;Xt!==null&&Xt.trim()!==""?(Y.content=Xt,f(Y)):!ut&&!dt.trim().startsWith("<")&&(Y.content=Ye!==void 0?dt:Y.content+Fe,le.delete(Y.id),re.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(L.isComplete){let Ye=($n=(ts=L.result)==null?void 0:ts.response)!=null?$n:Y.content;if(Ye){let At=le.get(Y.id),dt=At!=null?At:ce(Ye);Y.rawContent=dt;let ct=re.get(Y.id),ut=null,br=!1;if(ct&&(ut=ct.getExtractedText(),ut===null&&(ut=da(dt)),ut===null)){let zt=ct.processChunk(dt);zt instanceof Promise?(br=!0,zt.then(Xt=>{var zr;let Er=typeof Xt=="string"?Xt:(zr=Xt==null?void 0:Xt.text)!=null?zr:null;if(Er!==null){let _r=m;_r&&_r.id===Y.id&&(_r.content=Er,_r.streaming=!1,re.delete(_r.id),le.delete(_r.id),f(_r))}})):ut=typeof zt=="string"?zt:(Un=zt==null?void 0:zt.text)!=null?Un:null}if(!br){ut!==null&&ut.trim()!==""?Y.content=ut:le.has(Y.id)||(Y.content=ce(Ye));let zt=re.get(Y.id);if(zt){let Xt=(qn=zt.close)==null?void 0:qn.call(zt);Xt instanceof Promise&&Xt.catch(()=>{}),re.delete(Y.id)}le.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if(lt==="step_complete"){let q=L.stepType,H=L.executionType;if(q==="tool"||H==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let Ye=String((Vo=(so=L.id)!=null?so:ae.stepId)!=null?Vo:"");if(Ye){let At=P(ae.toolId,Ye);for(let[dt,ct]of h)dt.startsWith(At)&&ct.streaming!==!1&&(ct.streaming=!1,f(ct));C.delete(`${ae.toolId}::${Ye}`)}continue}let me=L.stopReason;if(M){if(m!==null){let dt=m;me&&(dt.stopReason=me),re.delete(dt.id),le.delete(dt.id),dt.streaming!==!1&&(dt.streaming=!1,f(dt))}let Ye=(ii=L.result)==null?void 0:ii.response,At=ye;At&&(me&&(At.stopReason=me),Ye!=null?Ue(At,Ye):(re.delete(At.id),le.delete(At.id))),ye=null;continue}let Y=(rs=L.result)==null?void 0:rs.response,Fe=Te();if(me&&(Fe.stopReason=me),Y!=null){let Ye=re.get(Fe.id),At=!1,dt=!1;if(Ye){let ct=Ye.getExtractedText(),ut=le.get(Fe.id),br=ut!=null?ut:ce(Y);if(Fe.rawContent=br,ct!==null&&ct.trim()!=="")Fe.content=ct,At=!0;else{let zt=da(br);if(zt!==null)Fe.content=zt,At=!0;else{let Xt=Ye.processChunk(br);if(Xt instanceof Promise)dt=!0,Xt.then(Er=>{var _r;let zr=typeof Er=="string"?Er:(_r=Er==null?void 0:Er.text)!=null?_r:null;if(zr!==null&&zr.trim()!==""){let Ar=m;Ar&&Ar.id===Fe.id&&(Ar.content=zr,Ar.streaming=!1,re.delete(Ar.id),le.delete(Ar.id),f(Ar))}else{let Ar=Ye.getExtractedText(),En=m;En&&En.id===Fe.id&&(Ar!==null&&Ar.trim()!==""?En.content=Ar:le.has(En.id)||(En.content=ce(Y)),En.streaming=!1,re.delete(En.id),le.delete(En.id),f(En))}});else{let Er=typeof Xt=="string"?Xt:(li=Xt==null?void 0:Xt.text)!=null?li:null;if(Er!==null&&Er.trim()!=="")Fe.content=Er,At=!0;else{let zr=Ye.getExtractedText();zr!==null&&zr.trim()!==""&&(Fe.content=zr,At=!0)}}}}}if(!dt){if(!Fe.rawContent){let ct=le.get(Fe.id);Fe.rawContent=ct!=null?ct:ce(Y)}if(!At&&!le.has(Fe.id)&&(Fe.content=ce(Y)),Ye){let ct=(va=Ye.close)==null?void 0:va.call(Ye);ct instanceof Promise&&ct.catch(()=>{})}re.delete(Fe.id),le.delete(Fe.id),Fe.streaming=!1,f(Fe)}}else re.delete(Fe.id),le.delete(Fe.id),Fe.streaming=!1,f(Fe)}else if(lt==="flow_complete"){let q=(Wt=L.result)==null?void 0:Wt.response;if(M){if(m!==null){let H=m;re.delete(H.id),le.delete(H.id),H.streaming!==!1&&(H.streaming=!1,f(H))}}else if(q!=null){let H=Te(),ae=le.get(H.id),me=ae!=null?ae:ce(q);H.rawContent=me;let Y=ce(q),Fe=re.get(H.id);if(Fe){let dt=da(me);if(dt!==null)Y=dt;else{let ct=Fe.processChunk(me);ct instanceof Promise&&ct.then(br=>{var Xt;let zt=typeof br=="string"?br:(Xt=br==null?void 0:br.text)!=null?Xt:null;zt!==null&&(H.content=zt,H.streaming=!1,f(H))});let ut=Fe.getExtractedText();ut!==null&&(Y=ut)}}re.delete(H.id),le.delete(H.id);let Ye=Y!==H.content,At=H.streaming!==!1;Ye&&(H.content=Y),H.streaming=!1,(Ye||At)&&f(H)}else if(m!==null){let H=m;re.delete(H.id),le.delete(H.id),H.streaming!==!1&&(H.streaming=!1,f(H))}r({type:"status",status:"idle"})}else if(lt==="agent_start")z={executionId:L.executionId,agentId:(ns=L.agentId)!=null?ns:"virtual",agentName:(kn=L.agentName)!=null?kn:"",status:"running",currentIteration:0,maxTurns:(nn=L.maxTurns)!=null?nn:1,startedAt:Ge(L.startedAt)};else if(lt==="agent_iteration_start"){if(z&&(z.currentIteration=L.iteration),Le==="separate"&&L.iteration>1){let q=m;q&&(q.streaming=!1,f(q),De.set(L.iteration-1,q),m=null)}}else if(lt==="agent_turn_start")y=null;else if(lt==="agent_turn_delta"){if(L.contentType==="text"){let q=Te();q.content+=(di=L.delta)!=null?di:"",q.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:z==null?void 0:z.agentName},y=q,f(q)}else if(L.contentType==="thinking"){let q=(ci=L.turnId)!=null?ci:`agent-think-${L.iteration}`,H=Xe(q);H.reasoning=(Ca=H.reasoning)!=null?Ca:{id:q,status:"streaming",chunks:[]},H.reasoning.chunks.push((io=L.delta)!=null?io:""),H.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},f(H)}else if(L.contentType==="tool_input"){let q=(pi=L.toolCallId)!=null?pi:E.lastId;if(q){let H=T.get(q);H!=null&&H.toolCall&&(H.toolCall.chunks=(jo=H.toolCall.chunks)!=null?jo:[],H.toolCall.chunks.push((os=L.delta)!=null?os:""),f(H))}}}else if(lt==="agent_turn_complete"){let q=L.turnId;if(q){let me=k.get(q);if(me!=null&&me.reasoning){me.reasoning.status="complete",me.reasoning.completedAt=Ge(L.completedAt);let Y=(lo=me.reasoning.startedAt)!=null?lo:Date.now();me.reasoning.durationMs=Math.max(0,((as=me.reasoning.completedAt)!=null?as:Date.now())-Y),me.streaming=!1,f(me)}}let H=L.stopReason,ae=m!=null?m:y;if(H&&ae!==null){let me=L.turnId;(!me||((Mo=ae.agentMetadata)==null?void 0:Mo.turnId)===me)&&(ae.stopReason=H,f(ae))}}else if(lt==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let q=(ko=L.toolCallId)!=null?ko:`agent-tool-${l()}`;He(oe(L),q);let H=Me(q),ae=(ui=H.toolCall)!=null?ui:{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=(sd=(fi=L.toolName)!=null?fi:L.name)!=null?sd:ae.name,ae.status="running",L.parameters!==void 0&&(ae.args=L.parameters),ae.startedAt=Ge((Go=L.startedAt)!=null?Go:L.timestamp),H.toolCall=ae,H.streaming=!0,H.agentMetadata={executionId:L.executionId,iteration:L.iteration},f(H)}else if(lt==="agent_tool_delta"){let q=(Eo=L.toolCallId)!=null?Eo:E.lastId;if(q){let H=(mi=T.get(q))!=null?mi:Me(q);H.toolCall&&(H.toolCall.chunks=(ss=H.toolCall.chunks)!=null?ss:[],H.toolCall.chunks.push((Lo=L.delta)!=null?Lo:""),H.toolCall.status="running",H.streaming=!0,f(H))}}else if(lt==="agent_tool_complete"){let q=(gi=L.toolCallId)!=null?gi:E.lastId;if(q){let H=(is=T.get(q))!=null?is:Me(q);if(H.toolCall){H.toolCall.status="complete",L.result!==void 0&&(H.toolCall.result=L.result),typeof L.executionTime=="number"&&(H.toolCall.durationMs=L.executionTime),H.toolCall.completedAt=Ge((Po=L.completedAt)!=null?Po:L.timestamp),H.streaming=!1,f(H);let ae=oe(L);ae&&E.byCall.delete(ae)}}}else if(lt==="agent_media"){let q=Array.isArray(L.media)?L.media:[],H=[];for(let ae of q){if(!ae||typeof ae!="object")continue;let me=ae,Y=typeof me.type=="string"?me.type:void 0,Fe=typeof me.mediaType=="string"?me.mediaType.toLowerCase():"",Ye=null,At="";if(Y==="media"){let dt=typeof me.data=="string"?me.data:void 0;if(!dt)continue;At=Fe.length>0?Fe:"application/octet-stream",Ye=`data:${At};base64,${dt}`}else if(Y==="image-url"){let dt=typeof me.url=="string"?me.url:void 0;if(!dt)continue;At=Fe,Ye=dt}else if(Y==="file-url"){let dt=typeof me.url=="string"?me.url:void 0;if(!dt)continue;At=Fe,Ye=dt}else continue;if(Ye)if(Y==="image-url"||At.startsWith("image/"))H.push({type:"image",image:Ye,...At?{mimeType:At}:{}});else if(At.startsWith("audio/"))H.push({type:"audio",audio:Ye,mimeType:At});else if(At.startsWith("video/"))H.push({type:"video",video:Ye,mimeType:At});else{let dt=At||"application/octet-stream";H.push({type:"file",data:Ye,mimeType:dt,filename:vw(dt)})}}if(H.length>0){let ae=l(),me=L.toolCallId,Fe={id:`agent-media-${typeof me=="string"&&me.length>0?`${me}-${ae}`:String(ae)}`,role:"assistant",content:"",contentParts:H,createdAt:new Date().toISOString(),streaming:!1,sequence:ae,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};f(Fe);let Ye=m;Ye&&(Ye.streaming=!1,f(Ye)),m=null,x.current=null}}else if(lt!=="agent_iteration_complete"){if(lt==="agent_reflection"||lt==="agent_reflect"){let q=`agent-reflection-${L.executionId}-${L.iteration}`,H={id:q,role:"assistant",content:(ls=L.reflection)!=null?ls:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:q,status:"complete",chunks:[(hi=L.reflection)!=null?hi:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};f(H)}else if(lt==="agent_complete"){z&&(z.status=L.success?"complete":"error",z.completedAt=Ge(L.completedAt),z.stopReason=L.stopReason);let q=m;q&&(q.streaming=!1,f(q)),r({type:"status",status:"idle"})}else if(lt==="agent_error"){let q=typeof L.error=="string"?L.error:(xi=(co=L.error)==null?void 0:co.message)!=null?xi:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",q):r({type:"error",error:new Error(q)})}else if(lt!=="agent_ping"){if(lt==="agent_approval_start"){let q=(Io=L.approvalId)!=null?Io:`approval-${l()}`,H={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(Qt=z==null?void 0:z.agentId)!=null?Qt:"virtual",executionId:(Sa=(Aa=L.executionId)!=null?Aa:z==null?void 0:z.executionId)!=null?Sa:"",toolName:(ds=L.toolName)!=null?ds:"",toolType:L.toolType,description:(yi=L.description)!=null?yi:`Execute ${(Jn=L.toolName)!=null?Jn:"tool"}`,parameters:L.parameters}};f(H)}else if(lt==="step_await"&&L.awaitReason==="approval_required"){let q=(cs=L.approvalId)!=null?cs:`approval-${l()}`,H={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(ps=z==null?void 0:z.agentId)!=null?ps:"virtual",executionId:(Ta=(bi=L.executionId)!=null?bi:z==null?void 0:z.executionId)!=null?Ta:"",toolName:(Ma=L.toolName)!=null?Ma:"",toolType:L.toolType,description:(wi=L.description)!=null?wi:`Execute ${(Ko=L.toolName)!=null?Ko:"tool"}`,parameters:L.parameters}};f(H)}else if(lt==="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:(vi=L.decision)!=null?vi:"approved",agentId:(us=z==null?void 0:z.agentId)!=null?us:"virtual",executionId:(ms=(fs=L.executionId)!=null?fs:z==null?void 0:z.executionId)!=null?ms:"",toolName:(gs=L.toolName)!=null?gs:"",description:(Xr=L.description)!=null?Xr:"",resolvedAt:Date.now()}};f(ae)}}else if(lt==="artifact_start"||lt==="artifact_delta"||lt==="artifact_update"||lt==="artifact_complete"){if(lt==="artifact_start"){let q=L.artifactType,H=String(L.id),ae=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:H,artifactType:q,title:ae,component:typeof L.component=="string"?L.component:void 0}),Ae.set(H,{markdown:"",title:ae}),!G.has(H)){G.add(H);let me={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:H,title:ae,artifactType:q,status:"streaming"}})};be.set(H,me),f(me)}}else if(lt==="artifact_delta"){let q=String(L.id),H=typeof L.delta=="string"?L.delta:String((un=L.delta)!=null?un:"");r({type:"artifact_delta",id:q,artDelta:H});let ae=Ae.get(q);ae&&(ae.markdown+=H)}else if(lt==="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(lt==="artifact_complete"){let q=String(L.id);r({type:"artifact_complete",id:q});let H=be.get(q);if(H){H.streaming=!1;try{let ae=JSON.parse((po=H.rawContent)!=null?po:"{}");if(ae.props){ae.props.status="complete";let me=Ae.get(q);me!=null&&me.markdown&&(ae.props.markdown=me.markdown)}H.rawContent=JSON.stringify(ae)}catch{}Ae.delete(q),f(H),be.delete(q)}}}else if(lt==="transcript_insert"){let q=L.message;if(!q||typeof q!="object")continue;let H=String((Ct=q.id)!=null?Ct:`msg-${l()}`),ae=q.role,Y={id:H,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(f(Y),Y.rawContent)try{let Fe=JSON.parse(Y.rawContent),Ye=(hs=Fe==null?void 0:Fe.props)==null?void 0:hs.artifactId;typeof Ye=="string"&&G.add(Ye)}catch{}m=null,x.current=null,re.delete(H),le.delete(H)}else if(lt==="error"||lt==="step_error"||lt==="dispatch_error"||lt==="flow_error"){let q=null;if(L.error instanceof Error)q=L.error;else if(lt==="dispatch_error"){let H=(Xo=L.message)!=null?Xo:L.error;H!=null&&H!==""&&(q=new Error(String(H)))}else if(lt==="step_error"||lt==="flow_error"){let H=L.error;typeof H=="string"&&H!==""?q=new Error(H):H!=null&&typeof H=="object"&&"message"in H&&(q=new Error(String((zn=H.message)!=null?zn:H)))}else lt==="error"&&L.error!=null&&L.error!==""&&(q=new Error(String(L.error)));if(q){r({type:"error",error:q});let H=m;H&&H.streaming&&(H.streaming=!1,f(H)),r({type:"status",status:"idle"})}}}}}he.length=0};;){let{done:O,value:Ie}=await o.read();if(O)break;a+=s.decode(Ie,{stream:!0});let Ne=a.split(`
53
+ ${r.description}`:"");return window.confirm(t)},i0=r=>{if(r==null)return"";try{let e=JSON.stringify(r,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(r)}},l0=r=>{if(r===void 0)return"{}";try{let e=JSON.stringify(r);return e===void 0?"{}":e}catch{return"{}"}},d0=r=>{if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}};var go=Ai(Fi(),1),Ni=r=>r.replace(/\\n/g,`
54
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Na=r=>{if(r===null)return"null";if(r===void 0)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r,null,2)}catch{return String(r)}},m0=r=>{var s,i;let e=(s=r.completedAt)!=null?s:Date.now(),t=(i=r.startedAt)!=null?i:e,o=(r.durationMs!==void 0?r.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},vh=r=>r.status==="complete"?m0(r):r.status==="pending"?"Waiting":"",g0=r=>{var o,a,s;let t=(typeof r.duration=="number"?r.duration:typeof r.durationMs=="number"?r.durationMs:Math.max(0,((o=r.completedAt)!=null?o:Date.now())-((s=(a=r.startedAt)!=null?a:r.completedAt)!=null?s:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ch=r=>r.status==="complete"?g0(r):"Using tool...",Oi=r=>{let e=r/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Ds=r=>{var t,n,o;let e=typeof r.duration=="number"?r.duration:typeof r.durationMs=="number"?r.durationMs:Math.max(0,((t=r.completedAt)!=null?t:Date.now())-((o=(n=r.startedAt)!=null?n:r.completedAt)!=null?o:Date.now()));return Oi(e)},_i=r=>{var t,n,o;let e=r.durationMs!==void 0?r.durationMs:Math.max(0,((t=r.completedAt)!=null?t:Date.now())-((o=(n=r.startedAt)!=null?n:r.completedAt)!=null?o:Date.now()));return Oi(e)},Md=(r,e,t)=>{var a;if(!e)return t;let n=((a=r.name)==null?void 0:a.trim())||"tool",o=Ds(r);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Ui=(r,e)=>{let t=r.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=o.exec(t))!==null;)s.index>a&&Bs(n,t.slice(a,s.index),[]),s[1]!==void 0?Bs(n,s[1],["bold"]):s[2]!==void 0?Bs(n,s[2],["italic"]):s[3]!==void 0&&Bs(n,s[3],["dim"]),a=s.index+s[0].length;return a<t.length&&Bs(n,t.slice(a),[]),n},Bs=(r,e,t)=>{let n=e.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&r.push({text:n[o],styles:t}),o<n.length-1&&r.push({text:"{duration}",styles:t,isDuration:!0})},h0=()=>{let r=null,e=0,t=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(o);if(a&&a[1])try{return a[1].replace(/\\n/g,`
55
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
56
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>r,processChunk:async n=>{if(n.length<=e)return r!==null?{text:r,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let a=t(n);return a!==null&&(r=a),e=n.length,r!==null?{text:r,raw:n}:null},close:async()=>{}}},la=r=>{try{let e=JSON.parse(r);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},qi=()=>{let r={processChunk:e=>null,getExtractedText:()=>null};return r.__isPlainTextParser=!0,r},zi=()=>{var e;let r=h0();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:r.processChunk(t)},getExtractedText:r.getExtractedText.bind(r),close:(e=r.close)==null?void 0:e.bind(r)}},$i=()=>{let r=null,e=0;return{getExtractedText:()=>r,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=e)return r!==null||r===""?{text:r||"",raw:t}:null;try{let o=(0,go.parse)(t,go.STR|go.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?r=typeof o.text=="string"?Ni(o.text):"":o.type==="init"&&o.form?r="":typeof o.text=="string"&&(r=Ni(o.text)))}catch{}return e=t.length,r!==null?{text:r,raw:t}:null},close:()=>{}}},wh=r=>{let e=null,t=0,o=r||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Ni(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ni(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>e,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return e!==null?{text:e,raw:a}:null;try{let i=(0,go.parse)(a,go.STR|go.OBJ),d=o(i);d!==null&&(e=d)}catch{}return t=a.length,{text:e||"",raw:a}},close:()=>{}}},Vi=()=>{let r=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let n=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(r=n[1],{text:r,raw:e}):null},getExtractedText:()=>r}};var ji=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var a,s,i;let n=(i=(a=t==null?void 0:t.seq)!=null?a:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(e,t);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:t,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((t,n)=>t[0]-n[0]);for(let[t,n]of e)this.buffer.delete(t),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 x0="https://api.runtype.com/v1/dispatch",Gi="https://api.runtype.com";function b0(r){var a,s;let e=r.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=(s=(a=e.slice(o+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var kd=r=>!!(r.contentParts&&r.contentParts.length>0||r.llmContent&&r.llmContent.trim().length>0||r.rawContent&&r.rawContent.trim().length>0||r.content&&r.content.trim().length>0);function y0(r){switch(r){case"json":return $i;case"regex-json":return zi;case"xml":return Vi;default:return qi}}var Ah=r=>r.startsWith("{")||r.startsWith("[")||r.startsWith("<");function v0(r,e){if(!r)return e;let t=r.trim(),n=e.trim();if(t.length===0)return e;if(n.length===0)return r;let o=Ah(t);if(!Ah(n))return r;if(!o||n===t||n.startsWith(t))return e;let s=la(r);return la(e)!==null&&s===null?e:r}var da=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,n,o,a;this.apiUrl=(t=e.apiUrl)!=null?t:x0,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:y0(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=((a=e.webmcp)==null?void 0:a.enabled)===!0?new Fa(e.webmcp):null}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,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$/,""))||Gi}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;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(),(t=(e=this.config).onSessionInit)==null||t.call(e,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let e=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={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(t)});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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Gi}/v1/client/feedback`}async sendFeedback(e){var a,s;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(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,(s=(a=this.config).onSessionExpired)==null||s.call(a),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){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:t})}async submitCSATFeedback(e,t){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:t})}async submitNPSFeedback(e,t){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:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,a,s,i;let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(o=this.config).onSessionExpired)==null||a.call(o);let h=new Error("Session expired. Please refresh to continue.");throw t({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,f={sessionId:d.sessionId,messages:e.messages.filter(kd).map(h=>{var w,C,T;return{id:h.id,role:h.role,content:(T=(C=(w=h.contentParts)!=null?w:h.llmContent)!=null?C: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,m=!!(u&&u.length>0),v=m?bh(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,S=m&&x&&this.lastSentClientToolsFingerprint===v,M=!1,E=null,k;for(let h=0;;h++){let C={...f,...m&&(M||!S)&&u?{clientTools:u}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C),signal:n.signal}),k.status===409&&h===0&&m){let T=await k.json().catch(()=>null);if((T==null?void 0:T.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}E=T!=null?T:{error:"Chat request failed"}}break}if(!k.ok){let h=E!=null?E:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(k.status===429){let C=new Error(h.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let w=new Error(h.error||"Failed to send message");throw t({type:"error",error:w}),w}if(!k.body){let h=new Error("No response body received");throw t({type:"error",error:h}),h}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(k.body,t,e.assistantMessageId)}finally{t({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")&&t({type:"error",error:l}),l}}async dispatchProxy(e,t){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var s;let o=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Gi}/v1/agents/${e.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,n){var l,p;let o=this.isClientTokenMode(),a=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Gi}/resume`,s;o&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(p=n==null?void 0:n.streamResponse)!=null?p:!0};return s&&(d.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(e){var a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(kd).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,i)=>{let d=new Date(s.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(s=>{var i,d,l;return{role:s.role,content:(l=(d=(i=s.contentParts)!=null?i:s.llmContent)!=null?d:s.rawContent)!=null?l:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(s,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(e){var a;let n={messages:e.slice().filter(kd).sort((s,i)=>{let d=new Date(s.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(s=>{var i,d,l;return{role:s.role,content:(l=(d=(i=s.contentParts)!=null?i:s.llmContent)!=null?d:s.rawContent)!=null?l:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(s,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object"){let i=s;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(e,t,n,o,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=f,o(f),f},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),s.current=null,t({type:"status",status:"idle"})),i.error&&(s.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,n){var Dt,ar,gr,nn;let o=e.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,p=F=>{let fe=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Re=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Xe=F.tools?F.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...F,reasoning:fe,toolCall:Re,tools:Xe}},f=F=>{if(F.role!=="assistant"||F.variant)return!0;let fe=Array.isArray(F.contentParts)&&F.contentParts.length>0,Re=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||fe||Re||!!F.stopReason},u=F=>{f(F)&&t({type:"message",message:p(F)})},m=null,v=null,x={current:null},S={current:null},M=!1,E=new Map,k=new Map,h=new Map,w=new Map,C={lastId:null,byStep:new Map},T={lastId:null,byCall:new Map},W=(F,fe,Re="")=>`${F}::${fe}::${Re}`,R=(F,fe)=>`${F}::${fe}::`,I=(F,fe,Re,Xe)=>{let Fe=W(F,fe,Re),Oe=h.get(Fe);if(Oe)return Oe;let Ye=Re?`-${Re}`:"",Tt={id:`nested-${F}-${fe}${Ye}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Re?{partId:Re}:{},agentMetadata:{executionId:Xe,parentToolId:F,parentStepId:fe}};return h.set(Fe,Tt),u(Tt),Tt},N=F=>{if(F==null)return null;try{return String(F)}catch{return null}},V=F=>{var fe,Re,Xe,Fe,Oe;return N((Oe=(Fe=(Xe=(Re=(fe=F.stepId)!=null?fe:F.step_id)!=null?Re:F.step)!=null?Xe:F.parentId)!=null?Fe:F.flowStepId)!=null?Oe:F.flow_step_id)},ie=F=>{var fe,Re,Xe,Fe,Oe,Ye,Tt;return N((Tt=(Ye=(Oe=(Fe=(Xe=(Re=(fe=F.callId)!=null?fe:F.call_id)!=null?Re:F.requestId)!=null?Xe:F.request_id)!=null?Fe:F.toolCallId)!=null?Oe:F.tool_call_id)!=null?Ye:F.stepId)!=null?Tt:F.step_id)},xe=n,Je=!1,we=()=>{if(m)return m;let F;return!Je&&xe?(F=xe,Je=!0):xe&&S.current?F=`${xe}_${S.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},De=(F,fe)=>{C.lastId=fe,F&&C.byStep.set(F,fe)},Ae=(F,fe)=>{var Oe;let Re=(Oe=F.reasoningId)!=null?Oe:F.id,Xe=V(F);if(Re){let Ye=String(Re);return De(Xe,Ye),Ye}if(Xe){let Ye=C.byStep.get(Xe);if(Ye)return C.lastId=Ye,Ye}if(C.lastId&&!fe)return C.lastId;if(!fe)return null;let Fe=`reason-${l()}`;return De(Xe,Fe),Fe},qe=F=>{let fe=E.get(F);if(fe)return fe;let Re={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return E.set(F,Re),u(Re),Re},Ie=(F,fe)=>{T.lastId=fe,F&&T.byCall.set(F,fe)},J=new Set,re=new Map,Q=new Set,ge=new Map,Z=F=>{if(!F)return!1;let fe=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return fe==="emit_artifact_markdown"||fe==="emit_artifact_component"},G=(F,fe)=>{var Oe;let Re=(Oe=F.toolId)!=null?Oe:F.id,Xe=ie(F);if(Re){let Ye=String(Re);return Ie(Xe,Ye),Ye}if(Xe){let Ye=T.byCall.get(Xe);if(Ye)return T.lastId=Ye,Ye}if(T.lastId&&!fe)return T.lastId;if(!fe)return null;let Fe=`tool-${l()}`;return Ie(Xe,Fe),Fe},pe=F=>{let fe=k.get(F);if(fe)return fe;let Re={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return k.set(F,Re),u(Re),Re},ke=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let fe=Number(F);if(!Number.isNaN(fe)&&Number.isFinite(fe))return fe;let Re=Date.parse(F);if(!Number.isNaN(Re))return Re}return Date.now()},le=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ne=new Map,de=new Map,Lt=new Map,St=new Map,We=null,he=(F,fe,Re)=>{var Tt;let Xe=Lt.get(F);Xe||(Xe=[],Lt.set(F,Xe));let Fe=0,Oe=Xe.length;for(;Fe<Oe;){let Qt=Fe+Oe>>>1;Xe[Qt].seq<fe?Fe=Qt+1:Oe=Qt}((Tt=Xe[Fe])==null?void 0:Tt.seq)===fe?Xe[Fe]={seq:fe,text:Re}:Xe.splice(Fe,0,{seq:fe,text:Re});let Ye="";for(let Qt=0;Qt<Xe.length;Qt++)Ye+=Xe[Qt].text;return Ye},at=(F,fe)=>{let Re=le(fe),Xe=de.get(F.id),Fe=v0(Xe,Re);F.rawContent=Fe;let Oe=ne.get(F.id),Ye=ft=>{var ye;let it=(ye=F.content)!=null?ye:"";ft.trim()!==""&&(it.trim().length===0||ft.startsWith(it)||ft.trimStart().startsWith(it.trim()))&&(F.content=ft)},Tt=()=>{var ft;if(Oe){let it=(ft=Oe.close)==null?void 0:ft.call(Oe);it instanceof Promise&&it.catch(()=>{})}ne.delete(F.id),de.delete(F.id),F.streaming=!1,u(F)};if(!Oe){Ye(Re),Tt();return}let Qt=la(Fe);if(Qt!==null&&Qt.trim()!==""){Ye(Qt),Tt();return}let sr=ft=>{var se;let it=typeof ft=="string"?ft:(se=ft==null?void 0:ft.text)!=null?se:null;if(it!==null&&it.trim()!=="")return it;let ye=Oe.getExtractedText();return ye!==null&&ye.trim()!==""?ye:Re},K;try{K=Oe.processChunk(Fe)}catch{Ye(Re),Tt();return}if(K instanceof Promise){K.then(ft=>{Ye(sr(ft)),Tt()}).catch(()=>{Ye(Re),Tt()});return}Ye(sr(K)),Tt()},Pe=[],j=!1,ue,nt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,ue()}))},It=new ji((F,fe)=>{Pe.push({payloadType:F,payload:fe}),nt()}),ee=null,je=new Map,Fr=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(ue=()=>{var F,fe,Re,Xe,Fe,Oe,Ye,Tt,Qt,sr,K,ft,it,ye,se,st,ur,ct,xr,Ir,pt,Pt,et,$t,br,ir,fr,Sr,cn,Mt,_r,hr,An,on,Ct,jn,Sn,_e,P,ae,Ee,Ot,Ze,_t,Zt,dr,wt,Ur,Vt,qr,Fn,no,wo,pn,jt,Kr,Tn,Ao,oo,So,Gn,un,Nn,kt,yr,vr,fn,To,ve,Mn,kn,q,Kn,ao,so,Xn,On,rs,mn,gn,_n,Un,Vo,io,zr,Qn,wa,jo,Aa,si,Sa,ii,Ta,Rt,ns,En,an,li,di,Ma,lo,os,Mo,as,ss,is,ls,sn,ka,Jn,Yn,ds,ci,cs,ps,Go,pi,ui,fi,mi,Zl,Ko,ko,gi,us,Eo,hi,fs,Lo,ms,xi,co,bi,Po,Gt,Ea,La,gs;for(let Ln=0;Ln<Pe.length;Ln++){let tt=Pe[Ln].payloadType,L=Pe[Ln].payload;if(tt==="reason_start"){let z=(F=Ae(L,!0))!=null?F:`reason-${l()}`,B=qe(z);B.reasoning=(fe=B.reasoning)!=null?fe:{id:z,status:"streaming",chunks:[]},B.reasoning.startedAt=(Xe=B.reasoning.startedAt)!=null?Xe:ke((Re=L.startedAt)!=null?Re:L.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",u(B)}else if(tt==="reason_delta"||tt==="reason_chunk"){let z=(Oe=(Fe=Ae(L,!1))!=null?Fe:Ae(L,!0))!=null?Oe:`reason-${l()}`,B=qe(z);B.reasoning=(Ye=B.reasoning)!=null?Ye:{id:z,status:"streaming",chunks:[]},B.reasoning.startedAt=(Qt=B.reasoning.startedAt)!=null?Qt:ke((Tt=L.startedAt)!=null?Tt:L.timestamp);let te=(ft=(K=(sr=L.reasoningText)!=null?sr:L.text)!=null?K:L.delta)!=null?ft:"";if(te&&L.hidden!==!0){let ce=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(ce!==void 0){let X=he(z,ce,String(te));B.reasoning.chunks=[X]}else B.reasoning.chunks.push(String(te))}if(B.reasoning.status=L.done?"complete":"streaming",L.done){B.reasoning.completedAt=ke((it=L.completedAt)!=null?it:L.timestamp);let ce=(ye=B.reasoning.startedAt)!=null?ye:Date.now();B.reasoning.durationMs=Math.max(0,((se=B.reasoning.completedAt)!=null?se:Date.now())-ce)}B.streaming=B.reasoning.status!=="complete",u(B)}else if(tt==="reason_complete"){let z=(ur=(st=Ae(L,!1))!=null?st:Ae(L,!0))!=null?ur:`reason-${l()}`,B=E.get(z);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=ke((ct=L.completedAt)!=null?ct:L.timestamp);let ce=(xr=B.reasoning.startedAt)!=null?xr:Date.now();B.reasoning.durationMs=Math.max(0,((Ir=B.reasoning.completedAt)!=null?Ir:Date.now())-ce),B.streaming=!1,u(B)}let te=V(L);te&&C.byStep.delete(te)}else if(tt==="tool_start"){let z=(pt=G(L,!0))!=null?pt:`tool-${l()}`,B=(Pt=L.toolName)!=null?Pt:L.name;if(Z(B)){J.add(z);continue}let te=pe(z),ce=(et=te.toolCall)!=null?et:{id:z,status:"pending"};ce.name=B!=null?B:ce.name,ce.status="running",L.args!==void 0?ce.args=L.args:L.parameters!==void 0&&(ce.args=L.parameters),ce.startedAt=(br=ce.startedAt)!=null?br:ke(($t=L.startedAt)!=null?$t:L.timestamp),ce.completedAt=void 0,ce.durationMs=void 0,te.toolCall=ce,te.streaming=!0;let X=L.agentContext;(X||L.executionId)&&(te.agentMetadata={executionId:(ir=X==null?void 0:X.executionId)!=null?ir:L.executionId,iteration:(fr=X==null?void 0:X.iteration)!=null?fr:L.iteration}),u(te)}else if(tt==="tool_chunk"||tt==="tool_delta"){let z=(cn=(Sr=G(L,!1))!=null?Sr:G(L,!0))!=null?cn:`tool-${l()}`;if(J.has(z))continue;let B=pe(z),te=(Mt=B.toolCall)!=null?Mt:{id:z,status:"running"};te.startedAt=(hr=te.startedAt)!=null?hr:ke((_r=L.startedAt)!=null?_r:L.timestamp);let ce=(Ct=(on=(An=L.text)!=null?An:L.delta)!=null?on:L.message)!=null?Ct:"";ce&&(te.chunks=(jn=te.chunks)!=null?jn:[],te.chunks.push(String(ce))),te.status="running",B.toolCall=te,B.streaming=!0;let X=L.agentContext;(X||L.executionId)&&(B.agentMetadata=(P=B.agentMetadata)!=null?P:{executionId:(Sn=X==null?void 0:X.executionId)!=null?Sn:L.executionId,iteration:(_e=X==null?void 0:X.iteration)!=null?_e:L.iteration}),u(B)}else if(tt==="tool_complete"){let z=(Ee=(ae=G(L,!1))!=null?ae:G(L,!0))!=null?Ee:`tool-${l()}`;if(J.has(z)){J.delete(z);continue}let B=pe(z),te=(Ot=B.toolCall)!=null?Ot:{id:z,status:"running"};te.status="complete",L.result!==void 0&&(te.result=L.result),typeof L.duration=="number"&&(te.duration=L.duration),te.completedAt=ke((Ze=L.completedAt)!=null?Ze:L.timestamp);let ce=(_t=L.duration)!=null?_t:L.executionTime;if(typeof ce=="number")te.durationMs=ce;else{let $e=(Zt=te.startedAt)!=null?Zt:Date.now();te.durationMs=Math.max(0,((dr=te.completedAt)!=null?dr:Date.now())-$e)}B.toolCall=te,B.streaming=!1;let X=L.agentContext;(X||L.executionId)&&(B.agentMetadata=(Vt=B.agentMetadata)!=null?Vt:{executionId:(wt=X==null?void 0:X.executionId)!=null?wt:L.executionId,iteration:(Ur=X==null?void 0:X.iteration)!=null?Ur:L.iteration}),u(B);let He=ie(L);He&&T.byCall.delete(He)}else if(tt==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let z=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,B=(qr=z!=null?z:L.toolId)!=null?qr:`local-${l()}`,te=pe(B),ce=L.toolName,X=Bo(ce),He=(Fn=te.toolCall)!=null?Fn:{id:B,status:"pending"};He.name=ce,He.args=L.parameters,He.status=X?"running":"complete",He.chunks=(no=He.chunks)!=null?no:[],He.startedAt=(pn=He.startedAt)!=null?pn:ke((wo=L.startedAt)!=null?wo:L.timestamp),X?(He.completedAt=void 0,He.duration=void 0,He.durationMs=void 0):He.completedAt=(jt=He.completedAt)!=null?jt:He.startedAt,te.toolCall=He,te.streaming=!1,te.agentMetadata={...te.agentMetadata,executionId:(Tn=L.executionId)!=null?Tn:(Kr=te.agentMetadata)==null?void 0:Kr.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},u(te)}else if(tt==="text_start"){if((Ao=L.toolContext)!=null&&Ao.toolId)continue;let z=L.partId;if(z!==void 0&&S.current!==null&&z!==S.current){let B=m;B&&(B.streaming=!1,u(B),We=B,m=null,M=!0)}z!==void 0&&(S.current=z)}else if(tt==="text_end"){if((oo=L.toolContext)!=null&&oo.toolId)continue;let z=m;z&&(z.streaming=!1,u(z),We=z,m=null,M=!0)}else if(tt==="step_chunk"||tt==="step_delta"){let z=L.stepType,B=L.executionType;if(z==="tool"||B==="context")continue;let te=L.toolContext;if(te!=null&&te.toolId){let $e=String((Gn=(So=L.id)!=null?So:te.stepId)!=null?Gn:`step-${l()}`),mt=L.partId!==void 0&&L.partId!==null?String(L.partId):"",lt=`${te.toolId}::${$e}`,zt=w.get(lt);if(mt!==""&&zt!==void 0&&zt!==""&&zt!==mt){let gt=h.get(W(te.toolId,$e,zt));gt&&gt.streaming!==!1&&(gt.streaming=!1,u(gt))}mt!==""&&w.set(lt,mt);let er=I(te.toolId,$e,mt,te.executionId),Jt=(yr=(kt=(Nn=(un=L.text)!=null?un:L.delta)!=null?Nn:L.content)!=null?kt:L.chunk)!=null?yr:"";Jt&&(er.content+=String(Jt),er.streaming=!0,u(er)),L.isComplete&&(er.streaming=!1,u(er));continue}let ce=L.partId;if(ce!==void 0&&S.current!==null&&ce!==S.current){let $e=m;$e&&($e.streaming=!1,u($e),We=$e,m=null,M=!0)}ce!==void 0&&(S.current=ce);let X=ce!==void 0&&(vr=St.get(ce))!=null?vr:we();ce!==void 0&&(X.partId||(X.partId=ce),St.set(ce,X));let He=(Mn=(ve=(To=(fn=L.text)!=null?fn:L.delta)!=null?To:L.content)!=null?ve:L.chunk)!=null?Mn:"";if(He){let $e=typeof L.seq=="number"?L.seq:void 0,mt=ce!=null?ce:X.id,lt=$e!==void 0?he(mt,$e,String(He)):((kn=de.get(X.id))!=null?kn:"")+He;X.rawContent=lt,ne.has(X.id)||ne.set(X.id,this.createStreamParser());let zt=ne.get(X.id),er=lt.trim().startsWith("{")||lt.trim().startsWith("[");if(er&&de.set(X.id,lt),zt.__isPlainTextParser===!0){X.content=$e!==void 0?lt:X.content+He,de.delete(X.id),ne.delete(X.id),X.rawContent=void 0,u(X);continue}let gt=zt.processChunk(lt);if(gt instanceof Promise)gt.then(Ft=>{var $r;let Ge=typeof Ft=="string"?Ft:($r=Ft==null?void 0:Ft.text)!=null?$r:null;if(Ge!==null&&Ge.trim()!=="")X.content=Ge,u(X);else if(!er&&!lt.trim().startsWith("<")){let Wr=m,tr=Wr&&Wr.id===X.id?Wr:X;tr.id===X.id&&(tr.content=$e!==void 0?lt:tr.content+He,de.delete(tr.id),ne.delete(tr.id),tr.rawContent=void 0,u(tr))}}).catch(()=>{X.content=$e!==void 0?lt:X.content+He,de.delete(X.id),ne.delete(X.id),X.rawContent=void 0,u(X)});else{let Ft=typeof gt=="string"?gt:(q=gt==null?void 0:gt.text)!=null?q:null;Ft!==null&&Ft.trim()!==""?(X.content=Ft,u(X)):!er&&!lt.trim().startsWith("<")&&(X.content=$e!==void 0?lt:X.content+He,de.delete(X.id),ne.delete(X.id),X.rawContent=void 0,u(X))}}if(L.isComplete){let $e=(ao=(Kn=L.result)==null?void 0:Kn.response)!=null?ao:X.content;if($e){let mt=de.get(X.id),lt=mt!=null?mt:le($e);X.rawContent=lt;let zt=ne.get(X.id),er=null,Jt=!1;if(zt&&(er=zt.getExtractedText(),er===null&&(er=la(lt)),er===null)){let gt=zt.processChunk(lt);gt instanceof Promise?(Jt=!0,gt.then(Ft=>{var $r;let Ge=typeof Ft=="string"?Ft:($r=Ft==null?void 0:Ft.text)!=null?$r:null;if(Ge!==null){let Wr=m;Wr&&Wr.id===X.id&&(Wr.content=Ge,Wr.streaming=!1,ne.delete(Wr.id),de.delete(Wr.id),u(Wr))}})):er=typeof gt=="string"?gt:(so=gt==null?void 0:gt.text)!=null?so:null}if(!Jt){er!==null&&er.trim()!==""?X.content=er:de.has(X.id)||(X.content=le($e));let gt=ne.get(X.id);if(gt){let Ft=(Xn=gt.close)==null?void 0:Xn.call(gt);Ft instanceof Promise&&Ft.catch(()=>{}),ne.delete(X.id)}de.delete(X.id),X.streaming=!1,u(X)}}}}else if(tt==="step_complete"){let z=L.stepType,B=L.executionType;if(z==="tool"||B==="context")continue;let te=L.toolContext;if(te!=null&&te.toolId){let $e=String((rs=(On=L.id)!=null?On:te.stepId)!=null?rs:"");if($e){let mt=R(te.toolId,$e);for(let[lt,zt]of h)lt.startsWith(mt)&&zt.streaming!==!1&&(zt.streaming=!1,u(zt));w.delete(`${te.toolId}::${$e}`)}continue}let ce=L.stopReason;if(M){if(m!==null){let lt=m;ce&&(lt.stopReason=ce),ne.delete(lt.id),de.delete(lt.id),lt.streaming!==!1&&(lt.streaming=!1,u(lt))}let $e=(mn=L.result)==null?void 0:mn.response,mt=We;mt&&(ce&&(mt.stopReason=ce),$e!=null?at(mt,$e):(ne.delete(mt.id),de.delete(mt.id))),We=null;continue}let X=(gn=L.result)==null?void 0:gn.response,He=we();if(ce&&(He.stopReason=ce),X!=null){let $e=ne.get(He.id),mt=!1,lt=!1;if($e){let zt=$e.getExtractedText(),er=de.get(He.id),Jt=er!=null?er:le(X);if(He.rawContent=Jt,zt!==null&&zt.trim()!=="")He.content=zt,mt=!0;else{let gt=la(Jt);if(gt!==null)He.content=gt,mt=!0;else{let Ft=$e.processChunk(Jt);if(Ft instanceof Promise)lt=!0,Ft.then(Ge=>{var Wr;let $r=typeof Ge=="string"?Ge:(Wr=Ge==null?void 0:Ge.text)!=null?Wr:null;if($r!==null&&$r.trim()!==""){let tr=m;tr&&tr.id===He.id&&(tr.content=$r,tr.streaming=!1,ne.delete(tr.id),de.delete(tr.id),u(tr))}else{let tr=$e.getExtractedText(),qn=m;qn&&qn.id===He.id&&(tr!==null&&tr.trim()!==""?qn.content=tr:de.has(qn.id)||(qn.content=le(X)),qn.streaming=!1,ne.delete(qn.id),de.delete(qn.id),u(qn))}});else{let Ge=typeof Ft=="string"?Ft:(_n=Ft==null?void 0:Ft.text)!=null?_n:null;if(Ge!==null&&Ge.trim()!=="")He.content=Ge,mt=!0;else{let $r=$e.getExtractedText();$r!==null&&$r.trim()!==""&&(He.content=$r,mt=!0)}}}}}if(!lt){if(!He.rawContent){let zt=de.get(He.id);He.rawContent=zt!=null?zt:le(X)}if(!mt&&!de.has(He.id)&&(He.content=le(X)),$e){let zt=(Un=$e.close)==null?void 0:Un.call($e);zt instanceof Promise&&zt.catch(()=>{})}ne.delete(He.id),de.delete(He.id),He.streaming=!1,u(He)}}else ne.delete(He.id),de.delete(He.id),He.streaming=!1,u(He)}else if(tt==="flow_complete"){let z=(Vo=L.result)==null?void 0:Vo.response;if(M){if(m!==null){let B=m;ne.delete(B.id),de.delete(B.id),B.streaming!==!1&&(B.streaming=!1,u(B))}}else if(z!=null){let B=we(),te=de.get(B.id),ce=te!=null?te:le(z);B.rawContent=ce;let X=le(z),He=ne.get(B.id);if(He){let lt=la(ce);if(lt!==null)X=lt;else{let zt=He.processChunk(ce);zt instanceof Promise&&zt.then(Jt=>{var Ft;let gt=typeof Jt=="string"?Jt:(Ft=Jt==null?void 0:Jt.text)!=null?Ft:null;gt!==null&&(B.content=gt,B.streaming=!1,u(B))});let er=He.getExtractedText();er!==null&&(X=er)}}ne.delete(B.id),de.delete(B.id);let $e=X!==B.content,mt=B.streaming!==!1;$e&&(B.content=X),B.streaming=!1,($e||mt)&&u(B)}else if(m!==null){let B=m;ne.delete(B.id),de.delete(B.id),B.streaming!==!1&&(B.streaming=!1,u(B))}t({type:"status",status:"idle"})}else if(tt==="agent_start")ee={executionId:L.executionId,agentId:(io=L.agentId)!=null?io:"virtual",agentName:(zr=L.agentName)!=null?zr:"",status:"running",currentIteration:0,maxTurns:(Qn=L.maxTurns)!=null?Qn:1,startedAt:ke(L.startedAt)};else if(tt==="agent_iteration_start"){if(ee&&(ee.currentIteration=L.iteration),Fr==="separate"&&L.iteration>1){let z=m;z&&(z.streaming=!1,u(z),je.set(L.iteration-1,z),m=null)}}else if(tt==="agent_turn_start")v=null;else if(tt==="agent_turn_delta"){if(L.contentType==="text"){let z=we();z.content+=(wa=L.delta)!=null?wa:"",z.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:ee==null?void 0:ee.agentName},v=z,u(z)}else if(L.contentType==="thinking"){let z=(jo=L.turnId)!=null?jo:`agent-think-${L.iteration}`,B=qe(z);B.reasoning=(Aa=B.reasoning)!=null?Aa:{id:z,status:"streaming",chunks:[]},B.reasoning.chunks.push((si=L.delta)!=null?si:""),B.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(B)}else if(L.contentType==="tool_input"){let z=(Sa=L.toolCallId)!=null?Sa:T.lastId;if(z){let B=k.get(z);B!=null&&B.toolCall&&(B.toolCall.chunks=(ii=B.toolCall.chunks)!=null?ii:[],B.toolCall.chunks.push((Ta=L.delta)!=null?Ta:""),u(B))}}}else if(tt==="agent_turn_complete"){let z=L.turnId;if(z){let ce=E.get(z);if(ce!=null&&ce.reasoning){ce.reasoning.status="complete",ce.reasoning.completedAt=ke(L.completedAt);let X=(Rt=ce.reasoning.startedAt)!=null?Rt:Date.now();ce.reasoning.durationMs=Math.max(0,((ns=ce.reasoning.completedAt)!=null?ns:Date.now())-X),ce.streaming=!1,u(ce)}}let B=L.stopReason,te=m!=null?m:v;if(B&&te!==null){let ce=L.turnId;(!ce||((En=te.agentMetadata)==null?void 0:En.turnId)===ce)&&(te.stopReason=B,u(te))}}else if(tt==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let z=(an=L.toolCallId)!=null?an:`agent-tool-${l()}`;Ie(ie(L),z);let B=pe(z),te=(li=B.toolCall)!=null?li:{id:z,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};te.name=(Ma=(di=L.toolName)!=null?di:L.name)!=null?Ma:te.name,te.status="running",L.parameters!==void 0&&(te.args=L.parameters),te.startedAt=ke((lo=L.startedAt)!=null?lo:L.timestamp),B.toolCall=te,B.streaming=!0,B.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(B)}else if(tt==="agent_tool_delta"){let z=(os=L.toolCallId)!=null?os:T.lastId;if(z){let B=(Mo=k.get(z))!=null?Mo:pe(z);B.toolCall&&(B.toolCall.chunks=(as=B.toolCall.chunks)!=null?as:[],B.toolCall.chunks.push((ss=L.delta)!=null?ss:""),B.toolCall.status="running",B.streaming=!0,u(B))}}else if(tt==="agent_tool_complete"){let z=(is=L.toolCallId)!=null?is:T.lastId;if(z){let B=(ls=k.get(z))!=null?ls:pe(z);if(B.toolCall){B.toolCall.status="complete",L.result!==void 0&&(B.toolCall.result=L.result),typeof L.executionTime=="number"&&(B.toolCall.durationMs=L.executionTime),B.toolCall.completedAt=ke((sn=L.completedAt)!=null?sn:L.timestamp),B.streaming=!1,u(B);let te=ie(L);te&&T.byCall.delete(te)}}}else if(tt==="agent_media"){let z=Array.isArray(L.media)?L.media:[],B=[];for(let te of z){if(!te||typeof te!="object")continue;let ce=te,X=typeof ce.type=="string"?ce.type:void 0,He=typeof ce.mediaType=="string"?ce.mediaType.toLowerCase():"",$e=null,mt="";if(X==="media"){let lt=typeof ce.data=="string"?ce.data:void 0;if(!lt)continue;mt=He.length>0?He:"application/octet-stream",$e=`data:${mt};base64,${lt}`}else if(X==="image-url"){let lt=typeof ce.url=="string"?ce.url:void 0;if(!lt)continue;mt=He,$e=lt}else if(X==="file-url"){let lt=typeof ce.url=="string"?ce.url:void 0;if(!lt)continue;mt=He,$e=lt}else continue;if($e)if(X==="image-url"||mt.startsWith("image/"))B.push({type:"image",image:$e,...mt?{mimeType:mt}:{}});else if(mt.startsWith("audio/"))B.push({type:"audio",audio:$e,mimeType:mt});else if(mt.startsWith("video/"))B.push({type:"video",video:$e,mimeType:mt});else{let lt=mt||"application/octet-stream";B.push({type:"file",data:$e,mimeType:lt,filename:b0(lt)})}}if(B.length>0){let te=l(),ce=L.toolCallId,He={id:`agent-media-${typeof ce=="string"&&ce.length>0?`${ce}-${te}`:String(te)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:te,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(He);let $e=m;$e&&($e.streaming=!1,u($e)),m=null,x.current=null}}else if(tt!=="agent_iteration_complete"){if(tt==="agent_reflection"||tt==="agent_reflect"){let z=`agent-reflection-${L.executionId}-${L.iteration}`,B={id:z,role:"assistant",content:(ka=L.reflection)!=null?ka:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Jn=L.reflection)!=null?Jn:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(B)}else if(tt==="agent_complete"){ee&&(ee.status=L.success?"complete":"error",ee.completedAt=ke(L.completedAt),ee.stopReason=L.stopReason);let z=m;z&&(z.streaming=!1,u(z)),t({type:"status",status:"idle"})}else if(tt==="agent_error"){let z=typeof L.error=="string"?L.error:(ds=(Yn=L.error)==null?void 0:Yn.message)!=null?ds:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):t({type:"error",error:new Error(z)})}else if(tt!=="agent_ping"){if(tt==="agent_approval_start"){let z=(ci=L.approvalId)!=null?ci:`approval-${l()}`,B={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(cs=ee==null?void 0:ee.agentId)!=null?cs:"virtual",executionId:(Go=(ps=L.executionId)!=null?ps:ee==null?void 0:ee.executionId)!=null?Go:"",toolName:(pi=L.toolName)!=null?pi:"",toolType:L.toolType,description:(fi=L.description)!=null?fi:`Execute ${(ui=L.toolName)!=null?ui:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};u(B)}else if(tt==="step_await"&&L.awaitReason==="approval_required"){let z=(mi=L.approvalId)!=null?mi:`approval-${l()}`,B={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Zl=ee==null?void 0:ee.agentId)!=null?Zl:"virtual",executionId:(ko=(Ko=L.executionId)!=null?Ko:ee==null?void 0:ee.executionId)!=null?ko:"",toolName:(gi=L.toolName)!=null?gi:"",toolType:L.toolType,description:(Eo=L.description)!=null?Eo:`Execute ${(us=L.toolName)!=null?us:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};u(B)}else if(tt==="agent_approval_complete"){let z=L.approvalId;if(z){let te={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(hi=L.decision)!=null?hi:"approved",agentId:(fs=ee==null?void 0:ee.agentId)!=null?fs:"virtual",executionId:(ms=(Lo=L.executionId)!=null?Lo:ee==null?void 0:ee.executionId)!=null?ms:"",toolName:(xi=L.toolName)!=null?xi:"",description:(co=L.description)!=null?co:"",resolvedAt:Date.now()}};u(te)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let z=L.artifactType,B=String(L.id),te=typeof L.title=="string"?L.title:void 0;if(t({type:"artifact_start",id:B,artifactType:z,title:te,component:typeof L.component=="string"?L.component:void 0}),ge.set(B,{markdown:"",title:te}),!Q.has(B)){Q.add(B);let ce={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:te,artifactType:z,status:"streaming"}})};re.set(B,ce),u(ce)}}else if(tt==="artifact_delta"){let z=String(L.id),B=typeof L.delta=="string"?L.delta:String((bi=L.delta)!=null?bi:"");t({type:"artifact_delta",id:z,artDelta:B});let te=ge.get(z);te&&(te.markdown+=B)}else if(tt==="artifact_update"){let z=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};t({type:"artifact_update",id:String(L.id),props:z,component:typeof L.component=="string"?L.component:void 0})}else if(tt==="artifact_complete"){let z=String(L.id);t({type:"artifact_complete",id:z});let B=re.get(z);if(B){B.streaming=!1;try{let te=JSON.parse((Po=B.rawContent)!=null?Po:"{}");if(te.props){te.props.status="complete";let ce=ge.get(z);ce!=null&&ce.markdown&&(te.props.markdown=ce.markdown)}B.rawContent=JSON.stringify(te)}catch{}ge.delete(z),u(B),re.delete(z)}}}else if(tt==="transcript_insert"){let z=L.message;if(!z||typeof z!="object")continue;let B=String((Gt=z.id)!=null?Gt:`msg-${l()}`),te=z.role,X={id:B,role:te==="user"?"user":te==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(u(X),X.rawContent)try{let He=JSON.parse(X.rawContent),$e=(Ea=He==null?void 0:He.props)==null?void 0:Ea.artifactId;typeof $e=="string"&&Q.add($e)}catch{}m=null,x.current=null,ne.delete(B),de.delete(B)}else if(tt==="error"||tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let z=null;if(L.error instanceof Error)z=L.error;else if(tt==="dispatch_error"){let B=(La=L.message)!=null?La:L.error;B!=null&&B!==""&&(z=new Error(String(B)))}else if(tt==="step_error"||tt==="flow_error"){let B=L.error;typeof B=="string"&&B!==""?z=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(z=new Error(String((gs=B.message)!=null?gs:B)))}else tt==="error"&&L.error!=null&&L.error!==""&&(z=new Error(String(L.error)));if(z){t({type:"error",error:z});let B=m;B&&B.streaming&&(B.streaming=!1,u(B)),t({type:"status",status:"idle"})}}}}}Pe.length=0};;){let{done:F,value:fe}=await o.read();if(F)break;s+=a.decode(fe,{stream:!0});let Re=s.split(`
60
57
 
61
- `);a=(ue=Ne.pop())!=null?ue:"";for(let je of Ne){let Ke=je.split(`
62
- `),xt="message",st="";for(let X of Ke)X.startsWith("event:")?xt=X.replace("event:","").trim():X.startsWith("data:")&&(st+=X.replace("data:","").trim());if(!st)continue;let Pt;try{Pt=JSON.parse(st)}catch(X){r({type:"error",error:X instanceof Error?X:new Error("Failed to parse chat stream payload")});continue}let Zt=xt!=="message"?xt:(Oe=Pt.type)!=null?Oe:"message";if((Z=this.onSSEEvent)==null||Z.call(this,Zt,Pt),this.parseSSEEvent){x.current=m;let X=await this.handleCustomSSEEvent(Pt,r,x,f,l,S);if(x.current&&x.current!==m&&(m=x.current),X)continue}xe.push(Zt,Pt),Ve()}}xe.flushPending(),Ve(),xe.destroy()}};function $h(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${t}_${e}`}function Na(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function pa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var tl="[Image]";function Uh(t){return typeof t=="string"?[{type:"text",text:t}]:t}function qh(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function zh(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Vh(t){return typeof t=="string"?[]:t.filter(e=>e.type==="image")}function Ds(t){return{type:"text",text:t}}function jh(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 Gh(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 Kh(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 Xh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Sw=["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"],yo=[...Xh,...Sw];function Tw(t){return Xh.includes(t)||t.startsWith("image/")}function rl(t){return Tw(t.type)}async function Jh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;rl(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 Qh(t,e=yo,r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Mw(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Yh(t,e){let r=Mw(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var nl=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 ol=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 Os=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 ol;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=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let y=!1,x=M=>{y||(y=!0,clearTimeout(S),m(new Error(M)))},S=setTimeout(()=>x("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(S),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",M=>{if(!M.wasClean&&!y){let k=M.code!==1006?` (code ${M.code})`:"";x("WebSocket connection failed"+k+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(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 nl(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(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(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 ua=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 fa(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Os(t.runtype);case"browser":if(!ua.isSupported())throw new Error("Browser speech recognition not supported");return new ua(t.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function al(t){if((t==null?void 0:t.type)==="runtype"&&t.runtype)return fa({type:"runtype",runtype:t.runtype});if(ua.isSupported())return fa({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ns(t){try{return al(t),!0}catch{return!1}}function Zh(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}
58
+ `);s=(ar=Re.pop())!=null?ar:"";for(let Xe of Re){let Fe=Xe.split(`
59
+ `),Oe="message",Ye="";for(let sr of Fe)sr.startsWith("event:")?Oe=sr.replace("event:","").trim():sr.startsWith("data:")&&(Ye+=sr.replace("data:","").trim());if(!Ye)continue;let Tt;try{Tt=JSON.parse(Ye)}catch(sr){t({type:"error",error:sr instanceof Error?sr:new Error("Failed to parse chat stream payload")});continue}let Qt=Oe!=="message"?Oe:(gr=Tt.type)!=null?gr:"message";if((nn=this.onSSEEvent)==null||nn.call(this,Qt,Tt),this.parseSSEEvent){x.current=m;let sr=await this.handleCustomSSEEvent(Tt,t,x,u,l,S);if(x.current&&x.current!==m&&(m=x.current),sr)continue}It.push(Qt,Tt),ue()}}It.flushPending(),ue(),It.destroy()}};function Sh(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${r}_${e}`}function Oa(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${r}_${e}`}function ca(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${r}_${e}`}var Ki="[Image]";function Th(r){return typeof r=="string"?[{type:"text",text:r}]:r}function Mh(r){return typeof r=="string"?r:r.filter(e=>e.type==="text").map(e=>e.text).join("")}function kh(r){return typeof r=="string"?!1:r.some(e=>e.type==="image")}function Eh(r){return typeof r=="string"?[]:r.filter(e=>e.type==="image")}function Fs(r){return{type:"text",text:r}}function Lh(r,e){return{type:"image",image:r,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function Ph(r){return new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;e({type:"image",image:o,mimeType:r.type,alt:r.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(r)})}function Rh(r,e=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var Ih=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],C0=["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"],ho=[...Ih,...C0];function w0(r){return Ih.includes(r)||r.startsWith("image/")}function Xi(r){return w0(r.type)}async function Wh(r){return new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;Xi(r)?e({type:"image",image:o,mimeType:r.type,alt:r.name}):e({type:"file",data:o,mimeType:r.type,filename:r.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(r)})}function Hh(r,e=ho,t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${r.type}". Accepted types: ${e.join(", ")}`}}function A0(r){let e=r.split(".");return e.length>1?e.pop().toLowerCase():""}function Bh(r,e){let t=A0(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"}[r]||t||"FILE"}var Qi=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 t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.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 t=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(t),a=n.createBuffer(1,o.length,this.sampleRate);a.getChannelData(0).set(o);let s=n.createBufferSource();s.buffer=a,s.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=a.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,s.onended=()=>{let d=this.activeSources.indexOf(s);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let 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 t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),n=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=0;a<t;a++){let s=o.getInt16(a*2,!0);n[a]=s/32768}return n}};var Ji=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,t,n,o,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(t),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let s=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(s);let i=0;for(let p=0;p<s.length;p++)i+=s[p]*s[p];let d=Math.sqrt(i/s.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,a()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ns=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 Ji;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,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let a=o.location.protocol==="https:"?"wss:":"ws:",s=(e=this.config)==null?void 0:e.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!s)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${a}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${a}//${s}/ws/agents/${i}/voice?token=...`,f=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((u,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=M=>{v||(v=!0,clearTimeout(S),m(new Error(M)))},S=setTimeout(()=>x("WebSocket connection timed out."+f),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(S),u())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+f)},{once:!0}),this.ws.addEventListener("close",M=>{if(!M.wasClean&&!v){let E=M.code!==1006?` (code ${M.code})`:"";x("WebSocket connection failed"+E+"."+f)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let t=JSON.parse(e.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var t,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"})),(t=e.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(e.response.audio).catch(o=>this.errorCallbacks.forEach(a=>a(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 Qi(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("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,t,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let a=this.w;this.audioContext||(this.audioContext=new(a.AudioContext||a.webkitAudioContext));let s=this.audioContext,i=(t=(e=this.config)==null?void 0:e.pauseDuration)!=null?t:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(s,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(u=>u("processing")),this.processingStartCallbacks.forEach(u=>u());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",f=new Blob(this.audioChunks,{type:p});await this.sendAudio(f),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(a){throw this.errorCallbacks.forEach(s=>s(a)),this.statusCallbacks.forEach(s=>s("error")),a}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(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 a,s;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 t=this.audioContext,n=(s=(a=this.config)==null?void 0:a.silenceThreshold)!=null?s:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(t=>t(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 t;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),a=this.generateRequestId();this.currentRequestId=a,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:a}))}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((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result.split(",")[1];t(s)},o.onerror=n,o.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let t=atob(e.base64),n=new Uint8Array(t.length);for(let l=0;l<t.length;l++)n[l]=t.charCodeAt(l);let o=e.format||"mp3",a=o==="mp3"?"audio/mpeg":`audio/${o}`,s=new Blob([n],{type:a}),i=URL.createObjectURL(s),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(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 pa=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,t;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=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let a=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(a=>a(new Error(o.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 ua(r){switch(r.type){case"runtype":if(!r.runtype)throw new Error("Runtype voice provider requires configuration");return new Ns(r.runtype);case"browser":if(!pa.isSupported())throw new Error("Browser speech recognition not supported");return new pa(r.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${r.type}`)}}function Yi(r){if((r==null?void 0:r.type)==="runtype"&&r.runtype)return ua({type:"runtype",runtype:r.runtype});if(pa.isSupported())return ua({type:"browser",browser:(r==null?void 0:r.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Os(r){try{return Yi(r),!0}catch{return!1}}function Dh(r,e){let t=r instanceof Error?r:new Error(String(r));if(typeof e=="string")return e;if(typeof e=="function")return e(t);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 t.message?`${n}
63
60
 
64
- _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]}),ex=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,_a=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)&&Ho(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 ca(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 Ns((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=fa(s);let a=(r=this.config.voiceRecognition)!=null?r:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,u,f,m,y,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(x=this.pendingVoiceAssistantMessageId)!=null?x:(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,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(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 ca(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:u}=e,m={id:a!=null?a:r==="user"?Na():r==="assistant"?pa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}injectAssistantMessage(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:u=!1,voiceProcessing:f,rawContent:m}=n,x={id:d!=null?d:o==="user"?Na():o==="assistant"?pa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};r.push(x)}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,u,f,m;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=Na(),s=pa(),a={id:o,role:"user",content:n||tl,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 x=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!x){let S=Zh(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,x||(y instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,y):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=pa();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 u=Zh(l,this.config.errorMessage);if(u){let f={id:e,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(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,n){var p,u,f,m,y;let o=`approval-${e.id}`,s={...e,status:r,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},r,n):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},r),x){let S=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((f=M==null?void 0:M.error)!=null?f:`Approval request failed: ${x.status}`)}S=x.body}else x instanceof ReadableStream&&(S=x);S?await this.connectStream(S,{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(x){let S=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(y=(m=this.callbacks).onError)==null||y.call(m,x instanceof Error?x:new Error(String(x)))}}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,u,f,m,y,x,S,M,k,T,h,C;let n=this.messages.find(w=>w.id===e.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=e.agentMetadata)==null?void 0:u.executionId,s=(f=e.toolCall)==null?void 0:f.name;if(!o||!s){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof r=="string"?void 0:r;if(a===void 0&&typeof r=="string"){let w=(x=e.toolCall)==null?void 0:x.args,E=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(E.length===1){let W=typeof((S=E[0])==null?void 0:S.question)=="string"?E[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 w=typeof r=="string"?r:Object.entries(r).map(([E,W])=>`${E}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((E,W)=>{let P=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!P)return;let R=w[P],N=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(o,{[s]:r});if(!w.ok){let E=await w.json().catch(()=>null);throw new Error((T=E==null?void 0:E.error)!=null?T:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let E=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(C=(h=this.callbacks).onError)==null||C.call(h,w instanceof Error?w:new Error(String(w)))}}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 u=>{var h,C,w,E,W,P,R;let f=(h=u.toolCall)==null?void 0:h.name,m=(C=u.toolCall)==null?void 0:C.id;if(!f||!m)return null;let y=`${e}:${m}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return null;this.webMcpInflightKeys.add(y),n.push(y);let x=this.markWebMcpToolRunning(u),S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let M=(E=(w=u.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?E:f,k=this.client.executeWebMcpToolCall(f,(W=u.toolCall)==null?void 0:W.args,S.signal),T;if(!k)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await k}catch(N){let j=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return j||(R=(P=this.callbacks).onError)==null||R.call(P,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(u,_s(j?"Aborted by cancel()":ex(N)),x),this.webMcpInflightKeys.delete(y),null}return S.signal.aborted?(this.markWebMcpToolComplete(u,_s("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(y),null):{dedupeKey:y,resumeKey:M,output:T,toolMessage:u,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let f=await this.client.resumeFlow(e,u,{signal:s.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${f.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,_s("Aborted by cancel()"),m.startedAt)}finally{for(let u of n)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var m,y,x,S,M,k,T,h,C,w,E,W;let r=(m=e.agentMetadata)==null?void 0:m.executionId,n=(y=e.toolCall)==null?void 0:y.name,o=(x=e.toolCall)==null?void 0:x.id;if(!r){(M=(S=this.callbacks).onError)==null||M.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){(T=(k=this.callbacks).onError)==null||T.call(k,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),u="execute",f=a;try{let P;if(p?P=await p:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(e,_s("Aborted by cancel()"),a);return}let R=(w=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?w:n;u="resume",await this.resumeWithToolOutput(r,R,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,P,a,f)},signal:d})}catch(P){let R=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(u==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(e,_s(R||d.aborted?"Aborted by cancel()":ex(P)),a),R||(W=(E=this.callbacks).onError)==null||W.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,u,f,m,y,x,S,M,k,T;if(s!==n)return o;let a={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(a.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=r.toolCall)==null?void 0:u.name,d=(f=r.agentMetadata)==null?void 0:f.executionId,l=(m=r.toolCall)==null?void 0:m.id;if(i&&Ho(i)&&d&&l&&((y=r.agentMetadata)==null?void 0:y.awaitingLocalTool)===!0){let h=`${d}:${l}`,C=this.webMcpInflightKeys.has(h),w=this.webMcpResolvedKeys.has(h),E=(x=o.toolCall)==null?void 0:x.name,W=((S=o.agentMetadata)==null?void 0:S.executionId)===d&&((M=o.toolCall)==null?void 0:M.id)===l&&E!==void 0&&Ho(E)&&((k=o.toolCall)==null?void 0:k.status)==="complete";(C||w||W)&&(a.agentMetadata={...(T=a.agentMetadata)!=null?T:{},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},ro=(t,e,r)=>{let n=t.createElement(e);return r&&(n.className=r),n};var _d=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Fd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var $d=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Ud=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var qd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var zd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Vd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var jd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Gd=[["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 Kd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var Xd=[["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 Qd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Yd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Zd=[["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 ec=[["path",{d:"M20 6 9 17l-5-5"}]];var tc=[["path",{d:"m6 9 6 6 6-6"}]];var rc=[["path",{d:"m15 18-6-6 6-6"}]];var nc=[["path",{d:"m9 18 6-6-6-6"}]];var oc=[["path",{d:"m18 15-6-6-6 6"}]];var sl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var il=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var ac=[["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 sc=[["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 ic=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var lc=[["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 dc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var cc=[["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 pc=[["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 ll=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var dl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var uc=[["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 fc=[["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 mc=[["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 gc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var hc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var xc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var yc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var bc=[["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 wc=[["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 vc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Cc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Ac=[["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 cl=[["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 Sc=[["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 Tc=[["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 Mc=[["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 kc=[["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 Ec=[["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 Lc=[["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 pl=[["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 Pc=[["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 Ic=[["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 Rc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Wc=[["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 Bc=[["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 ul=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Hc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Dc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Oc=[["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 Nc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var _c=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Fc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var $c=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Uc=[["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 qc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var zc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Vc=[["path",{d:"M5 12h14"}]];var jc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Gc=[["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 Kc=[["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 Xc=[["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 Qc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Yc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Zc=[["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 ep=[["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 tp=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var rp=[["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 np=[["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 op=[["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 ap=[["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 sp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var ip=[["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 lp=[["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 dp=[["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 cp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var pp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var fl=[["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 up=[["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 fp=[["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 mp=[["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 gp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var ml=[["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 hp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var xp=[["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 yp=[["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 bp=[["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 wp=[["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 vp=[["path",{d:"M17 14V2"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}]];var Cp=[["path",{d:"M7 10v12"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}]];var Ap=[["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 Sp=[["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 Tp=[["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 gl=[["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 Mp=[["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 kp=[["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 Ep=[["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 Lp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Pp=[["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 Ip=[["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 Rp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Wp=[["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 kw={activity:_d,"arrow-down":Fd,"arrow-up":zd,"arrow-up-right":qd,bot:Xd,"chevron-down":tc,"chevron-up":oc,"chevron-right":nc,"chevron-left":rc,check:ec,clipboard:sc,"clipboard-copy":ac,copy:lc,file:yc,"file-code":gc,"file-spreadsheet":hc,"file-text":xc,"image-plus":Pc,loader:Hc,"loader-circle":ul,mic:qc,paperclip:Xc,"refresh-cw":np,search:sp,send:ip,"shield-alert":cp,"shield-check":pp,"shield-x":fl,square:hp,"thumbs-down":vp,"thumbs-up":Cp,upload:kp,"volume-2":Lp,x:Rp,user:Ep,mail:Oc,phone:Zc,calendar:Yd,clock:ic,building:Jd,"map-pin":Nc,lock:Dc,key:Wc,"credit-card":dc,"at-sign":Vd,hash:Mc,globe:Tc,link:Bc,"circle-check":sl,"circle-x":il,"triangle-alert":gl,info:Rc,ban:jd,shield:up,"arrow-left":$d,"arrow-right":Ud,"external-link":uc,ellipsis:dl,"ellipsis-vertical":ll,menu:Fc,house:pl,plus:tp,minus:Vc,pencil:Qc,trash:Tp,"trash-2":Sp,save:ap,download:pc,share:dp,funnel:cl,settings:lp,"rotate-cw":op,maximize:_c,minimize:zc,"shopping-cart":mp,"shopping-bag":fp,package:Kc,truck:Mp,tag:wp,gift:Sc,receipt:rp,wallet:Ip,store:yp,"dollar-sign":cc,percent:Yc,play:ep,pause:Jc,"volume-x":Pp,camera:Zd,image:Ic,film:wc,headphones:kc,"message-circle":$c,"message-square":Uc,bell:Gd,heart:Ec,star:xp,eye:mc,"eye-off":fc,bookmark:Kd,"calendar-days":Qd,history:Lc,timer:Ap,folder:Ac,"folder-open":Cc,files:bc,sparkles:ml,zap:Wp,sun:bp,moon:Gc,flag:vc,monitor:jc,smartphone:gp},Be=(t,e=24,r="currentColor",n=2)=>{let o=kw[t];return o?Ew(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 Ew(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 hl={allowedTypes:yo,maxFileSize:10*1024*1024,maxFiles:4};function Lw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Pw(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 ma=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=e.allowedTypes)!=null?r:hl.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:hl.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:hl.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:hl.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=Qh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Jh(l),f=rl(l)?URL.createObjectURL(l):null,m={id:Lw(),file:l,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(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=rl(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=Pw(e.file.type),d=Be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=v("span");l.textContent=Yh(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=Be("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 tx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Fs(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];tx(s)&&tx(o)?r[n]=Fs(s,o):r[n]=o}return r}var wn="min(440px, calc(100vw - 24px))",xl="440px",nr={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:wn,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 rx(t,e){if(!(!t&&!e))return t?e?Fs(t,e):t:e}function yl(t){var e,r,n,o,s,a,i,d,l,p,u,f,m,y,x,S,M,k,T,h,C;return t?{...nr,...t,theme:rx(nr.theme,t.theme),darkTheme:rx(nr.darkTheme,t.darkTheme),launcher:{...nr.launcher,...t.launcher,dock:{...(e=nr.launcher)==null?void 0:e.dock,...(r=t.launcher)==null?void 0:r.dock},clearChat:{...(n=nr.launcher)==null?void 0:n.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...nr.copy,...t.copy},sendButton:{...nr.sendButton,...t.sendButton},statusIndicator:{...nr.statusIndicator,...t.statusIndicator},voiceRecognition:{...nr.voiceRecognition,...t.voiceRecognition},features:(()=>{var Se,Xe,He,V,be,G,Ae,J;let w=(Se=nr.features)==null?void 0:Se.artifacts,E=(Xe=t.features)==null?void 0:Xe.artifacts,W=(He=nr.features)==null?void 0:He.scrollToBottom,P=(V=t.features)==null?void 0:V.scrollToBottom,R=(be=nr.features)==null?void 0:be.streamAnimation,N=(G=t.features)==null?void 0:G.streamAnimation,j=(Ae=nr.features)==null?void 0:Ae.askUserQuestion,oe=(J=t.features)==null?void 0:J.askUserQuestion,ve=w===void 0&&E===void 0?void 0:{...w,...E,layout:{...w==null?void 0:w.layout,...E==null?void 0:E.layout}},nt=W===void 0&&P===void 0?void 0:{...W,...P},Te=R===void 0&&N===void 0?void 0:{...R,...N},$e=j===void 0&&oe===void 0?void 0:{...j,...oe,styles:{...j==null?void 0:j.styles,...oe==null?void 0:oe.styles}};return{...nr.features,...t.features,...nt!==void 0?{scrollToBottom:nt}:{},...ve!==void 0?{artifacts:ve}:{},...Te!==void 0?{streamAnimation:Te}:{},...$e!==void 0?{askUserQuestion:$e}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:nr.suggestionChips,suggestionChipsConfig:{...nr.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...nr.layout,...t.layout,header:{...(a=nr.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=nr.layout)==null?void 0:d.messages,...(l=t.layout)==null?void 0:l.messages,avatar:{...(u=(p=nr.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=t.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(y=nr.layout)==null?void 0:y.messages)==null?void 0:x.timestamp,...(M=(S=t.layout)==null?void 0:S.messages)==null?void 0:M.timestamp}},slots:{...(k=nr.layout)==null?void 0:k.slots,...(T=t.layout)==null?void 0:T.slots}},markdown:{...nr.markdown,...t.markdown,options:{...(h=nr.markdown)==null?void 0:h.options,...(C=t.markdown)==null?void 0:C.options}},messageActions:{...nr.messageActions,...t.messageActions}}:nr}var Bp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Hp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Dp={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:wn,maxWidth:xl,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:"palette.shadows.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",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 Fa(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."))?Fa(t,n):n}function bl(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=Fa(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 Op(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 nx(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]=nx(s,o):r[n]=o}return r}function Iw(t,e){return e?nx(t,e):t}function $a(t,e={}){var o,s,a,i,d,l,p,u,f,m,y,x,S;let r={palette:Bp,semantic:Hp,components:Dp},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,...(f=(u=t==null?void 0:t.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...r.semantic.colors.feedback,...(y=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...r.semantic.spacing,...(x=t==null?void 0:t.semantic)==null?void 0:x.spacing},typography:{...r.semantic.typography,...(S=t==null?void 0:t.semantic)==null?void 0:S.typography}},components:Iw(r.components,t==null?void 0:t.components)};if(e.validate!==!1){let M=Op(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 wl(t){var x,S,M,k,T,h,C,w,E,W,P,R,N,j,oe,ve,nt,Te,$e,Se,Xe,He,V,be,G,Ae,J,ie,Me,Ge,ce,re,le,gt,ke,ye,tt,Ue,he,Q,Ve,ee,xe,z,De,Le,ge,ue,Oe,Z,O,Ie,Ne,je,Ke,xt,st,Pt,Zt,X,er,it,Vt,de,we,Ot,lr,It,hr,Ut,Nt,Mt,Rt,dr,ht,ur,Cr,Br,Ur,bt,sn,gr,Kn,Nr,oo,Dn,On,fe,I,te,Pe,Ze,tr,jt,or,Hr,qr,Cn,Jt,Gt,Dr,An,Ao,ao,So,Xn,ln,Nn,Bt,xr,yr,dn,To,Sn,_n,cn,U,Tn;let e=bl(t),r={};for(let[Ee,pn]of Object.entries(e)){let Mn=Ee.replace(/\./g,"-");r[`--persona-${Mn}`]=pn.value}r["--persona-primary"]=(x=r["--persona-semantic-colors-primary"])!=null?x: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"]=(T=r["--persona-semantic-colors-background"])!=null?T: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"]=(C=r["--persona-semantic-colors-text"])!=null?C:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(w=r["--persona-semantic-colors-text-muted"])!=null?w:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(E=r["--persona-semantic-colors-text-inverse"])!=null?E:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(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"]=(N=r["--persona-components-voice-recording-background"])!=null?N:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(j=r["--persona-components-voice-processing-icon"])!=null?j: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"]=(ve=r["--persona-components-approval-requested-background"])!=null?ve:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(nt=r["--persona-components-approval-requested-border"])!=null?nt:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Te=r["--persona-components-approval-requested-text"])!=null?Te:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=($e=r["--persona-components-approval-requested-shadow"])!=null?$e:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-approval-approve-bg"]=(Se=r["--persona-components-approval-approve-background"])!=null?Se:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Xe=r["--persona-components-approval-deny-background"])!=null?Xe:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(He=r["--persona-components-attachment-image-background"])!=null?He:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(V=r["--persona-components-attachment-image-border"])!=null?V:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(be=r["--persona-semantic-typography-fontFamily"])!=null?be:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(G=r["--persona-semantic-typography-fontSize"])!=null?G:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Ae=r["--persona-semantic-typography-fontWeight"])!=null?Ae:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(J=r["--persona-semantic-typography-lineHeight"])!=null?J: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"]=(ie=r["--persona-palette-radius-sm"])!=null?ie:"0.125rem",r["--persona-radius-md"]=(Me=r["--persona-palette-radius-md"])!=null?Me:"0.375rem",r["--persona-radius-lg"]=(Ge=r["--persona-palette-radius-lg"])!=null?Ge:"0.5rem",r["--persona-radius-xl"]=(ce=r["--persona-palette-radius-xl"])!=null?ce:"0.75rem",r["--persona-radius-full"]=(re=r["--persona-palette-radius-full"])!=null?re:"9999px",r["--persona-launcher-radius"]=(gt=(le=r["--persona-components-launcher-borderRadius"])!=null?le:r["--persona-palette-radius-full"])!=null?gt:"9999px",r["--persona-launcher-bg"]=(ke=r["--persona-components-launcher-background"])!=null?ke:r["--persona-primary"],r["--persona-launcher-fg"]=(ye=r["--persona-components-launcher-foreground"])!=null?ye:r["--persona-text-inverse"],r["--persona-launcher-border"]=(tt=r["--persona-components-launcher-border"])!=null?tt:r["--persona-border"],r["--persona-button-primary-bg"]=(Ue=r["--persona-components-button-primary-background"])!=null?Ue:r["--persona-primary"],r["--persona-button-primary-fg"]=(he=r["--persona-components-button-primary-foreground"])!=null?he:r["--persona-text-inverse"],r["--persona-button-radius"]=(Ve=(Q=r["--persona-components-button-primary-borderRadius"])!=null?Q:r["--persona-palette-radius-full"])!=null?Ve:"9999px",r["--persona-panel-radius"]=(xe=(ee=r["--persona-components-panel-borderRadius"])!=null?ee:r["--persona-radius-xl"])!=null?xe:"0.75rem",r["--persona-panel-border"]=(z=r["--persona-components-panel-border"])!=null?z:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Le=(De=r["--persona-components-panel-shadow"])!=null?De:r["--persona-palette-shadows-xl"])!=null?Le:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(ge=r["--persona-components-launcher-shadow"])!=null?ge:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Oe=(ue=r["--persona-components-input-borderRadius"])!=null?ue:r["--persona-radius-lg"])!=null?Oe:"0.5rem",r["--persona-message-user-radius"]=(O=(Z=r["--persona-components-message-user-borderRadius"])!=null?Z:r["--persona-radius-lg"])!=null?O:"0.5rem",r["--persona-message-assistant-radius"]=(Ne=(Ie=r["--persona-components-message-assistant-borderRadius"])!=null?Ie:r["--persona-radius-lg"])!=null?Ne:"0.5rem",r["--persona-header-bg"]=(je=r["--persona-components-header-background"])!=null?je:r["--persona-surface"],r["--persona-header-border"]=(Ke=r["--persona-components-header-border"])!=null?Ke:r["--persona-divider"],r["--persona-header-icon-bg"]=(xt=r["--persona-components-header-iconBackground"])!=null?xt:r["--persona-primary"],r["--persona-header-icon-fg"]=(st=r["--persona-components-header-iconForeground"])!=null?st:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Pt=r["--persona-components-header-titleForeground"])!=null?Pt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Zt=r["--persona-components-header-subtitleForeground"])!=null?Zt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(X=r["--persona-components-header-actionIconForeground"])!=null?X:r["--persona-muted"];let n=(er=t.components)==null?void 0:er.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(it=t.components)==null?void 0:it.introCard;r["--persona-intro-card-bg"]=(Vt=r["--persona-components-introCard-background"])!=null?Vt:r["--persona-surface"],r["--persona-intro-card-radius"]=(de=r["--persona-components-introCard-borderRadius"])!=null?de:"1rem",r["--persona-intro-card-padding"]=(we=r["--persona-components-introCard-padding"])!=null?we:"1.5rem",r["--persona-intro-card-shadow"]=(lr=(Ot=o==null?void 0:o.shadow)!=null?Ot:r["--persona-components-introCard-shadow"])!=null?lr:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(It=r["--persona-components-input-background"])!=null?It:r["--persona-surface"],r["--persona-input-placeholder"]=(hr=r["--persona-components-input-placeholder"])!=null?hr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Ut=r["--persona-components-message-user-background"])!=null?Ut:r["--persona-accent"],r["--persona-message-user-text"]=(Nt=r["--persona-components-message-user-text"])!=null?Nt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Mt=r["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Rt=r["--persona-components-message-assistant-background"])!=null?Rt:r["--persona-surface"],r["--persona-message-assistant-text"]=(dr=r["--persona-components-message-assistant-text"])!=null?dr:r["--persona-text"],r["--persona-message-assistant-border"]=(ht=r["--persona-components-message-assistant-border"])!=null?ht:r["--persona-border"],r["--persona-message-assistant-shadow"]=(ur=r["--persona-components-message-assistant-shadow"])!=null?ur:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(Br=(Cr=r["--persona-components-scrollToBottom-background"])!=null?Cr:r["--persona-button-primary-bg"])!=null?Br:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(bt=(Ur=r["--persona-components-scrollToBottom-foreground"])!=null?Ur:r["--persona-button-primary-fg"])!=null?bt:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(sn=r["--persona-components-scrollToBottom-border"])!=null?sn:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(gr=r["--persona-components-scrollToBottom-size"])!=null?gr:"40px",r["--persona-scroll-to-bottom-radius"]=(oo=(Nr=(Kn=r["--persona-components-scrollToBottom-borderRadius"])!=null?Kn:r["--persona-button-radius"])!=null?Nr:r["--persona-radius-full"])!=null?oo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(On=(Dn=r["--persona-components-scrollToBottom-shadow"])!=null?Dn:r["--persona-palette-shadows-sm"])!=null?On:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(fe=r["--persona-components-scrollToBottom-padding"])!=null?fe:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(I=r["--persona-components-scrollToBottom-gap"])!=null?I:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(Pe=(te=r["--persona-components-scrollToBottom-fontSize"])!=null?te:r["--persona-palette-typography-fontSize-sm"])!=null?Pe:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(Ze=r["--persona-components-scrollToBottom-iconSize"])!=null?Ze:"14px",r["--persona-tool-bubble-shadow"]=(tr=r["--persona-components-toolBubble-shadow"])!=null?tr:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(jt=r["--persona-components-reasoningBubble-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(or=r["--persona-components-composer-shadow"])!=null?or:"none",r["--persona-md-inline-code-bg"]=(Hr=r["--persona-components-markdown-inlineCode-background"])!=null?Hr:r["--persona-container"],r["--persona-md-inline-code-color"]=(qr=r["--persona-components-markdown-inlineCode-foreground"])!=null?qr:r["--persona-text"],r["--persona-md-link-color"]=(Jt=(Cn=r["--persona-components-markdown-link-foreground"])!=null?Cn:r["--persona-accent"])!=null?Jt:"#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"]=(Gt=r["--persona-components-markdown-codeBlock-background"])!=null?Gt:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Dr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Dr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(An=r["--persona-components-markdown-codeBlock-textColor"])!=null?An:"inherit",r["--persona-md-table-header-bg"]=(Ao=r["--persona-components-markdown-table-headerBackground"])!=null?Ao:r["--persona-container"],r["--persona-md-table-border-color"]=(ao=r["--persona-components-markdown-table-borderColor"])!=null?ao:r["--persona-border"],r["--persona-md-hr-color"]=(So=r["--persona-components-markdown-hr-color"])!=null?So:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(Xn=r["--persona-components-markdown-blockquote-borderColor"])!=null?Xn:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(ln=r["--persona-components-markdown-blockquote-background"])!=null?ln:"transparent",r["--persona-md-blockquote-text-color"]=(Nn=r["--persona-components-markdown-blockquote-textColor"])!=null?Nn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(Bt=r["--persona-components-collapsibleWidget-container"])!=null?Bt:r["--persona-surface"],r["--cw-surface"]=(xr=r["--persona-components-collapsibleWidget-surface"])!=null?xr:r["--persona-surface"],r["--cw-border"]=(yr=r["--persona-components-collapsibleWidget-border"])!=null?yr:r["--persona-border"],r["--persona-message-border"]=(dn=r["--persona-components-message-border"])!=null?dn:r["--persona-border"];let p=t.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(r["--persona-icon-btn-bg"]=u.background),u.border&&(r["--persona-icon-btn-border"]=u.border),u.color&&(r["--persona-icon-btn-color"]=u.color),u.padding&&(r["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(r["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(r["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(r["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(r["--persona-label-btn-bg"]=f.background),f.border&&(r["--persona-label-btn-border"]=f.border),f.color&&(r["--persona-label-btn-color"]=f.color),f.padding&&(r["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(r["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(r["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(r["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(r["--persona-label-btn-gap"]=f.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let Ee=y.toolbar;Ee.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=Ee.iconHoverColor),Ee.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=Ee.iconHoverBackground),Ee.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=Ee.iconPadding),Ee.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=Ee.iconBorderRadius),Ee.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=Ee.iconBorder),Ee.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=Ee.toggleGroupGap),Ee.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=Ee.toggleBorderRadius),Ee.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=Ee.copyBackground),Ee.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=Ee.copyBorder),Ee.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=Ee.copyColor),Ee.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=Ee.copyBorderRadius),Ee.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=Ee.copyPadding),Ee.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=Ee.copyMenuBackground,r["--persona-dropdown-bg"]=(To=r["--persona-dropdown-bg"])!=null?To:Ee.copyMenuBackground),Ee.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=Ee.copyMenuBorder,r["--persona-dropdown-border"]=(Sn=r["--persona-dropdown-border"])!=null?Sn:Ee.copyMenuBorder),Ee.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=Ee.copyMenuShadow,r["--persona-dropdown-shadow"]=(_n=r["--persona-dropdown-shadow"])!=null?_n:Ee.copyMenuShadow),Ee.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=Ee.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(cn=r["--persona-dropdown-radius"])!=null?cn:Ee.copyMenuBorderRadius),Ee.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ee.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(U=r["--persona-dropdown-item-hover-bg"])!=null?U:Ee.copyMenuItemHoverBackground),Ee.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=Ee.iconBackground),Ee.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=Ee.toolbarBorder)}if(y!=null&&y.tab){let Ee=y.tab;Ee.background&&(r["--persona-artifact-tab-bg"]=Ee.background),Ee.activeBackground&&(r["--persona-artifact-tab-active-bg"]=Ee.activeBackground),Ee.activeBorder&&(r["--persona-artifact-tab-active-border"]=Ee.activeBorder),Ee.borderRadius&&(r["--persona-artifact-tab-radius"]=Ee.borderRadius),Ee.textColor&&(r["--persona-artifact-tab-color"]=Ee.textColor),Ee.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=Ee.hoverBackground),Ee.listBackground&&(r["--persona-artifact-tab-list-bg"]=Ee.listBackground),Ee.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=Ee.listBorderColor),Ee.listPadding&&(r["--persona-artifact-tab-list-padding"]=Ee.listPadding)}if(y!=null&&y.pane){let Ee=y.pane;if(Ee.toolbarBackground){let pn=(Tn=Fa(t,Ee.toolbarBackground))!=null?Tn:Ee.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pn}}return r}var ox={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 Rw={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"}}},ax=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},$s=()=>{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"},Ww=t=>{var r;let e=(r=t==null?void 0:t.colorScheme)!=null?r:"light";return e==="light"?"light":e==="dark"?"dark":$s()},Np=t=>Ww(t),Bw=t=>$a(t),Hw=t=>{var r;let e=$a(void 0,{validate:!1});return $a({...t,palette:{...e.palette,colors:{...Rw.colors,...(r=t==null?void 0:t.palette)==null?void 0:r.colors}}},{validate:!1})},Ua=t=>{let e=Np(t),r=ax(t==null?void 0:t.theme),n=ax(t==null?void 0:t.darkTheme);return e==="dark"?Hw(Fs(r!=null?r:{},n!=null?n:{})):Bw(r)},Dw=t=>wl(t),Do=(t,e)=>{let r=Ua(e),n=Dw(r);for(let[o,s]of Object.entries(n))t.style.setProperty(o,s)},vl=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t($s())});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($s());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 sx=(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:f=>f.getAttribute("im-preserve")==="true",shouldReAppend:f=>f.getAttribute("im-re-append")==="true",shouldRemove:t,afterHeadMorphed:t},restoreFocus:!0};function r(f,m,y={}){f=p(f);let x=u(m),S=l(f,x,y),M=o(S,()=>i(S,f,x,k=>k.morphStyle==="innerHTML"?(s(k,f,x),Array.from(f.childNodes)):n(k,f,x)));return S.pantry.remove(),M}function n(f,m,y){let x=u(m);return s(f,x,y,m,m.nextSibling),Array.from(x.childNodes)}function o(f,m){var T;if(!f.config.restoreFocus)return m();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return m();let{id:x,selectionStart:S,selectionEnd:M}=y,k=m();return x&&x!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(y=f.target.querySelector(`[id="${x}"]`),y==null||y.focus()),y&&!y.selectionEnd&&M&&y.setSelectionRange(S,M),k}let s=(function(){function f(h,C,w,E=null,W=null){C instanceof HTMLTemplateElement&&w instanceof HTMLTemplateElement&&(C=C.content,w=w.content),E||(E=C.firstChild);for(let P of w.childNodes){if(E&&E!=W){let N=y(h,P,E,W);if(N){N!==E&&S(h,E,N),a(N,P,h),E=N.nextSibling;continue}}if(P instanceof Element){let N=P.getAttribute("id");if(h.persistentIds.has(N)){let j=M(C,N,E,h);a(j,P,h),E=j.nextSibling;continue}}let R=m(C,P,E,h);R&&(E=R.nextSibling)}for(;E&&E!=W;){let P=E;E=E.nextSibling,x(h,P)}}function m(h,C,w,E){if(E.callbacks.beforeNodeAdded(C)===!1)return null;if(E.idMap.has(C)){let W=document.createElement(C.tagName);return h.insertBefore(W,w),a(W,C,E),E.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(C,!0);return h.insertBefore(W,w),E.callbacks.afterNodeAdded(W),W}}let y=(function(){function h(E,W,P,R){let N=null,j=W.nextSibling,oe=0,ve=P;for(;ve&&ve!=R;){if(w(ve,W)){if(C(E,ve,W))return ve;N===null&&(E.idMap.has(ve)||(N=ve))}if(N===null&&j&&w(ve,j)&&(oe++,j=j.nextSibling,oe>=2&&(N=void 0)),E.activeElementAndParents.includes(ve))break;ve=ve.nextSibling}return N||null}function C(E,W,P){let R=E.idMap.get(W),N=E.idMap.get(P);if(!N||!R)return!1;for(let j of R)if(N.has(j))return!0;return!1}function w(E,W){var N,j,oe;let P=E,R=W;return P.nodeType===R.nodeType&&P.tagName===R.tagName&&(!((N=P.getAttribute)!=null&&N.call(P,"id"))||((j=P.getAttribute)==null?void 0:j.call(P,"id"))===((oe=R.getAttribute)==null?void 0:oe.call(R,"id")))}return h})();function x(h,C){var w;if(h.idMap.has(C))T(h.pantry,C,null);else{if(h.callbacks.beforeNodeRemoved(C)===!1)return;(w=C.parentNode)==null||w.removeChild(C),h.callbacks.afterNodeRemoved(C)}}function S(h,C,w){let E=C;for(;E&&E!==w;){let W=E;E=E.nextSibling,x(h,W)}return E}function M(h,C,w,E){var P,R;let W=((R=(P=E.target).getAttribute)==null?void 0:R.call(P,"id"))===C&&E.target||E.target.querySelector(`[id="${C}"]`)||E.pantry.querySelector(`[id="${C}"]`);return k(W,E),T(h,W,w),W}function k(h,C){let w=h.getAttribute("id");for(;h=h.parentNode;){let E=C.idMap.get(h);E&&(E.delete(w),E.size||C.idMap.delete(h))}}function T(h,C,w){if(h.moveBefore)try{h.moveBefore(C,w)}catch{h.insertBefore(C,w)}else h.insertBefore(C,w)}return f})(),a=(function(){function f(k,T,h){return h.ignoreActive&&k===document.activeElement?null:(h.callbacks.beforeNodeMorphed(k,T)===!1||(k instanceof HTMLHeadElement&&h.head.ignore||(k instanceof HTMLHeadElement&&h.head.style!=="morph"?d(k,T,h):(m(k,T,h),M(k,h)||s(h,k,T))),h.callbacks.afterNodeMorphed(k,T)),k)}function m(k,T,h){let C=T.nodeType;if(C===1){let w=k,E=T,W=w.attributes,P=E.attributes;for(let R of P)S(R.name,w,"update",h)||w.getAttribute(R.name)!==R.value&&w.setAttribute(R.name,R.value);for(let R=W.length-1;0<=R;R--){let N=W[R];if(N&&!E.hasAttribute(N.name)){if(S(N.name,w,"remove",h))continue;w.removeAttribute(N.name)}}M(w,h)||y(w,E,h)}(C===8||C===3)&&k.nodeValue!==T.nodeValue&&(k.nodeValue=T.nodeValue)}function y(k,T,h){if(k instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let C=T.value,w=k.value;x(k,T,"checked",h),x(k,T,"disabled",h),T.hasAttribute("value")?w!==C&&(S("value",k,"update",h)||(k.setAttribute("value",C),k.value=C)):S("value",k,"remove",h)||(k.value="",k.removeAttribute("value"))}else if(k instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)x(k,T,"selected",h);else if(k instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let C=T.value,w=k.value;if(S("value",k,"update",h))return;C!==w&&(k.value=C),k.firstChild&&k.firstChild.nodeValue!==C&&(k.firstChild.nodeValue=C)}}function x(k,T,h,C){let w=T[h],E=k[h];if(w!==E){let W=S(h,k,"update",C);W||(k[h]=T[h]),w?W||k.setAttribute(h,""):S(h,k,"remove",C)||k.removeAttribute(h)}}function S(k,T,h,C){return k==="value"&&C.ignoreActiveValue&&T===document.activeElement?!0:C.callbacks.beforeAttributeUpdated(k,T,h)===!1}function M(k,T){return!!T.ignoreActiveValue&&k===document.activeElement&&k!==document.body}return f})();function i(f,m,y,x){if(f.head.block){let S=m.querySelector("head"),M=y.querySelector("head");if(S&&M){let k=d(S,M,f);return Promise.all(k).then(()=>{let T=Object.assign(f,{head:{block:!1,ignore:!0}});return x(T)})}}return x(f)}function d(f,m,y){let x=[],S=[],M=[],k=[],T=new Map;for(let C of m.children)T.set(C.outerHTML,C);for(let C of f.children){let w=T.has(C.outerHTML),E=y.head.shouldReAppend(C),W=y.head.shouldPreserve(C);w||W?E?S.push(C):(T.delete(C.outerHTML),M.push(C)):y.head.style==="append"?E&&(S.push(C),k.push(C)):y.head.shouldRemove(C)!==!1&&S.push(C)}k.push(...T.values());let h=[];for(let C of k){let w=document.createRange().createContextualFragment(C.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(w)!==!1){if("href"in w&&w.href||"src"in w&&w.src){let E,W=new Promise(function(P){E=P});w.addEventListener("load",function(){E()}),h.push(W)}f.appendChild(w),y.callbacks.afterNodeAdded(w),x.push(w)}}for(let C of S)y.callbacks.beforeNodeRemoved(C)!==!1&&(f.removeChild(C),y.callbacks.afterNodeRemoved(C));return y.head.afterHeadMorphed(f,{added:x,kept:M,removed:S}),h}let l=(function(){function f(h,C,w){let{persistentIds:E,idMap:W}=k(h,C),P=m(w),R=P.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:h,newContent:C,config:P,morphStyle:R,ignoreActive:P.ignoreActive,ignoreActiveValue:P.ignoreActiveValue,restoreFocus:P.restoreFocus,idMap:W,persistentIds:E,pantry:y(),activeElementAndParents:x(h),callbacks:P.callbacks,head:P.head}}function m(h){let C=Object.assign({},e);return Object.assign(C,h),C.callbacks=Object.assign({},e.callbacks,h.callbacks),C.head=Object.assign({},e.head,h.head),C}function y(){let h=document.createElement("div");return h.hidden=!0,document.body.insertAdjacentElement("afterend",h),h}function x(h){let C=[],w=document.activeElement;if((w==null?void 0:w.tagName)!=="BODY"&&h.contains(w))for(;w&&(C.push(w),w!==h);)w=w.parentElement;return C}function S(h){var w;let C=Array.from(h.querySelectorAll("[id]"));return(w=h.getAttribute)!=null&&w.call(h,"id")&&C.push(h),C}function M(h,C,w,E){for(let W of E){let P=W.getAttribute("id");if(C.has(P)){let R=W;for(;R;){let N=h.get(R);if(N==null&&(N=new Set,h.set(R,N)),N.add(P),R===w)break;R=R.parentElement}}}}function k(h,C){let w=S(h),E=S(C),W=T(w,E),P=new Map;M(P,W,h,w);let R=C.__idiomorphRoot||C;return M(P,W,R,E),{persistentIds:W,idMap:P}}function T(h,C){let w=new Set,E=new Map;for(let{id:P,tagName:R}of h)E.has(P)?w.add(P):E.set(P,R);let W=new Set;for(let{id:P,tagName:R}of C)W.has(P)?w.add(P):E.get(P)===R&&W.add(P);for(let P of w)W.delete(P);return W}return f})(),{normalizeElement:p,normalizeParent:u}=(function(){let f=new WeakSet;function m(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(f.has(M))return M;if(M instanceof Node){if(M.parentNode)return new x(M);{let k=document.createElement("div");return k.append(M),k}}else{let k=document.createElement("div");for(let T of[...M])k.append(T);return k}}class x{constructor(k){this.originalNode=k,this.realParentNode=k.parentNode,this.previousSibling=k.previousSibling,this.nextSibling=k.nextSibling}get childNodes(){let k=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)k.push(T),T=T.nextSibling;return k}querySelectorAll(k){return this.childNodes.reduce((T,h)=>{if(h instanceof Element){h.matches(k)&&T.push(h);let C=h.querySelectorAll(k);for(let w=0;w<C.length;w++)T.push(C[w])}return T},[])}insertBefore(k,T){return this.realParentNode.insertBefore(k,T)}moveBefore(k,T){return this.realParentNode.moveBefore(k,T)}get __idiomorphRoot(){return this.originalNode}}function S(M){let k=new DOMParser,T=M.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let h=k.parseFromString(M,"text/html");if(T.match(/<\/html>/))return f.add(h),h;{let C=h.firstChild;return C&&f.add(C),C}}else{let C=k.parseFromString("<body><template>"+M+"</template></body>","text/html").body.querySelector("template").content;return f.add(C),C}}return{normalizeElement:m,normalizeParent:y}})();return{morph:r,defaults:e}})();var Cl=(t,e,r={})=>{let{preserveTypingAnimation:n=!0}=r;sx.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 Al={index:-1,draft:""};function ix(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:{...Al}}}function lx(t,e){var r,n,o,s,a,i,d,l,p,u,f,m,y,x,S,M,k,T,h,C,w,E,W,P,R,N,j,oe,ve,nt,Te,$e,Se,Xe,He,V,be,G;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,(f=(u=t.approval)==null?void 0:u.status)!=null?f:"",(y=(m=t.toolCall)==null?void 0:m.status)!=null?y:"",(S=(x=t.toolCall)==null?void 0:x.name)!=null?S:"",(T=(k=(M=t.toolCall)==null?void 0:M.chunks)==null?void 0:k.length)!=null?T:0,(E=(w=(C=(h=t.toolCall)==null?void 0:h.chunks)==null?void 0:C[t.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?E:"",typeof((W=t.toolCall)==null?void 0:W.args)=="string"?t.toolCall.args.length:(P=t.toolCall)!=null&&P.args?JSON.stringify(t.toolCall.args).length:0,(j=(N=(R=t.reasoning)==null?void 0:R.chunks)==null?void 0:N.length)!=null?j:0,(Te=(nt=(ve=(oe=t.reasoning)==null?void 0:oe.chunks)==null?void 0:ve[t.reasoning.chunks.length-1])==null?void 0:nt.length)!=null?Te:0,(He=(Xe=(Se=($e=t.reasoning)==null?void 0:$e.chunks)==null?void 0:Se[t.reasoning.chunks.length-1])==null?void 0:Xe.slice(-32))!=null?He:"",(be=(V=t.contentParts)==null?void 0:V.length)!=null?be:0,(G=t.stopReason)!=null?G:"",e].join("\0")}function dx(){return new Map}function cx(t,e,r){let n=t.get(e);return n&&n.fingerprint===r?n.wrapper:null}function px(t,e,r,n){t.set(e,{fingerprint:r,wrapper:n})}function ux(t,e){for(let r of t.keys())e.has(r)||t.delete(r)}function Sl(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Us(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function qs(t,e){return Us(t)-t.scrollTop<=e}function Tl(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 Ml(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 Gr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Kr=1e5,Oo=Kr+1;var zs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ow=["pre","code","a","script","style"],kl=t=>{var e,r,n,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:zs.type,placeholder:(r=t==null?void 0:t.placeholder)!=null?r:zs.placeholder,speed:(n=t==null?void 0:t.speed)!=null?n:zs.speed,duration:(o=t==null?void 0:t.duration)!=null?o:zs.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:zs.buffer}},mx=[{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"}],Vs=new Map;for(let t of mx)Vs.set(t.name,t);var ga=t=>{Vs.set(t.name,t)},$p=t=>{mx.some(e=>e.name===t)||Vs.delete(t)},Up=()=>Array.from(Vs.keys()),js=(t,e)=>{var r,n;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(r=e[t])!=null?r:null:(n=Vs.get(t))!=null?n:null},El=(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},Nw=(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},_w=(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},_p=/\s/,Fw=(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},$w=(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(_p.test(s[i])){let l=i;for(;l<s.length&&_p.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&&!_p.test(s[p]);)l.appendChild(Nw(n,s[p],e,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,t)},Uw=(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(_w(n,l,e,r.value)),r.value+=1));o.replaceChild(a,t)},Gs=(t,e,r,n)=>{var u,f;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((u=n==null?void 0:n.skipTags)!=null?u:Ow).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Fw(d,s)||i.push(d),d=a.nextNode();let l={value:(f=n==null?void 0:n.startIndex)!=null?f:0},p=e==="char"?$w:Uw;for(let m of i)p(m,r,l);return o.innerHTML},Ll=(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},Ks=(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},fx=new WeakMap,qw=(t,e)=>{var s;if(!t.styles)return;let r=fx.get(e);if(r||(r=new Set,fx.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)},Fp=new WeakMap,zw=(t,e)=>{if(!t.onAttach)return;let r=Fp.get(e);if(r||(r=new Map,Fp.set(e,r)),r.has(t.name))return;let n=t.onAttach(e);r.set(t.name,n)},gx=t=>{let e=Fp.get(t);if(e){for(let r of e.values())typeof r=="function"&&r();e.clear()}},qp=(t,e)=>{qw(t,e),zw(t,e)};function zp(t,e=Kr){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 Xs=0,No=null;function Vp(t=document){var r;if(Xs++,Xs===1){let n=t.body,s=((r=t.defaultView)!=null?r:window).scrollY||t.documentElement.scrollTop;No={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,Xs=Math.max(0,Xs-1),Xs===0&&No)){let o=t.body,s=(n=t.defaultView)!=null?n:window;o.style.overflow=No.originalOverflow,o.style.position=No.originalPosition,o.style.top=No.originalTop,o.style.width=No.originalWidth,s.scrollTo(0,No.scrollY),No=null}}}var Pl={side:"right",width:"420px",animate:!0,reveal:"resize"},kr=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="docked"},_o=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="composer-bar"},Wn=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:Pl.side,width:(o=e==null?void 0:e.width)!=null?o:Pl.width,animate:(s=e==null?void 0:e.animate)!=null?s:Pl.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Pl.reveal}};var Gn={"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=`
61
+ _Details: ${t.message}_`:n}var _s=r=>({isError:!0,content:[{type:"text",text:r}]}),Fh=(r,e="WebMCP tool execution failed.")=>r instanceof Error&&r.message?r.message:typeof r=="string"&&r?r:e,_a=class r{constructor(e={},t){this.config=e;this.callbacks=t;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 t,n,o,a,s,i,d,l;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall;((t=e.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Bo(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:(a=e.message.agentMetadata.iteration)!=null?a: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;((s=this.agentExecution)==null?void 0:s.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(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new da(e),this.wireDefaultWebMcpConfirm();for(let a of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(a.id,{...a,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 Os((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,t,n;return(n=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?n:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var t,n,o;try{let a=e||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=ua(a);let s=(t=this.config.voiceRecognition)!=null?t:{},i=(n=s.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=s.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,f,u,m,v,x;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}):(f=l.transcript)!=null&&f.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}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(M=>M.role==="assistant"))==null?void 0:v.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,f;this.voiceStatus=l,this.voiceActive=l==="listening",(f=(p=this.callbacks).onVoiceStatusChanged)==null||f.call(p,l)}),this.voiceProvider.connect()}catch(a){console.error("Failed to setup voice:",a)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(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 t,n,o,a,s,i,d,l,p;if(!((t=this.config.voiceRecognition)!=null&&t.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:(a=e.runtype)==null?void 0:a.host,voiceId:(s=e.runtype)==null?void 0:s.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,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(e=this.callbacks).onError)==null||t.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 t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}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,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...e},this.client=new da(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:f}=e,m={id:s!=null?s:t==="user"?Oa():t==="assistant"?ca():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}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 t=[];for(let n of e){let{role:o,content:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:p,streaming:f=!1,voiceProcessing:u,rawContent:m}=n,x={id:d!=null?d:o==="user"?Oa():o==="assistant"?ca():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:o="",llmContent:a,id:s,createdAt:i,sequence:d}=e,l={text:o,component:t,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var l,p,f,u,m;let n=e.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Oa(),a=ca(),s={id:o,role:"user",content:n||Ki,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let S=Dh(v,this.config.errorMessage);if(S){let M={id:a,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(p=this.callbacks).onError)==null||f.call(p,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,a,s,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=ca();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.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 f=Dh(l,this.config.errorMessage);if(f){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,t){var o,a,s;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.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,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,a,s;try{if(((a=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:a.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(s=e.description)!=null?s:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${t.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(a=>a.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),n(t==="approved")}async resolveApproval(e,t,n){var p,f,u,m,v;let o=`approval-${e.id}`,a={...e,status:t,resolvedAt:Date.now()},s=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,n):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let S=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((u=M==null?void 0:M.error)!=null?u:`Approval request failed: ${x.status}`)}S=x.body}else x instanceof ReadableStream&&(S=x);S?await this.connectStream(S,{allowReentry:!0}):(t==="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(x){let S=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var p,f,u,m,v,x,S,M,E,k,h,w;let n=this.messages.find(C=>C.id===e.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,a=(u=e.toolCall)==null?void 0:u.name;if(!o||!a){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof t=="string"?void 0:t;if(s===void 0&&typeof t=="string"){let C=(x=e.toolCall)==null?void 0:x.args,T=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(T.length===1){let W=typeof((S=T[0])==null?void 0:S.question)=="string"?T[0].question:"";W&&(s={[W]:t})}}this.markAskUserQuestionResolved(e,s),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(E=e.toolCall)==null?void 0:E.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([T,W])=>`${T}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=s!=null?s:{};l.forEach((T,W)=>{let R=typeof(T==null?void 0:T.question)=="string"?T.question:"";if(!R)return;let I=C[R],N=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[a]:t});if(!C.ok){let T=await C.json().catch(()=>null);throw new Error((k=T==null?void 0:T.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(w=(h=this.callbacks).onError)==null||w.call(h,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var a,s;let t=(a=e.agentMetadata)==null?void 0:a.executionId,n=(s=e.toolCall)==null?void 0:s.id;if(!t||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,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 t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(e,n)}resolveWebMcpToolStartedAt(e){var o,a;let t=this.messages.find(s=>s.id===e.id),n=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(a=e.toolCall)==null?void 0:a.startedAt];for(let s of n)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,n,o=Date.now()){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:n,completedAt:o,duration:void 0,durationMs:Math.max(0,o-n)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,l,p;let n=[],o=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(t.map(async f=>{var h,w,C,T,W,R,I;let u=(h=f.toolCall)==null?void 0:h.name,m=(w=f.toolCall)==null?void 0:w.id;if(!u||!m)return null;let v=`${e}:${m}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),n.push(v);let x=this.markWebMcpToolRunning(f),S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let M=(T=(C=f.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?T:u,E=this.client.executeWebMcpToolCall(u,(W=f.toolCall)==null?void 0:W.args,S.signal),k;if(!E)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await E}catch(N){let V=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return V||(I=(R=this.callbacks).onError)==null||I.call(R,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(f,_s(V?"Aborted by cancel()":Fh(N)),x),this.webMcpInflightKeys.delete(v),null}return S.signal.aborted?(this.markWebMcpToolComplete(f,_s("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:M,output:k,toolMessage:f,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=s.filter(m=>m!==null),i.length===0)return;let f={};for(let m of i)f[m.resumeKey]=m.output;let u=await this.client.resumeFlow(e,f,{signal:a.signal});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${u.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,f instanceof Error?f:new Error(String(f)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,_s("Aborted by cancel()"),m.startedAt)}finally{for(let f of n)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var m,v,x,S,M,E,k,h,w,C,T,W;let t=(m=e.agentMetadata)==null?void 0:m.executionId,n=(v=e.toolCall)==null?void 0:v.name,o=(x=e.toolCall)==null?void 0:x.id;if(!t){(M=(S=this.callbacks).onError)==null||M.call(S,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let R=`${t}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(t,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(I){(k=(E=this.callbacks).onError)==null||k.call(E,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(R)}return}let a=`${t}:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);let s=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),f="execute",u=s;try{let R;if(p?R=await p:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,_s("Aborted by cancel()"),s);return}let I=(C=(w=e.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?C:n;f="resume",await this.resumeWithToolOutput(t,I,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(e,R,s,u)},signal:d})}catch(R){let I=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(f==="execute"||I||d.aborted)&&this.markWebMcpToolComplete(e,_s(I||d.aborted?"Aborted by cancel()":Fh(R)),s),I||(W=(T=this.callbacks).onError)==null||W.call(T,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,n,o){var s,i;let a=await this.client.resumeFlow(e,{[t]:n},{signal:o==null?void 0:o.signal});if(!a.ok){let d=await a.json().catch(()=>null);throw new Error((s=d==null?void 0:d.error)!=null?s:`Resume failed: ${a.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let 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 t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let a={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,a),this.selectedArtifactId=t,this.emitArtifactsState(),a}let n={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,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:(t=e.component)!=null?t:"",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 t;(t=this.abortController)==null||t.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,t=null){this.artifacts.clear();for(let n of e)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!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(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,e)}speak(e,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(e),a=n.getVoices();if(t.voice){let s=a.find(i=>i.name===t.voice);s&&(o.voice=s)}else a.length>0&&(o.voice=t.pickVoice?t.pickVoice(a):r.pickBestVoice(a));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(e){var n;let t=["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 t){let a=e.find(s=>s.name===o);if(a)return a}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 t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),n=this.messages.findIndex(o=>o.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,a)=>{var p,f,u,m,v,x,S,M,E,k,h,w,C;if(a!==n)return o;let s={...o,...t};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let T=o.approval,W=t.approval;s.approval={...T,...W,executionId:W.executionId||T.executionId,toolName:W.toolName||T.toolName,description:W.description||T.description,toolType:(f=W.toolType)!=null?f:T.toolType,reason:(u=W.reason)!=null?u:T.reason,parameters:(m=W.parameters)!=null?m:T.parameters}}let i=(v=t.toolCall)==null?void 0:v.name,d=(x=t.agentMetadata)==null?void 0:x.executionId,l=(S=t.toolCall)==null?void 0:S.id;if(i&&Bo(i)&&d&&l&&((M=t.agentMetadata)==null?void 0:M.awaitingLocalTool)===!0){let T=`${d}:${l}`,W=this.webMcpInflightKeys.has(T),R=this.webMcpResolvedKeys.has(T),I=(E=o.toolCall)==null?void 0:E.name,N=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((h=o.toolCall)==null?void 0:h.id)===l&&I!==void 0&&Bo(I)&&((w=o.toolCall)==null?void 0:w.status)==="complete";(W||R||N)&&(s.agentMetadata={...(C=s.agentMetadata)!=null?C:{},awaitingLocalTool:!1},s.toolCall=o.toolCall,s.streaming=o.streaming)}return s}),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((t,n)=>{var d,l;let o=new Date(t.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(a)&&o!==a)return o-a;let s=(d=t.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return s!==i?s-i:t.id.localeCompare(n.id)})}};var y=(r,e)=>{let t=document.createElement(r);return e&&(t.className=e),t},to=(r,e,t)=>{let n=r.createElement(e);return t&&(n.className=t),n};var Ed=[["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 Ld=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Pd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Rd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Id=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Wd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Hd=[["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 Bd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Dd=[["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 Fd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var Nd=[["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 Od=[["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 _d=[["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 Ud=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var qd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var zd=[["path",{d:"M20 6 9 17l-5-5"}]];var $d=[["path",{d:"m6 9 6 6 6-6"}]];var Vd=[["path",{d:"m15 18-6-6 6-6"}]];var jd=[["path",{d:"m9 18 6-6-6-6"}]];var Gd=[["path",{d:"m18 15-6-6-6 6"}]];var Zi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var el=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Kd=[["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 Xd=[["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 Qd=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Jd=[["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 Yd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Zd=[["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 ec=[["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 tl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var rl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var tc=[["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 rc=[["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 nc=[["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 oc=[["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 ac=[["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 sc=[["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 ic=[["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 lc=[["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 dc=[["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 cc=[["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 pc=[["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 uc=[["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 nl=[["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 fc=[["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 mc=[["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 gc=[["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 hc=[["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 xc=[["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 bc=[["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 ol=[["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 yc=[["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 vc=[["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 Cc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var wc=[["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 Ac=[["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 al=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Sc=[["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 Tc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Mc=[["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 kc=[["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 Ec=[["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 Lc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Pc=[["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 Rc=[["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 Ic=[["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 Wc=[["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 Hc=[["path",{d:"M5 12h14"}]];var Bc=[["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 Dc=[["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 Fc=[["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 Nc=[["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 Oc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var _c=[["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 Uc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var qc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var zc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var $c=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Vc=[["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 jc=[["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 Gc=[["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 Kc=[["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 Xc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Qc=[["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 Jc=[["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 Yc=[["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 Zc=[["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 ep=[["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 sl=[["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 tp=[["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 rp=[["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 np=[["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 op=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var il=[["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 ap=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var sp=[["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 ip=[["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 lp=[["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 dp=[["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 cp=[["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 pp=[["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 up=[["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 fp=[["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 mp=[["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 ll=[["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 gp=[["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 hp=[["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 xp=[["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 bp=[["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 yp=[["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 vp=[["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 Cp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var wp=[["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 S0={activity:Ed,"arrow-down":Ld,"arrow-up":Wd,"arrow-up-right":Id,bot:Nd,"chevron-down":$d,"chevron-up":Gd,"chevron-right":jd,"chevron-left":Vd,check:zd,clipboard:Xd,"clipboard-copy":Kd,copy:Jd,file:ic,"file-code":oc,"file-spreadsheet":ac,"file-text":sc,"image-plus":yc,loader:Sc,"loader-circle":al,mic:Ic,paperclip:Nc,"refresh-cw":jc,search:Xc,send:Qc,"shield-alert":Zc,"shield-check":ep,"shield-x":sl,square:ap,"thumbs-down":cp,"thumbs-up":pp,upload:hp,"volume-2":bp,x:Cp,user:xp,mail:Mc,phone:qc,calendar:Ud,clock:Qd,building:Od,"map-pin":kc,lock:Tc,key:wc,"credit-card":Yd,"at-sign":Hd,hash:gc,globe:mc,link:Ac,"circle-check":Zi,"circle-x":el,"triangle-alert":ll,info:Cc,ban:Bd,shield:tp,"arrow-left":Pd,"arrow-right":Rd,"external-link":tc,ellipsis:rl,"ellipsis-vertical":tl,menu:Lc,house:ol,plus:$c,minus:Hc,pencil:_c,trash:mp,"trash-2":fp,save:Kc,download:ec,share:Yc,funnel:nl,settings:Jc,"rotate-cw":Gc,maximize:Ec,minimize:Wc,"shopping-cart":np,"shopping-bag":rp,package:Fc,truck:gp,tag:dp,gift:fc,receipt:Vc,wallet:vp,store:ip,"dollar-sign":Zd,percent:Uc,play:zc,pause:Oc,"volume-x":yp,camera:qd,image:vc,film:dc,headphones:hc,"message-circle":Pc,"message-square":Rc,bell:Dd,heart:xc,star:sp,eye:nc,"eye-off":rc,bookmark:Fd,"calendar-days":_d,history:bc,timer:up,folder:uc,"folder-open":pc,files:lc,sparkles:il,zap:wp,sun:lp,moon:Dc,flag:cc,monitor:Bc,smartphone:op},Me=(r,e=24,t="currentColor",n=2)=>{let o=S0[r];return o?T0(o,e,t,n):(console.warn(`Lucide icon "${r}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function T0(r,e,t,n){if(!Array.isArray(r))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",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),r.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var dl={allowedTypes:ho,maxFileSize:10*1024*1024,maxFiles:4};function M0(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function k0(r){return r==="application/pdf"||r.startsWith("text/")||r.includes("word")?"file-text":r.includes("excel")||r.includes("spreadsheet")?"file-spreadsheet":r==="application/json"?"file-code":"file"}var fa=class r{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,n,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:dl.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:dl.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:dl.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:dl.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 t,n,o,a,s,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,l,"count");continue}let p=Hh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let f=(o=p.error)!=null&&o.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,f);continue}try{let f=await Wh(l),u=Xi(l)?URL.createObjectURL(l):null,m={id:M0(),file:l,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var a,s,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let o=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var e,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Xi(e.file),n=y("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",t&&e.previewUrl){let s=y("img");s.src=e.previewUrl,s.alt=e.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",n.appendChild(s)}else{let s=y("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=k0(e.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=y("span");l.textContent=Bh(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",s.appendChild(l),n.appendChild(s)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let a=Me("x",10,"var(--persona-text-inverse, #ffffff)",2);a?o.appendChild(a):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(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,t){return new r({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:t})}};var Nh=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function Us(r,e){if(!r)return e;if(!e)return r;let t={...r};for(let[n,o]of Object.entries(e)){let a=t[n];Nh(a)&&Nh(o)?t[n]=Us(a,o):t[n]=o}return t}var Cn="min(440px, calc(100vw - 24px))",cl="440px",Xt={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:Cn,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:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},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 Oh(r,e){if(!(!r&&!e))return r?e?Us(r,e):r:e}function pl(r){var e,t,n,o,a,s,i,d,l,p,f,u,m,v,x,S,M,E,k,h,w;return r?{...Xt,...r,theme:Oh(Xt.theme,r.theme),darkTheme:Oh(Xt.darkTheme,r.darkTheme),launcher:{...Xt.launcher,...r.launcher,dock:{...(e=Xt.launcher)==null?void 0:e.dock,...(t=r.launcher)==null?void 0:t.dock},clearChat:{...(n=Xt.launcher)==null?void 0:n.clearChat,...(o=r.launcher)==null?void 0:o.clearChat}},copy:{...Xt.copy,...r.copy},sendButton:{...Xt.sendButton,...r.sendButton},statusIndicator:{...Xt.statusIndicator,...r.statusIndicator},voiceRecognition:{...Xt.voiceRecognition,...r.voiceRecognition},features:(()=>{var J,re,Q,ge,Z,G,pe,ke,le,ne;let C=(J=Xt.features)==null?void 0:J.artifacts,T=(re=r.features)==null?void 0:re.artifacts,W=(Q=Xt.features)==null?void 0:Q.scrollToBottom,R=(ge=r.features)==null?void 0:ge.scrollToBottom,I=(Z=Xt.features)==null?void 0:Z.scrollBehavior,N=(G=r.features)==null?void 0:G.scrollBehavior,V=(pe=Xt.features)==null?void 0:pe.streamAnimation,ie=(ke=r.features)==null?void 0:ke.streamAnimation,xe=(le=Xt.features)==null?void 0:le.askUserQuestion,Je=(ne=r.features)==null?void 0:ne.askUserQuestion,we=C===void 0&&T===void 0?void 0:{...C,...T,layout:{...C==null?void 0:C.layout,...T==null?void 0:T.layout}},De=W===void 0&&R===void 0?void 0:{...W,...R},Ae=I===void 0&&N===void 0?void 0:{...I,...N},qe=V===void 0&&ie===void 0?void 0:{...V,...ie},Ie=xe===void 0&&Je===void 0?void 0:{...xe,...Je,styles:{...xe==null?void 0:xe.styles,...Je==null?void 0:Je.styles}};return{...Xt.features,...r.features,...De!==void 0?{scrollToBottom:De}:{},...Ae!==void 0?{scrollBehavior:Ae}:{},...we!==void 0?{artifacts:we}:{},...qe!==void 0?{streamAnimation:qe}:{},...Ie!==void 0?{askUserQuestion:Ie}:{}}})(),suggestionChips:(a=r.suggestionChips)!=null?a:Xt.suggestionChips,suggestionChipsConfig:{...Xt.suggestionChipsConfig,...r.suggestionChipsConfig},layout:{...Xt.layout,...r.layout,header:{...(s=Xt.layout)==null?void 0:s.header,...(i=r.layout)==null?void 0:i.header},messages:{...(d=Xt.layout)==null?void 0:d.messages,...(l=r.layout)==null?void 0:l.messages,avatar:{...(f=(p=Xt.layout)==null?void 0:p.messages)==null?void 0:f.avatar,...(m=(u=r.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Xt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(M=(S=r.layout)==null?void 0:S.messages)==null?void 0:M.timestamp}},slots:{...(E=Xt.layout)==null?void 0:E.slots,...(k=r.layout)==null?void 0:k.slots}},markdown:{...Xt.markdown,...r.markdown,options:{...(h=Xt.markdown)==null?void 0:h.options,...(w=r.markdown)==null?void 0:w.options}},messageActions:{...Xt.messageActions,...r.messageActions}}:Xt}var Ap={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"}},Sp={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"}},Tp={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:Cn,maxWidth:cl,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:"palette.shadows.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",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 Ua(r,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),n=r;for(let o of t){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ua(r,n):n}function ul(r){let e={};function t(n,o){for(let[a,s]of Object.entries(n)){let i=`${o}.${a}`;if(typeof s=="string"){let d=Ua(r,s);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 s=="object"&&s!==null&&t(s,i)}}return t(r.palette,"palette"),t(r.semantic,"semantic"),t(r.components,"components"),e}function Mp(r){let e=[],t=[];return r.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),r.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),r.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function _h(r,e){let t={...r};for(let[n,o]of Object.entries(e)){let a=t[n];a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?t[n]=_h(a,o):t[n]=o}return t}function E0(r,e){return e?_h(r,e):r}function qa(r,e={}){var o,a,s,i,d,l,p,f,u,m,v,x,S;let t={palette:Ap,semantic:Sp,components:Tp},n={palette:{...t.palette,...r==null?void 0:r.palette,colors:{...t.palette.colors,...(o=r==null?void 0:r.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(a=r==null?void 0:r.palette)==null?void 0:a.spacing},typography:{...t.palette.typography,...(s=r==null?void 0:r.palette)==null?void 0:s.typography},shadows:{...t.palette.shadows,...(i=r==null?void 0:r.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=r==null?void 0:r.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=r==null?void 0:r.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...r==null?void 0:r.semantic,colors:{...t.semantic.colors,...(p=r==null?void 0:r.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(u=(f=r==null?void 0:r.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=r==null?void 0:r.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=r==null?void 0:r.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(S=r==null?void 0:r.semantic)==null?void 0:S.typography}},components:E0(t.components,r==null?void 0:r.components)};if(e.validate!==!1){let M=Mp(n);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let M of e.plugins)n=M.transform(n);return n}function fl(r){var x,S,M,E,k,h,w,C,T,W,R,I,N,V,ie,xe,Je,we,De,Ae,qe,Ie,J,re,Q,ge,Z,G,pe,ke,le,ne,de,Lt,St,We,he,at,Pe,j,ue,nt,It,ee,je,Fr,Dt,ar,gr,nn,F,fe,Re,Xe,Fe,Oe,Ye,Tt,Qt,sr,K,ft,it,ye,se,st,ur,ct,xr,Ir,pt,Pt,et,$t,br,ir,fr,Sr,cn,Mt,_r,hr,An,on,Ct,jn,Sn,_e,P,ae,Ee,Ot,Ze,_t,Zt,dr,wt,Ur,Vt,qr,Fn,no,wo,pn,jt,Kr,Tn,Ao,oo,So,Gn,un,Nn,kt,yr,vr,fn,To;let e=ul(r),t={};for(let[ve,Mn]of Object.entries(e)){let kn=ve.replace(/\./g,"-");t[`--persona-${kn}`]=Mn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(S=t["--persona-semantic-colors-secondary"])!=null?S:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(M=t["--persona-semantic-colors-accent"])!=null?M:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(E=t["--persona-semantic-colors-surface"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(h=t["--persona-semantic-colors-container"])!=null?h:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(T=t["--persona-semantic-colors-text-inverse"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(W=t["--persona-semantic-colors-border"])!=null?W:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(R=t["--persona-semantic-colors-divider"])!=null?R:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(I=t["--persona-components-voice-recording-indicator"])!=null?I:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(N=t["--persona-components-voice-recording-background"])!=null?N:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ie=t["--persona-components-voice-speaking-icon"])!=null?ie:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(xe=t["--persona-components-approval-requested-background"])!=null?xe:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Je=t["--persona-components-approval-requested-border"])!=null?Je:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(we=t["--persona-components-approval-requested-text"])!=null?we:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(De=t["--persona-components-approval-requested-shadow"])!=null?De:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Ae=t["--persona-components-approval-approve-background"])!=null?Ae:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(qe=t["--persona-components-approval-deny-background"])!=null?qe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ie=t["--persona-components-attachment-image-background"])!=null?Ie:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(J=t["--persona-components-attachment-image-border"])!=null?J:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Q=t["--persona-semantic-typography-fontSize"])!=null?Q:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ge=t["--persona-semantic-typography-fontWeight"])!=null?ge:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Z=t["--persona-semantic-typography-lineHeight"])!=null?Z:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(G=t["--persona-palette-radius-sm"])!=null?G:"0.125rem",t["--persona-radius-md"]=(pe=t["--persona-palette-radius-md"])!=null?pe:"0.375rem",t["--persona-radius-lg"]=(ke=t["--persona-palette-radius-lg"])!=null?ke:"0.5rem",t["--persona-radius-xl"]=(le=t["--persona-palette-radius-xl"])!=null?le:"0.75rem",t["--persona-radius-full"]=(ne=t["--persona-palette-radius-full"])!=null?ne:"9999px",t["--persona-launcher-radius"]=(Lt=(de=t["--persona-components-launcher-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?Lt:"9999px",t["--persona-launcher-bg"]=(St=t["--persona-components-launcher-background"])!=null?St:t["--persona-primary"],t["--persona-launcher-fg"]=(We=t["--persona-components-launcher-foreground"])!=null?We:t["--persona-text-inverse"],t["--persona-launcher-border"]=(he=t["--persona-components-launcher-border"])!=null?he:t["--persona-border"],t["--persona-button-primary-bg"]=(at=t["--persona-components-button-primary-background"])!=null?at:t["--persona-primary"],t["--persona-button-primary-fg"]=(Pe=t["--persona-components-button-primary-foreground"])!=null?Pe:t["--persona-text-inverse"],t["--persona-button-radius"]=(ue=(j=t["--persona-components-button-primary-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?ue:"9999px",t["--persona-panel-radius"]=(It=(nt=t["--persona-components-panel-borderRadius"])!=null?nt:t["--persona-radius-xl"])!=null?It:"0.75rem",t["--persona-panel-border"]=(ee=t["--persona-components-panel-border"])!=null?ee:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Fr=(je=t["--persona-components-panel-shadow"])!=null?je:t["--persona-palette-shadows-xl"])!=null?Fr:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(Dt=t["--persona-components-launcher-shadow"])!=null?Dt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(gr=(ar=t["--persona-components-input-borderRadius"])!=null?ar:t["--persona-radius-lg"])!=null?gr:"0.5rem",t["--persona-message-user-radius"]=(F=(nn=t["--persona-components-message-user-borderRadius"])!=null?nn:t["--persona-radius-lg"])!=null?F:"0.5rem",t["--persona-message-assistant-radius"]=(Re=(fe=t["--persona-components-message-assistant-borderRadius"])!=null?fe:t["--persona-radius-lg"])!=null?Re:"0.5rem",t["--persona-header-bg"]=(Xe=t["--persona-components-header-background"])!=null?Xe:t["--persona-surface"],t["--persona-header-border"]=(Fe=t["--persona-components-header-border"])!=null?Fe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Oe=t["--persona-components-header-iconBackground"])!=null?Oe:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ye=t["--persona-components-header-iconForeground"])!=null?Ye:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Tt=t["--persona-components-header-titleForeground"])!=null?Tt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Qt=t["--persona-components-header-subtitleForeground"])!=null?Qt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(sr=t["--persona-components-header-actionIconForeground"])!=null?sr:t["--persona-muted"];let n=(K=r.components)==null?void 0:K.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom);let o=(ft=r.components)==null?void 0:ft.introCard;t["--persona-intro-card-bg"]=(it=t["--persona-components-introCard-background"])!=null?it:t["--persona-surface"],t["--persona-intro-card-radius"]=(ye=t["--persona-components-introCard-borderRadius"])!=null?ye:"1rem",t["--persona-intro-card-padding"]=(se=t["--persona-components-introCard-padding"])!=null?se:"1.5rem",t["--persona-intro-card-shadow"]=(ur=(st=o==null?void 0:o.shadow)!=null?st:t["--persona-components-introCard-shadow"])!=null?ur:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(ct=t["--persona-components-input-background"])!=null?ct:t["--persona-surface"],t["--persona-input-placeholder"]=(xr=t["--persona-components-input-placeholder"])!=null?xr:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Ir=t["--persona-components-message-user-background"])!=null?Ir:t["--persona-accent"],t["--persona-message-user-text"]=(pt=t["--persona-components-message-user-text"])!=null?pt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Pt=t["--persona-components-message-user-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(et=t["--persona-components-message-assistant-background"])!=null?et:t["--persona-surface"],t["--persona-message-assistant-text"]=($t=t["--persona-components-message-assistant-text"])!=null?$t:t["--persona-text"],t["--persona-message-assistant-border"]=(br=t["--persona-components-message-assistant-border"])!=null?br:t["--persona-border"],t["--persona-message-assistant-shadow"]=(ir=t["--persona-components-message-assistant-shadow"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Sr=(fr=t["--persona-components-scrollToBottom-background"])!=null?fr:t["--persona-button-primary-bg"])!=null?Sr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Mt=(cn=t["--persona-components-scrollToBottom-foreground"])!=null?cn:t["--persona-button-primary-fg"])!=null?Mt:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(_r=t["--persona-components-scrollToBottom-border"])!=null?_r:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(hr=t["--persona-components-scrollToBottom-size"])!=null?hr:"40px",t["--persona-scroll-to-bottom-radius"]=(Ct=(on=(An=t["--persona-components-scrollToBottom-borderRadius"])!=null?An:t["--persona-button-radius"])!=null?on:t["--persona-radius-full"])!=null?Ct:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Sn=(jn=t["--persona-components-scrollToBottom-shadow"])!=null?jn:t["--persona-palette-shadows-sm"])!=null?Sn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(_e=t["--persona-components-scrollToBottom-padding"])!=null?_e:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(P=t["--persona-components-scrollToBottom-gap"])!=null?P:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Ee=(ae=t["--persona-components-scrollToBottom-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-sm"])!=null?Ee:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Ot=t["--persona-components-scrollToBottom-iconSize"])!=null?Ot:"14px",t["--persona-tool-bubble-shadow"]=(Ze=t["--persona-components-toolBubble-shadow"])!=null?Ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(_t=t["--persona-components-reasoningBubble-shadow"])!=null?_t:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Zt=t["--persona-components-composer-shadow"])!=null?Zt:"none",t["--persona-md-inline-code-bg"]=(dr=t["--persona-components-markdown-inlineCode-background"])!=null?dr:t["--persona-container"],t["--persona-md-inline-code-color"]=(wt=t["--persona-components-markdown-inlineCode-foreground"])!=null?wt:t["--persona-text"],t["--persona-md-link-color"]=(Vt=(Ur=t["--persona-components-markdown-link-foreground"])!=null?Ur:t["--persona-accent"])!=null?Vt:"#0f0f0f";let a=t["--persona-components-markdown-heading-h1-fontSize"];a&&(t["--persona-md-h1-size"]=a);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(qr=t["--persona-components-markdown-codeBlock-background"])!=null?qr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Fn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Fn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(no=t["--persona-components-markdown-codeBlock-textColor"])!=null?no:"inherit",t["--persona-md-table-header-bg"]=(wo=t["--persona-components-markdown-table-headerBackground"])!=null?wo:t["--persona-container"],t["--persona-md-table-border-color"]=(pn=t["--persona-components-markdown-table-borderColor"])!=null?pn:t["--persona-border"],t["--persona-md-hr-color"]=(jt=t["--persona-components-markdown-hr-color"])!=null?jt:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Kr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Kr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Tn=t["--persona-components-markdown-blockquote-background"])!=null?Tn:"transparent",t["--persona-md-blockquote-text-color"]=(Ao=t["--persona-components-markdown-blockquote-textColor"])!=null?Ao:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(oo=t["--persona-components-collapsibleWidget-container"])!=null?oo:t["--persona-surface"],t["--cw-surface"]=(So=t["--persona-components-collapsibleWidget-surface"])!=null?So:t["--persona-surface"],t["--cw-border"]=(Gn=t["--persona-components-collapsibleWidget-border"])!=null?Gn:t["--persona-border"],t["--persona-message-border"]=(un=t["--persona-components-message-border"])!=null?un:t["--persona-border"];let p=r.components,f=p==null?void 0:p.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let ve=v.toolbar;ve.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ve.iconHoverColor),ve.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ve.iconHoverBackground),ve.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ve.iconPadding),ve.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ve.iconBorderRadius),ve.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ve.iconBorder),ve.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ve.toggleGroupGap),ve.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ve.toggleBorderRadius),ve.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ve.copyBackground),ve.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ve.copyBorder),ve.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ve.copyColor),ve.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ve.copyBorderRadius),ve.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ve.copyPadding),ve.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ve.copyMenuBackground,t["--persona-dropdown-bg"]=(Nn=t["--persona-dropdown-bg"])!=null?Nn:ve.copyMenuBackground),ve.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ve.copyMenuBorder,t["--persona-dropdown-border"]=(kt=t["--persona-dropdown-border"])!=null?kt:ve.copyMenuBorder),ve.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ve.copyMenuShadow,t["--persona-dropdown-shadow"]=(yr=t["--persona-dropdown-shadow"])!=null?yr:ve.copyMenuShadow),ve.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ve.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(vr=t["--persona-dropdown-radius"])!=null?vr:ve.copyMenuBorderRadius),ve.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ve.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(fn=t["--persona-dropdown-item-hover-bg"])!=null?fn:ve.copyMenuItemHoverBackground),ve.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ve.iconBackground),ve.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ve.toolbarBorder)}if(v!=null&&v.tab){let ve=v.tab;ve.background&&(t["--persona-artifact-tab-bg"]=ve.background),ve.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ve.activeBackground),ve.activeBorder&&(t["--persona-artifact-tab-active-border"]=ve.activeBorder),ve.borderRadius&&(t["--persona-artifact-tab-radius"]=ve.borderRadius),ve.textColor&&(t["--persona-artifact-tab-color"]=ve.textColor),ve.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ve.hoverBackground),ve.listBackground&&(t["--persona-artifact-tab-list-bg"]=ve.listBackground),ve.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ve.listBorderColor),ve.listPadding&&(t["--persona-artifact-tab-list-padding"]=ve.listPadding)}if(v!=null&&v.pane){let ve=v.pane;if(ve.toolbarBackground){let Mn=(To=Ua(r,ve.toolbarBackground))!=null?To:ve.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Mn}}return t}var Uh={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 L0={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"}}},qh=r=>{if(!(!r||typeof r!="object"||Array.isArray(r)))return r},qs=()=>{var r;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},P0=r=>{var t;let e=(t=r==null?void 0:r.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":qs()},kp=r=>P0(r),R0=r=>qa(r),I0=r=>{var t;let e=qa(void 0,{validate:!1});return qa({...r,palette:{...e.palette,colors:{...L0.colors,...(t=r==null?void 0:r.palette)==null?void 0:t.colors}}},{validate:!1})},za=r=>{let e=kp(r),t=qh(r==null?void 0:r.theme),n=qh(r==null?void 0:r.darkTheme);return e==="dark"?I0(Us(t!=null?t:{},n!=null?n:{})):R0(t)},W0=r=>fl(r),Do=(r,e)=>{let t=za(e),n=W0(t);for(let[o,a]of Object.entries(n))r.style.setProperty(o,a)},ml=r=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{r(qs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>r(qs());t.addEventListener?(t.addEventListener("change",n),e.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),e.push(()=>t.removeListener(n)))}return()=>{e.forEach(t=>t())}};var zh=(function(){"use strict";let r=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:r,afterNodeAdded:r,beforeNodeMorphed:r,afterNodeMorphed:r,beforeNodeRemoved:r,afterNodeRemoved:r,beforeAttributeUpdated:r},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:r,afterHeadMorphed:r},restoreFocus:!0};function t(u,m,v={}){u=p(u);let x=f(m),S=l(u,x,v),M=o(S,()=>i(S,u,x,E=>E.morphStyle==="innerHTML"?(a(E,u,x),Array.from(u.childNodes)):n(E,u,x)));return S.pantry.remove(),M}function n(u,m,v){let x=f(m);return a(u,x,v,m,m.nextSibling),Array.from(x.childNodes)}function o(u,m){var k;if(!u.config.restoreFocus)return m();let v=document.activeElement;if(!(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement))return m();let{id:x,selectionStart:S,selectionEnd:M}=v,E=m();return x&&x!==((k=document.activeElement)==null?void 0:k.getAttribute("id"))&&(v=u.target.querySelector(`[id="${x}"]`),v==null||v.focus()),v&&!v.selectionEnd&&M&&v.setSelectionRange(S,M),E}let a=(function(){function u(h,w,C,T=null,W=null){w instanceof HTMLTemplateElement&&C instanceof HTMLTemplateElement&&(w=w.content,C=C.content),T||(T=w.firstChild);for(let R of C.childNodes){if(T&&T!=W){let N=v(h,R,T,W);if(N){N!==T&&S(h,T,N),s(N,R,h),T=N.nextSibling;continue}}if(R instanceof Element){let N=R.getAttribute("id");if(h.persistentIds.has(N)){let V=M(w,N,T,h);s(V,R,h),T=V.nextSibling;continue}}let I=m(w,R,T,h);I&&(T=I.nextSibling)}for(;T&&T!=W;){let R=T;T=T.nextSibling,x(h,R)}}function m(h,w,C,T){if(T.callbacks.beforeNodeAdded(w)===!1)return null;if(T.idMap.has(w)){let W=document.createElement(w.tagName);return h.insertBefore(W,C),s(W,w,T),T.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(w,!0);return h.insertBefore(W,C),T.callbacks.afterNodeAdded(W),W}}let v=(function(){function h(T,W,R,I){let N=null,V=W.nextSibling,ie=0,xe=R;for(;xe&&xe!=I;){if(C(xe,W)){if(w(T,xe,W))return xe;N===null&&(T.idMap.has(xe)||(N=xe))}if(N===null&&V&&C(xe,V)&&(ie++,V=V.nextSibling,ie>=2&&(N=void 0)),T.activeElementAndParents.includes(xe))break;xe=xe.nextSibling}return N||null}function w(T,W,R){let I=T.idMap.get(W),N=T.idMap.get(R);if(!N||!I)return!1;for(let V of I)if(N.has(V))return!0;return!1}function C(T,W){var N,V,ie;let R=T,I=W;return R.nodeType===I.nodeType&&R.tagName===I.tagName&&(!((N=R.getAttribute)!=null&&N.call(R,"id"))||((V=R.getAttribute)==null?void 0:V.call(R,"id"))===((ie=I.getAttribute)==null?void 0:ie.call(I,"id")))}return h})();function x(h,w){var C;if(h.idMap.has(w))k(h.pantry,w,null);else{if(h.callbacks.beforeNodeRemoved(w)===!1)return;(C=w.parentNode)==null||C.removeChild(w),h.callbacks.afterNodeRemoved(w)}}function S(h,w,C){let T=w;for(;T&&T!==C;){let W=T;T=T.nextSibling,x(h,W)}return T}function M(h,w,C,T){var R,I;let W=((I=(R=T.target).getAttribute)==null?void 0:I.call(R,"id"))===w&&T.target||T.target.querySelector(`[id="${w}"]`)||T.pantry.querySelector(`[id="${w}"]`);return E(W,T),k(h,W,C),W}function E(h,w){let C=h.getAttribute("id");for(;h=h.parentNode;){let T=w.idMap.get(h);T&&(T.delete(C),T.size||w.idMap.delete(h))}}function k(h,w,C){if(h.moveBefore)try{h.moveBefore(w,C)}catch{h.insertBefore(w,C)}else h.insertBefore(w,C)}return u})(),s=(function(){function u(E,k,h){return h.ignoreActive&&E===document.activeElement?null:(h.callbacks.beforeNodeMorphed(E,k)===!1||(E instanceof HTMLHeadElement&&h.head.ignore||(E instanceof HTMLHeadElement&&h.head.style!=="morph"?d(E,k,h):(m(E,k,h),M(E,h)||a(h,E,k))),h.callbacks.afterNodeMorphed(E,k)),E)}function m(E,k,h){let w=k.nodeType;if(w===1){let C=E,T=k,W=C.attributes,R=T.attributes;for(let I of R)S(I.name,C,"update",h)||C.getAttribute(I.name)!==I.value&&C.setAttribute(I.name,I.value);for(let I=W.length-1;0<=I;I--){let N=W[I];if(N&&!T.hasAttribute(N.name)){if(S(N.name,C,"remove",h))continue;C.removeAttribute(N.name)}}M(C,h)||v(C,T,h)}(w===8||w===3)&&E.nodeValue!==k.nodeValue&&(E.nodeValue=k.nodeValue)}function v(E,k,h){if(E instanceof HTMLInputElement&&k instanceof HTMLInputElement&&k.type!=="file"){let w=k.value,C=E.value;x(E,k,"checked",h),x(E,k,"disabled",h),k.hasAttribute("value")?C!==w&&(S("value",E,"update",h)||(E.setAttribute("value",w),E.value=w)):S("value",E,"remove",h)||(E.value="",E.removeAttribute("value"))}else if(E instanceof HTMLOptionElement&&k instanceof HTMLOptionElement)x(E,k,"selected",h);else if(E instanceof HTMLTextAreaElement&&k instanceof HTMLTextAreaElement){let w=k.value,C=E.value;if(S("value",E,"update",h))return;w!==C&&(E.value=w),E.firstChild&&E.firstChild.nodeValue!==w&&(E.firstChild.nodeValue=w)}}function x(E,k,h,w){let C=k[h],T=E[h];if(C!==T){let W=S(h,E,"update",w);W||(E[h]=k[h]),C?W||E.setAttribute(h,""):S(h,E,"remove",w)||E.removeAttribute(h)}}function S(E,k,h,w){return E==="value"&&w.ignoreActiveValue&&k===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(E,k,h)===!1}function M(E,k){return!!k.ignoreActiveValue&&E===document.activeElement&&E!==document.body}return u})();function i(u,m,v,x){if(u.head.block){let S=m.querySelector("head"),M=v.querySelector("head");if(S&&M){let E=d(S,M,u);return Promise.all(E).then(()=>{let k=Object.assign(u,{head:{block:!1,ignore:!0}});return x(k)})}}return x(u)}function d(u,m,v){let x=[],S=[],M=[],E=[],k=new Map;for(let w of m.children)k.set(w.outerHTML,w);for(let w of u.children){let C=k.has(w.outerHTML),T=v.head.shouldReAppend(w),W=v.head.shouldPreserve(w);C||W?T?S.push(w):(k.delete(w.outerHTML),M.push(w)):v.head.style==="append"?T&&(S.push(w),E.push(w)):v.head.shouldRemove(w)!==!1&&S.push(w)}E.push(...k.values());let h=[];for(let w of E){let C=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(v.callbacks.beforeNodeAdded(C)!==!1){if("href"in C&&C.href||"src"in C&&C.src){let T,W=new Promise(function(R){T=R});C.addEventListener("load",function(){T()}),h.push(W)}u.appendChild(C),v.callbacks.afterNodeAdded(C),x.push(C)}}for(let w of S)v.callbacks.beforeNodeRemoved(w)!==!1&&(u.removeChild(w),v.callbacks.afterNodeRemoved(w));return v.head.afterHeadMorphed(u,{added:x,kept:M,removed:S}),h}let l=(function(){function u(h,w,C){let{persistentIds:T,idMap:W}=E(h,w),R=m(C),I=R.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(I))throw`Do not understand how to morph style ${I}`;return{target:h,newContent:w,config:R,morphStyle:I,ignoreActive:R.ignoreActive,ignoreActiveValue:R.ignoreActiveValue,restoreFocus:R.restoreFocus,idMap:W,persistentIds:T,pantry:v(),activeElementAndParents:x(h),callbacks:R.callbacks,head:R.head}}function m(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 v(){let h=document.createElement("div");return h.hidden=!0,document.body.insertAdjacentElement("afterend",h),h}function x(h){let w=[],C=document.activeElement;if((C==null?void 0:C.tagName)!=="BODY"&&h.contains(C))for(;C&&(w.push(C),C!==h);)C=C.parentElement;return w}function S(h){var C;let w=Array.from(h.querySelectorAll("[id]"));return(C=h.getAttribute)!=null&&C.call(h,"id")&&w.push(h),w}function M(h,w,C,T){for(let W of T){let R=W.getAttribute("id");if(w.has(R)){let I=W;for(;I;){let N=h.get(I);if(N==null&&(N=new Set,h.set(I,N)),N.add(R),I===C)break;I=I.parentElement}}}}function E(h,w){let C=S(h),T=S(w),W=k(C,T),R=new Map;M(R,W,h,C);let I=w.__idiomorphRoot||w;return M(R,W,I,T),{persistentIds:W,idMap:R}}function k(h,w){let C=new Set,T=new Map;for(let{id:R,tagName:I}of h)T.has(R)?C.add(R):T.set(R,I);let W=new Set;for(let{id:R,tagName:I}of w)W.has(R)?C.add(R):T.get(R)===I&&W.add(R);for(let R of C)W.delete(R);return W}return u})(),{normalizeElement:p,normalizeParent:f}=(function(){let u=new WeakSet;function m(M){return M instanceof Document?M.documentElement:M}function v(M){if(M==null)return document.createElement("div");if(typeof M=="string")return v(S(M));if(u.has(M))return M;if(M instanceof Node){if(M.parentNode)return new x(M);{let E=document.createElement("div");return E.append(M),E}}else{let E=document.createElement("div");for(let k of[...M])E.append(k);return E}}class x{constructor(E){this.originalNode=E,this.realParentNode=E.parentNode,this.previousSibling=E.previousSibling,this.nextSibling=E.nextSibling}get childNodes(){let E=[],k=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;k&&k!=this.nextSibling;)E.push(k),k=k.nextSibling;return E}querySelectorAll(E){return this.childNodes.reduce((k,h)=>{if(h instanceof Element){h.matches(E)&&k.push(h);let w=h.querySelectorAll(E);for(let C=0;C<w.length;C++)k.push(w[C])}return k},[])}insertBefore(E,k){return this.realParentNode.insertBefore(E,k)}moveBefore(E,k){return this.realParentNode.moveBefore(E,k)}get __idiomorphRoot(){return this.originalNode}}function S(M){let E=new DOMParser,k=M.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(k.match(/<\/html>/)||k.match(/<\/head>/)||k.match(/<\/body>/)){let h=E.parseFromString(M,"text/html");if(k.match(/<\/html>/))return u.add(h),h;{let w=h.firstChild;return w&&u.add(w),w}}else{let w=E.parseFromString("<body><template>"+M+"</template></body>","text/html").body.querySelector("template").content;return u.add(w),w}}return{normalizeElement:m,normalizeParent:v}})();return{morph:t,defaults:e}})();var gl=(r,e,t={})=>{let{preserveTypingAnimation:n=!0}=t;zh.morph(r,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,a){var s,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let d=(s=o.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var hl={index:-1,draft:""};function $h(r){let{direction:e,history:t,currentValue:n,atStart:o,state:a}=r,s=a.index!==-1;if(t.length===0)return{handled:!1,state:a};if(e==="up"){if(!s&&!o)return{handled:!1,state:a};if(!s){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:n}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:t[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<t.length-1){let i=a.index+1;return{handled:!0,value:t[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...hl}}}function Vh(r,e){var t,n,o,a,s,i,d,l,p,f,u,m,v,x,S,M,E,k,h,w,C,T,W,R,I,N,V,ie,xe,Je,we,De,Ae,qe,Ie,J,re,Q;return[r.id,r.role,(n=(t=r.content)==null?void 0:t.length)!=null?n:0,(a=(o=r.content)==null?void 0:o.slice(-32))!=null?a:"",r.streaming?"1":"0",(s=r.variant)!=null?s:"",(d=(i=r.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=r.llmContent)==null?void 0:l.length)!=null?p:0,(u=(f=r.approval)==null?void 0:f.status)!=null?u:"",(v=(m=r.toolCall)==null?void 0:m.status)!=null?v:"",(S=(x=r.toolCall)==null?void 0:x.name)!=null?S:"",(k=(E=(M=r.toolCall)==null?void 0:M.chunks)==null?void 0:E.length)!=null?k:0,(T=(C=(w=(h=r.toolCall)==null?void 0:h.chunks)==null?void 0:w[r.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?T:"",typeof((W=r.toolCall)==null?void 0:W.args)=="string"?r.toolCall.args.length:(R=r.toolCall)!=null&&R.args?JSON.stringify(r.toolCall.args).length:0,(V=(N=(I=r.reasoning)==null?void 0:I.chunks)==null?void 0:N.length)!=null?V:0,(we=(Je=(xe=(ie=r.reasoning)==null?void 0:ie.chunks)==null?void 0:xe[r.reasoning.chunks.length-1])==null?void 0:Je.length)!=null?we:0,(Ie=(qe=(Ae=(De=r.reasoning)==null?void 0:De.chunks)==null?void 0:Ae[r.reasoning.chunks.length-1])==null?void 0:qe.slice(-32))!=null?Ie:"",(re=(J=r.contentParts)==null?void 0:J.length)!=null?re:0,(Q=r.stopReason)!=null?Q:"",e].join("\0")}function jh(){return new Map}function Gh(r,e,t){let n=r.get(e);return n&&n.fingerprint===t?n.wrapper:null}function Kh(r,e,t,n){r.set(e,{fingerprint:t,wrapper:n})}function Xh(r,e){for(let t of r.keys())e.has(t)||r.delete(t)}function xl(r=!0){let e=r;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function xo(r){return Math.max(0,r.scrollHeight-r.clientHeight)}function ma(r,e){return xo(r)-r.scrollTop<=e}function bl(r){let{following:e,currentScrollTop:t,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=r,p=t-n;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:t}:!e&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function yl(r){let{following:e,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=r;return e&&t<0?"pause":!e&&o&&t>0&&n?"resume":"none"}function Qh(r,e){return!r||r.isCollapsed?!1:e.contains(r.anchorNode)||e.contains(r.focusNode)}function Jh(r){let e=Math.max(0,r.anchorOffsetTop-r.topOffset),t=Math.max(0,e+r.viewportHeight-r.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Yh(r){let e=Math.max(0,r.currentContentHeight-r.contentHeightAtAnchor);return Math.max(0,r.initialSpacerHeight-e)}var jr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Gr=1e5,Fo=Gr+1;var zs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},H0=["pre","code","a","script","style"],vl=r=>{var e,t,n,o,a;return{type:(e=r==null?void 0:r.type)!=null?e:zs.type,placeholder:(t=r==null?void 0:r.placeholder)!=null?t:zs.placeholder,speed:(n=r==null?void 0:r.speed)!=null?n:zs.speed,duration:(o=r==null?void 0:r.duration)!=null?o:zs.duration,buffer:(a=r==null?void 0:r.buffer)!=null?a:zs.buffer}},ex=[{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 r of ex)$s.set(r.name,r);var ga=r=>{$s.set(r.name,r)},Pp=r=>{ex.some(e=>e.name===r)||$s.delete(r)},Rp=()=>Array.from($s.keys()),Vs=(r,e)=>{var t,n;return r==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,r)?(t=e[r])!=null?t:null:(n=$s.get(r))!=null?n:null},Cl=(r,e,t,n,o)=>{if(!o)return r;if(t!=null&&t.bufferContent)return t.bufferContent(r,n);if(!r)return r;if(e==="word"){let a=r.search(/\s(?=\S*$)/);return a<0?"":r.slice(0,a)}if(e==="line"){let a=r.lastIndexOf(`
62
+ `);return a<0?"":r.slice(0,a)}return r},B0=(r,e,t,n)=>{let o=r.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=e,o},D0=(r,e,t,n)=>{let o=r.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=e,o},Ep=/\s/,F0=(r,e)=>{let t=r.parentNode;for(;t;){if(t.nodeType===1){let n=t;if(e.has(n.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},N0=(r,e,t)=>{var d;let n=r.ownerDocument,o=r.parentNode;if(!n||!o)return;let a=(d=r.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(Ep.test(a[i])){let l=i;for(;l<a.length&&Ep.test(a[l]);)l+=1;s.appendChild(n.createTextNode(a.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<a.length&&!Ep.test(a[p]);)l.appendChild(B0(n,a[p],e,t.value)),t.value+=1,p+=1;s.appendChild(l),i=p}o.replaceChild(s,r)},O0=(r,e,t)=>{var d;let n=r.ownerDocument,o=r.parentNode;if(!n||!o)return;let a=(d=r.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(n.createTextNode(l)):(s.appendChild(D0(n,l,e,t.value)),t.value+=1));o.replaceChild(s,r)},js=(r,e,t,n)=>{var f,u;if(!r||typeof document=="undefined")return r;let o=document.createElement("div");o.innerHTML=r;let a=new Set(((f=n==null?void 0:n.skipTags)!=null?f:H0).map(m=>m.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=s.nextNode();for(;d;)F0(d,a)||i.push(d),d=s.nextNode();let l={value:(u=n==null?void 0:n.startIndex)!=null?u:0},p=e==="char"?N0:O0;for(let m of i)p(m,t,l);return o.innerHTML},wl=(r=document)=>{let e=r.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Gs=(r=document)=>{let e=r.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=r.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Zh=new WeakMap,_0=(r,e)=>{var a;if(!r.styles)return;let t=Zh.get(e);if(t||(t=new Set,Zh.set(e,t)),t.has(r.name)){let s=r.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;t.delete(r.name)}t.add(r.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(a=e.ownerDocument)!=null?a:document).createElement("style");o.setAttribute("data-persona-animation",r.name),o.textContent=r.styles,e.appendChild(o)},Lp=new WeakMap,U0=(r,e)=>{if(!r.onAttach)return;let t=Lp.get(e);if(t||(t=new Map,Lp.set(e,t)),t.has(r.name))return;let n=r.onAttach(e);t.set(r.name,n)},tx=r=>{let e=Lp.get(r);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Ip=(r,e)=>{_0(r,e),U0(r,e)};function Wp(r,e=Gr){let t=r.style.position,n=r.style.zIndex,o=r.style.isolation,a=getComputedStyle(r),s=a.position==="static"||a.position==="";return s&&(r.style.position="relative"),r.style.zIndex=String(e),r.style.isolation="isolate",()=>{s&&(r.style.position=t),r.style.zIndex=n,r.style.isolation=o}}var Ks=0,No=null;function Hp(r=document){var t;if(Ks++,Ks===1){let n=r.body,a=((t=r.defaultView)!=null?t:window).scrollY||r.documentElement.scrollTop;No={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:a},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${a}px`,n.style.width="100%"}let e=!1;return()=>{var n;if(!e&&(e=!0,Ks=Math.max(0,Ks-1),Ks===0&&No)){let o=r.body,a=(n=r.defaultView)!=null?n:window;o.style.overflow=No.originalOverflow,o.style.position=No.originalPosition,o.style.top=No.originalTop,o.style.width=No.originalWidth,a.scrollTo(0,No.scrollY),No=null}}}var Al={side:"right",width:"420px",animate:!0,reveal:"resize"},Rr=r=>{var e,t;return((t=(e=r==null?void 0:r.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},Oo=r=>{var e,t;return((t=(e=r==null?void 0:r.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},Hn=r=>{var t,n,o,a,s;let e=(t=r==null?void 0:r.launcher)==null?void 0:t.dock;return{side:(n=e==null?void 0:e.side)!=null?n:Al.side,width:(o=e==null?void 0:e.width)!=null?o:Al.width,animate:(a=e==null?void 0:e.animate)!=null?a:Al.animate,reveal:(s=e==null?void 0:e.reveal)!=null?s:Al.reveal}};var Vn={"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 Xs=(r,e)=>{let t=y("button");t.type="button",t.innerHTML=`
66
63
  <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
64
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
68
65
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -70,14 +67,14 @@ _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
70
67
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
71
68
  </span>
72
69
  <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 T,h,C,w,E,W,P,R,N,j,oe,ve,nt;let a=(T=s.launcher)!=null?T:{},i=kr(s),d=r.querySelector("[data-role='launcher-title']");if(d){let Te=(h=a.title)!=null?h:"Chat Assistant";d.textContent=Te,d.setAttribute("title",Te)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let Te=(C=a.subtitle)!=null?C:"Get answers fast";l.textContent=Te,l.setAttribute("title",Te)}let p=r.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Te=(w=a.agentIconSize)!=null?w:"40px";if(u.style.height=Te,u.style.width=Te,u.innerHTML="",a.agentIconName){let $e=parseFloat(Te)||24,Se=Be(a.agentIconName,$e*.6,"var(--persona-text-inverse, #ffffff)",2);Se?(u.appendChild(Se),u.style.display=""):(u.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",u.style.display="")}let f=r.querySelector("[data-role='launcher-image']");if(f){let Te=(P=a.agentIconSize)!=null?P:"40px";f.style.height=Te,f.style.width=Te,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Te=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=Te,m.style.width=Te,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let $e=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,$e=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Se=parseFloat(Te)||24,Xe=Math.max(Se-$e,8),He=Be(a.callToActionIconName,Xe,"currentColor",2);He?m.appendChild(He):m.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}let y=a.position&&Gn[a.position]?Gn[a.position]:Gn["bottom-right"],x="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:`${x} ${y}`,i||(r.style.zIndex=String((oe=a.zIndex)!=null?oe:Kr));let M="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(ve=a.border)!=null?ve:M,r.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow: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=(nt=a.collapsedMaxWidth)!=null?nt:"",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 Vw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Il=(t,e={})=>{var x,S,M,k,T,h;let{showClose:r=!0,wrapperClassName:n=Vw,buttonSize:o,iconSize:s="28px"}=e,a=(x=t==null?void 0:t.launcher)!=null?x:{},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",u=(k=a.closeButtonShowTooltip)!=null?k:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let f=(T=a.closeButtonIconName)!=null?T:"x",m=(h=a.closeButtonIconText)!=null?h:"\xD7";l.style.color=a.closeButtonColor||rn.actionIconColor;let y=Be(f,s,"currentColor",1);if(y?(y.style.display="block",l.appendChild(y)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let C=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${C} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&p){let C=null,w=()=>{if(C)return;let W=l.ownerDocument,P=W.body;if(!P)return;C=ro(W,"div","persona-clear-chat-tooltip"),C.textContent=p;let R=ro(W,"div");R.className="persona-clear-chat-tooltip-arrow",C.appendChild(R);let N=l.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Oo),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",P.appendChild(C)},E=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",E),l.addEventListener("focus",w),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",w),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},jw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rl=(t,e={})=>{var C,w,E,W,P,R,N,j,oe,ve,nt,Te,$e;let{wrapperClassName:r=jw,buttonSize:n,iconSize:o="20px"}=e,a=(w=((C=t==null?void 0:t.launcher)!=null?C:{}).clearChat)!=null?w:{},i=(E=n!=null?n:a.size)!=null?E:"32px",d=(W=a.iconName)!=null?W:"refresh-cw",l=(P=a.iconColor)!=null?P:"",p=(R=a.backgroundColor)!=null?R:"",u=(N=a.borderWidth)!=null?N:"",f=(j=a.borderColor)!=null?j:"",m=(oe=a.borderRadius)!=null?oe:"",y=(ve=a.paddingX)!=null?ve:"",x=(nt=a.paddingY)!=null?nt:"",S=(Te=a.tooltipText)!=null?Te:"Clear chat",M=($e=a.showTooltip)!=null?$e:!0,k=v("div",r),T=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");T.style.height=i,T.style.width=i,T.type="button",T.setAttribute("aria-label",S),T.style.color=l||rn.actionIconColor;let h=Be(d,o,"currentColor",1);if(h&&(h.style.display="block",T.appendChild(h)),p&&(T.style.backgroundColor=p,T.classList.remove("hover:persona-bg-gray-100")),u||f){let Se=u||"0px",Xe=f||"transparent";T.style.border=`${Se} solid ${Xe}`,T.classList.remove("persona-border-none")}if(m&&(T.style.borderRadius=m,T.classList.remove("persona-rounded-full")),y&&(T.style.paddingLeft=y,T.style.paddingRight=y),x&&(T.style.paddingTop=x,T.style.paddingBottom=x),k.appendChild(T),M&&S){let Se=null,Xe=()=>{if(Se)return;let V=T.ownerDocument,be=V.body;if(!be)return;Se=ro(V,"div","persona-clear-chat-tooltip"),Se.textContent=S;let G=ro(V,"div");G.className="persona-clear-chat-tooltip-arrow",Se.appendChild(G);let Ae=T.getBoundingClientRect();Se.style.position="fixed",Se.style.zIndex=String(Oo),Se.style.left=`${Ae.left+Ae.width/2}px`,Se.style.top=`${Ae.top-8}px`,Se.style.transform="translate(-50%, -100%)",be.appendChild(Se)},He=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};k.addEventListener("mouseenter",Xe),k.addEventListener("mouseleave",He),T.addEventListener("focus",Xe),T.addEventListener("blur",He),k._cleanupTooltip=()=>{He(),k.removeEventListener("mouseenter",Xe),k.removeEventListener("mouseleave",He),T.removeEventListener("focus",Xe),T.removeEventListener("blur",He)}}return{button:T,wrapper:k}};var rn={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))"},bo=t=>{var C,w,E,W,P,R,N,j,oe,ve,nt,Te,$e,Se,Xe,He;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=(C=e==null?void 0:e.launcher)!=null?C:{},s=(w=o.headerIconSize)!=null?w:"48px",a=(E=o.closeButtonPlacement)!=null?E:"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 V=parseFloat(s)||24,be=Be(d,V*.6,"currentColor",1);be?l.replaceChildren(be):l.textContent=(R=(P=e==null?void 0:e.launcher)==null?void 0:P.agentIconText)!=null?R:"\u{1F4AC}"}else if((N=e==null?void 0:e.launcher)!=null&&N.iconUrl){let V=v("img");V.src=e.launcher.iconUrl,V.alt="",V.className="persona-rounded-xl persona-object-cover",V.style.height=s,V.style.width=s,l.replaceChildren(V)}else l.textContent=(oe=(j=e==null?void 0:e.launcher)==null?void 0:j.agentIconText)!=null?oe:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=v("span","persona-text-base persona-font-semibold");u.style.color=rn.titleColor,u.textContent=(nt=(ve=e==null?void 0:e.launcher)==null?void 0:ve.title)!=null?nt:"Chat Assistant";let f=v("span","persona-text-xs");f.style.color=rn.subtitleColor,f.textContent=($e=(Te=e==null?void 0:e.launcher)==null?void 0:Te.subtitle)!=null?$e:"Here to help you get answers fast",p.append(u,f),i?n.append(p):n.append(l,p);let m=(Se=o.clearChat)!=null?Se:{},y=(Xe=m.enabled)!=null?Xe:!0,x=(He=m.placement)!=null?He:"inline",S=null,M=null;if(y){let be=Rl(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=be.button,M=be.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&n.appendChild(M)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&x==="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:T,wrapper:h}=Il(e,{showClose:r,wrapperClassName:k});return a!=="top-right"&&n.appendChild(h),{header:n,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:T,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:M}},ha=(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 Fo(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(Oo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.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",m.id),m.destructive&&y.setAttribute("data-destructive",""),m.icon){let S=Be(m.icon,16,"currentColor",1.5);S&&y.appendChild(S)}let x=document.createElement("span");x.textContent=m.label,y.appendChild(x),y.addEventListener("click",S=>{S.stopPropagation(),p(),r(m.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=y=>{!a.contains(y.target)&&!n.contains(y.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Wr(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=Be(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Qs(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 f=Be(e,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=v("span");if(u.textContent=r,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function hx(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 u;p.icon?u=Wr({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=v("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Wl(t){var m,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 u=Be(r,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,S;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Fo({items:n,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let S=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var jp=t=>{var n;let e=bo({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 Gw(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=Be(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=Fo({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 Gp=t=>{var k,T,h,C,w,E,W,P,R;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=Wl({label:(T=a.title)!=null?T:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=rn.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=rn.titleColor,p.textContent=(C=a.title)!=null?C:"Chat Assistant",l.appendChild(p),Gw(l,o==null?void 0:o.trailingActions,(w=o==null?void 0:o.onAction)!=null?w:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let j=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||j()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),j())})}let N=o==null?void 0:o.titleRowHover;N&&(l.style.borderRadius=(E=N.borderRadius)!=null?E:"10px",l.style.padding=(W=N.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 j,oe;l.style.backgroundColor=(j=N.background)!=null?j:"",l.style.borderColor=(oe=N.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(P=a.closeButtonSize)!=null?P:"32px",f=v("div",""),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=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=a.closeButtonColor||rn.actionIconColor;let y=(R=a.closeButtonIconName)!=null?R:"x",x=Be(y,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);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:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Bl={default:jp,minimal:Gp},Kp=t=>{var e;return(e=Bl[t])!=null?e:Bl.default},qa=(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 u=v("span"),f=v("span"),m=v("button");m.style.display="none";let y=v("div");return y.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=e==null?void 0:e.layout)!=null?a:"default",s=Kp(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 Hl=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}},Dl=t=>{var C,w,E,W,P,R,N,j,oe,ve,nt,Te;let e=(C=t==null?void 0:t.sendButton)!=null?C:{},r=(w=e.useIcon)!=null?w:!1,n=(E=e.iconText)!=null?E:"\u2191",o=e.iconName,s=(W=e.stopIconName)!=null?W:"square",a=(P=e.tooltipText)!=null?P:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(j=(N=t==null?void 0:t.copy)==null?void 0:N.sendButtonLabel)!=null?j:"Send",l=(ve=(oe=t==null?void 0:t.copy)==null?void 0:oe.stopButtonLabel)!=null?ve:"Stop",p=(nt=e.showTooltip)!=null?nt:!1,u=(Te=e.size)!=null?Te:"40px",f=e.backgroundColor,m=e.textColor,y=v("div","persona-send-button-wrapper"),x=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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let S=null,M=null;if(r){x.style.width=u,x.style.height=u,x.style.minWidth=u,x.style.minHeight=u,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let $e=parseFloat(u)||24,Se=(m==null?void 0:m.trim())||"currentColor";o?(S=Be(o,$e,Se,2),S?x.appendChild(S):x.textContent=n):x.textContent=n,M=Be(s,$e,Se,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");e.borderWidth&&(x.style.borderWidth=e.borderWidth,x.style.borderStyle="solid"),e.borderColor&&(x.style.borderColor=e.borderColor),e.paddingX?(x.style.paddingLeft=e.paddingX,x.style.paddingRight=e.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),e.paddingY?(x.style.paddingTop=e.paddingY,x.style.paddingBottom=e.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let k=null;p&&a&&(k=v("div","persona-send-button-tooltip"),k.textContent=a,y.appendChild(k)),x.setAttribute("aria-label",a),y.appendChild(x);let T="send";return{button:x,wrapper:y,setMode:$e=>{if($e===T)return;T=$e;let Se=$e==="stop"?i:a;if(x.setAttribute("aria-label",Se),k&&(k.textContent=Se),r){if(S&&M){let Xe=$e==="stop"?M:S;x.replaceChildren(Xe)}}else x.textContent=$e==="stop"?l:d}}},Ol=t=>{var k,T,h,C,w,E,W,P,R,N,j,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=((T=e.provider)==null?void 0:T.type)==="runtype";if(!(n||o))return null;let a=(C=(h=t==null?void 0:t.sendButton)==null?void 0:h.size)!=null?C:"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=(w=e.iconName)!=null?w:"mic",p=(E=e.iconSize)!=null?E:a,u=parseFloat(p)||24,f=(P=e.backgroundColor)!=null?P:(W=t==null?void 0:t.sendButton)==null?void 0:W.backgroundColor,m=(N=e.iconColor)!=null?N:(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",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Be(l,u,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),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=(j=e.tooltipText)!=null?j:"Start voice recognition";if(((oe=e.showTooltip)!=null?oe:!1)&&S){let ve=v("div","persona-send-button-tooltip");ve.textContent=S,i.appendChild(ve)}return{button:d,wrapper:i}},Nl=t=>{var y,x,S,M,k,T,h,C;let e=(y=t==null?void 0:t.attachments)!=null?y:{};if(e.enabled!==!0)return null;let r=(S=(x=t==null?void 0:t.sendButton)==null?void 0:x.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:yo).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",(T=e.buttonTooltipText)!=null?T:"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 u=Be(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),o.click()}),s.appendChild(a);let f=(C=e.buttonTooltipText)!=null?C:"Attach file",m=v("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:o,previewsContainer:n}},_l=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},Fl=()=>v("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var za=t=>{var y,x,S,M,k,T;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=Fl(),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}=Hl(e);a();let i=Dl(e),d=Ol(e),l=Nl(e),p=_l(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=v("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(f,m),o.append(u),o.addEventListener("click",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:(x=d==null?void 0:d.wrapper)!=null?x: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:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var xx=()=>{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=Be("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=Be("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,n,o),{root:t,textNode:n}},yx=t=>{var y,x,S,M,k,T;let{config:e}=t,r=v("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=Fl();n.style.display="none";let o=_l(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Hl(e);s.style.maxHeight="100px",a();let i=Dl(e),d=Ol(e),l=Nl(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 u=v("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let f=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.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(u,s,f),l&&r.append(l.previewsContainer),r.append(p,n,o);let m=p;return{footer:r,suggestions:n,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x: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:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var bx=t=>{var p,u,f,m,y,x,S,M,k,T,h,C,w,E,W,P,R;let e=(u=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)!=null?u:!0,r=kr(t);if(_o(t)){let N=(m=(f=t==null?void 0:t.launcher)==null?void 0:f.composerBar)!=null?m:{},j=v("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(y=N.expandedSize)!=null?y:"anchored",j.style.zIndex=String((S=(x=t==null?void 0:t.launcher)==null?void 0:x.zIndex)!=null?S:Kr);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%",j.appendChild(oe);let ve=v("div","persona-widget-pill-root");return ve.setAttribute("data-persona-composer-bar",""),ve.dataset.state="collapsed",ve.dataset.expandedSize=(M=N.expandedSize)!=null?M:"anchored",ve.style.zIndex=String((T=(k=t==null?void 0:t.launcher)==null?void 0:k.zIndex)!=null?T:Kr),{wrapper:j,panel:oe,pillRoot:ve}}if(r){let N=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(j),{wrapper:N,panel:j}}if(!e){let N=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(C=(h=t==null?void 0:t.launcher)==null?void 0:h.width)!=null?C:"100%";return N.style.width=oe,j.style.width="100%",N.appendChild(j),{wrapper:N,panel:j}}let o=(w=t==null?void 0:t.launcher)!=null?w:{},s=o.position&&Gn[o.position]?Gn[o.position]:Gn["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((W=(E=t==null?void 0:t.launcher)==null?void 0:E.zIndex)!=null?W:Kr);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:wn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Kw=(t,e)=>{var h,C,w,E,W,P,R,N,j;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}=Il(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=(w=(C=(h=t==null?void 0:t.launcher)==null?void 0:h.clearChat)==null?void 0:C.enabled)!=null?w:!0,a=null,i=null;if(s){let oe=Rl(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 u=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(W=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeTitle)!=null?W:"Hello \u{1F44B}";let f=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.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(u,f);let m=v("div","persona-flex persona-flex-col persona-gap-3"),y=(N=t==null?void 0:t.layout)==null?void 0:N.contentMaxWidth;y&&(m.style.maxWidth=y,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((j=t==null?void 0:t.copy)==null?void 0:j.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,m);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=yx({config:t}),{root:k,textNode:T}=xx();return r.append(d,o,l,S),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,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:u,introSubtitle:f,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:T}},wx=(t,e=!0)=>{var S,M,k,T,h,C,w,E,W;if(_o(t))return Kw(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?qa(t,n,{showClose:e}):bo({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=kr(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=(T=(k=t==null?void 0:t.copy)==null?void 0:k.welcomeTitle)!=null?T:"Hello \u{1F44B}";let l=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(C=(h=t==null?void 0:t.copy)==null?void 0:h.welcomeSubtitle)!=null?C:"Ask anything about your account or products.",i.append(d,l);let p=v("div","persona-flex persona-flex-col persona-gap-3"),u=(w=t==null?void 0:t.layout)==null?void 0:w.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((E=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 m=za({config:t}),y=((W=t==null?void 0:t.layout)==null?void 0:W.showFooter)!==!1;o?ha(r,s,t):(s.header.style.display="none",ha(r,s,t)),r.append(a);let x=v("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",y||(m.footer.style.display="none"),r.append(m.footer),r.append(x),{container:r,body:a,messagesWrapper:p,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Xw=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}},Jw=(t,e)=>{if(!t)return null;let r=Xw(t);if(r===null)return null;let n=e==null?void 0:e[t],o=n!==void 0?n:r;return o||null},Qw=(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},Yw=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Xp=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,Cx=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),ev=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),tv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),rv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),nv=(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 u;let l=v("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Jp}px`,l.style.maxHeight=`${Cx}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}),Yw(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}},ov=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(!Xp(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}},av=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(!Xp(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=`${Cx}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}},sv=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(!Xp(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}},xa=()=>{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},Qp=(t,e,r)=>{let n={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:xa};if(e){let o=e(n);if(o!==null)return o}return xa()},iv=(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},vx=(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},lv=(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},Yp=(t,e,r)=>{var m,y,x,S,M,k;let n=(m=e.showCopy)!=null?m:!0,o=(y=e.showUpvote)!=null?y:!0,s=(x=e.showDownvote)!=null?x:!0;if(!n&&!o&&!s){let T=v("div");return T.style.display="none",T.id=`actions-${t.id}`,T.setAttribute("data-actions-for",t.id),T}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],u=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${t.id}`,u.setAttribute("data-actions-for",t.id);let f=(T,h,C)=>{let w=Wr({icon:T,label:h,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",C),w};return n&&u.appendChild(f("copy","Copy message","copy")),o&&u.appendChild(f("thumbs-up","Upvote","upvote")),s&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Va=(t,e,r,n,o,s)=>{var V,be,G,Ae,J,ie,Me,Ge,ce,re,le,gt,ke,ye,tt,Ue,he;let a=r!=null?r:{},i=(V=a.layout)!=null?V:"bubble",d=a.avatar,l=a.timestamp,p=(be=d==null?void 0:d.show)!=null?be:!1,u=(G=l==null?void 0:l.show)!=null?G:!1,f=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=(J=l==null?void 0:l.position)!=null?J:"below",y=lv(t.role,i),x=v("div",y.join(" "));x.id=`bubble-${t.id}`,x.setAttribute("data-message-id",t.id),x.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Zw(t),M=(Me=(ie=t.content)==null?void 0:ie.trim())!=null?Me:"",T=S.length>0&&M===tl,h=kl((ce=(Ge=s==null?void 0:s.widgetConfig)==null?void 0:Ge.features)==null?void 0:ce.streamAnimation),C=(gt=(le=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:le.streamAnimation)==null?void 0:gt.plugins,w=t.role==="assistant"&&h.type!=="none"?js(h.type,C):null,E=t.role==="assistant"&&((ke=w==null?void 0:w.isAnimating)==null?void 0:ke.call(w,t))===!0,W=t.role==="assistant"&&w!==null&&(!!t.streaming||E);W&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),W&&w&&(w.containerClass&&P.classList.add(w.containerClass),P.style.setProperty("--persona-stream-step",`${h.speed}ms`),P.style.setProperty("--persona-stream-duration",`${h.duration}ms`));let R=W?El((ye=t.content)!=null?ye:"",h.buffer,w,t,!!t.streaming):(tt=t.content)!=null?tt:"",N=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),j=N;W&&(w==null?void 0:w.wrap)==="char"?j=Gs(N,"char",t.id,{skipTags:w.skipTags}):W&&(w==null?void 0:w.wrap)==="word"&&(j=Gs(N,"word",t.id,{skipTags:w.skipTags}));let oe=null;if(T?(oe=document.createElement("div"),oe.innerHTML=j,oe.style.display="none",P.appendChild(oe)):P.innerHTML=j,W&&(w!=null&&w.useCaret)&&!T&&M){let Q=Ll(),Ve=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),ee=Ve[Ve.length-1];if(ee!=null&&ee.parentNode)ee.parentNode.insertBefore(Q,ee.nextSibling);else{let xe=P.lastElementChild;xe?xe.appendChild(Q):P.appendChild(Q)}}if(u&&m==="inline"&&t.createdAt){let Q=vx(t,l);Q.classList.add("persona-ml-2","persona-inline"),P.appendChild(Q)}if(S.length>0){let Q=nv(S,!T&&!!M,()=>{T&&oe&&(oe.style.display="")});Q?x.appendChild(Q):T&&oe&&(oe.style.display="")}let ve=ev(t);if(ve.length>0){let Q=ov(ve);Q&&x.appendChild(Q)}let nt=tv(t);if(nt.length>0){let Q=av(nt);Q&&x.appendChild(Q)}let Te=rv(t);if(Te.length>0){let Q=sv(Te);Q&&x.appendChild(Q)}if(x.appendChild(P),u&&m==="below"&&t.createdAt){let Q=vx(t,l);Q.classList.add("persona-mt-1"),x.appendChild(Q)}let $e=t.role==="assistant"?Jw(t.stopReason,(he=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.copy)==null?void 0:he.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Q=!!(R&&R.trim()),Ve=h.placeholder==="skeleton",ee=Ve&&h.buffer==="line"&&Q;if(Q)ee&&x.appendChild(Ks());else if(Ve)x.appendChild(Ks());else{let xe=Qp("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);xe&&x.appendChild(xe)}}if($e&&t.stopReason&&!t.streaming&&(M||(P.style.display="none"),x.appendChild(Qw(t.stopReason,$e))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let Q=Yp(t,n,o);x.appendChild(Q)}if(!p||t.role==="system")return x;let Xe=v("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),He=iv(d,t.role);return f==="right"||f==="left"&&t.role==="user"?Xe.append(x,He):Xe.append(He,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Xe},Ax=(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}):Va(t,e,r,n,o,s)};var ja=new Set,dv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),cv=(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
- `):""},Sx=(t,e)=>{let r=ja.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=Be(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")},Zp=(t,e)=>{var nt,Te,$e,Se,Xe,He,V,be,G,Ae,J;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=(Te=(nt=e==null?void 0:e.features)==null?void 0:nt.reasoningDisplay)!=null?Te:{},s=o.expandable!==!1,a=s&&ja.has(t.id),i=r.status!=="complete",d=cv(t,($e=o.previewMaxLines)!=null?$e: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"),u=v("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(Se=e==null?void 0:e.reasoning)!=null?Se:{},y=String((Xe=r.startedAt)!=null?Xe:Date.now()),x=()=>{let ie=v("span","");return ie.setAttribute("data-tool-elapsed",y),ie.textContent=Gi(r),ie},S=(He=m.renderCollapsedSummary)==null?void 0:He.call(m,{message:t,reasoning:r,defaultSummary:f,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Gi(r),createElapsedElement:x});typeof S=="string"&&S.trim()?(u.textContent=S,p.appendChild(u)):S instanceof HTMLElement?p.appendChild(S):(u.textContent=f,p.appendChild(u));let M=v("span","persona-text-xs persona-text-persona-primary");M.textContent=Oh(r),p.appendChild(M);let k=(V=o.loadingAnimation)!=null?V:"none",T=m.activeTextTemplate,h=m.completeTextTemplate,C=i?T:h,w=S instanceof HTMLElement,E=(ie,Me,Ge)=>{let ce=Ge;for(let re of Me){let le=v("span","persona-tool-char");le.style.setProperty("--char-index",String(ce)),le.textContent=re===" "?"\xA0":re,ie.appendChild(le),ce++}return ce},W=(ie,Me)=>{u.textContent="";let Ge=Ki(ie,""),ce=0;for(let re of Ge){let le=re.styles.length>0?(()=>{let gt=v("span",re.styles.map(ke=>`persona-tool-text-${ke}`).join(" "));return u.appendChild(gt),gt})():u;if(re.isDuration&&i)le.appendChild(x());else{let gt=re.isDuration?Gi(r):re.text;Me?ce=E(le,gt,ce):le.appendChild(document.createTextNode(gt))}}};if(!w&&C)if(M.style.display="none",u.style.display="",i&&k!=="none"){let ie=(be=m.loadingAnimationDuration)!=null?be:2e3;u.setAttribute("data-preserve-animation","true"),k==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),W(C,!1)):(u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),k==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),W(C,!0))}else W(C,!1);else if(!w&&i&&k!=="none"){u.style.display="";let ie=(G=m.loadingAnimationDuration)!=null?G:2e3;if(u.setAttribute("data-preserve-animation","true"),k==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ie}ms`);else{u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),k==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Me=u.textContent||f;u.textContent="",E(u,Me,0)}r.status==="complete"&&(u.style.display="none")}else w||(r.status==="complete"?u.style.display="none":u.style.display="");let P=null;if(s){P=v("div","persona-flex persona-items-center");let Me=Be(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?P.appendChild(Me):P.textContent=a?"Hide":"Show";let Ge=v("div","persona-flex persona-items-center persona-ml-auto");Ge.append(P),l.append(p,Ge)}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 ie=(J=(Ae=e==null?void 0:e.reasoning)==null?void 0:Ae.renderCollapsedPreview)==null?void 0:J.call(Ae,{message:t,reasoning:r,defaultPreview:d,isActive:i,config:e!=null?e:{}});dv(R,ie)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!s)return n.append(l,R),n;let N=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=a?"":"none";let j=r.chunks.join(""),oe=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=j||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),P){P.innerHTML="";let Me=Be(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?P.appendChild(Me):P.textContent=a?"Hide":"Show"}N.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),n.append(l,R,N),n};var Ga=new Set,pv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),uv=(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=Oa(r.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
76
- `):""},fv=(t,e)=>{var p,u,f,m,y;let r=t.toolCall,n=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(u=n==null?void 0:n.collapsedMode)!=null?u:"tool-call",s=uv(t,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=r?Nh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},l=a;return o==="tool-name"?l=((y=r.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Od(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Od(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Tx=(t,e,r)=>{var p;let n=Ga.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 u=o.toggleTextColor||o.headerTextColor||"currentColor",f=Be(n?"chevron-up":"chevron-down",16,u,2);f?l.appendChild(f):l.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},eu=(t,e)=>{var j,oe,ve,nt,Te,$e,Se,Xe,He;let r=t.toolCall,n=(j=e==null?void 0:e.toolCall)!=null?j:{},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),o.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return o;let s=(ve=(oe=e==null?void 0:e.features)==null?void 0:oe.toolCallDisplay)!=null?ve:{},a=s.expandable!==!1,i=a&&Ga.has(t.id),{summary:d,previewText:l,isActive:p}=fv(t,e),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(u.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(u.style.paddingLeft=n.headerPaddingX,u.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(u.style.paddingTop=n.headerPaddingY,u.style.paddingBottom=n.headerPaddingY);let f=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let y=String((nt=r.startedAt)!=null?nt:Date.now()),x=()=>{let V=v("span","");return V.setAttribute("data-tool-elapsed",y),V.textContent=Hs(r),V},S=($e=n.renderCollapsedSummary)==null?void 0:$e.call(n,{message:t,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(Te=s.collapsedMode)!=null?Te:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Hs(r),createElapsedElement:x});typeof S=="string"&&S.trim()?(m.textContent=S,f.appendChild(m)):S instanceof HTMLElement?f.appendChild(S):(m.textContent=d,f.appendChild(m));let M=(Se=s.loadingAnimation)!=null?Se:"none",k=n.activeTextTemplate,T=n.completeTextTemplate,h=p?k:T,C=S instanceof HTMLElement,w=(V,be,G)=>{let Ae=G;for(let J of be){let ie=v("span","persona-tool-char");ie.style.setProperty("--char-index",String(Ae)),ie.textContent=J===" "?"\xA0":J,V.appendChild(ie),Ae++}return Ae},E=(V,be)=>{var ie;m.textContent="";let G=((ie=r.name)==null?void 0:ie.trim())||"tool",Ae=Ki(V,G),J=0;for(let Me of Ae){let Ge=Me.styles.length>0?(()=>{let ce=v("span",Me.styles.map(re=>`persona-tool-text-${re}`).join(" "));return m.appendChild(ce),ce})():m;if(Me.isDuration&&p)Ge.appendChild(x());else{let ce=Me.isDuration?Hs(r):Me.text;be?J=w(Ge,ce,J):Ge.appendChild(document.createTextNode(ce))}}};if(!C)if(p&&M!=="none"){let V=(Xe=n.loadingAnimationDuration)!=null?Xe:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${V}ms`),h&&E(h,!1);else if(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${V}ms`),M==="shimmer-color"&&(n.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),h)E(h,!0);else{let be=m.textContent||d;m.textContent="",w(m,be,0)}}else h&&E(h,!1);let W=null;if(a){W=v("div","persona-flex persona-items-center");let V=n.toggleTextColor||n.headerTextColor||"currentColor",be=Be(i?"chevron-up":"chevron-down",16,V,2);be?W.appendChild(be):W.textContent=i?"Hide":"Show";let G=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");G.append(W),u.append(f,G)}else u.append(f);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 V=(He=n.renderCollapsedPreview)==null?void 0:He.call(n,{message:t,toolCall:r,defaultPreview:l,isActive:p,config:e!=null?e:{}});pv(P,V)||(P.textContent=l),P.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,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 V=v("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?V.style.color=n.contentTextColor:n.headerTextColor&&(V.style.color=n.headerTextColor),V.textContent=r.name,R.appendChild(V)}if(r.args!==void 0){let V=v("div","persona-space-y-1"),be=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(be.style.color=n.labelTextColor),be.textContent="Arguments";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(G.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(G.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(G.style.color=n.codeBlockTextColor),G.textContent=Oa(r.args),V.append(be,G),R.appendChild(V)}if(r.chunks&&r.chunks.length){let V=v("div","persona-space-y-1"),be=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(be.style.color=n.labelTextColor),be.textContent="Activity";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(G.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(G.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(G.style.color=n.codeBlockTextColor),G.textContent=r.chunks.join(""),V.append(be,G),R.appendChild(V)}if(r.status==="complete"&&r.result!==void 0){let V=v("div","persona-space-y-1"),be=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(be.style.color=n.labelTextColor),be.textContent="Result";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(G.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(G.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(G.style.color=n.codeBlockTextColor),G.textContent=Oa(r.result),V.append(be,G),R.appendChild(V)}if(r.status==="complete"&&typeof r.duration=="number"){let V=v("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(V.style.color=n.contentTextColor),V.textContent=`Duration: ${r.duration}ms`,R.appendChild(V)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let V=n.toggleTextColor||n.headerTextColor||"currentColor",be=Be(i?"chevron-up":"chevron-down",16,V,2);be?W.appendChild(be):W.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",P.style.display=i?"none":P.textContent||P.childNodes.length?"":"none"})(),o.append(u,P,R),o};var $o=ld(zi(),1);var ru="ask_user_question",tu=8,Ka="data-persona-ask-sheet-for",mv="Other",gv="Other\u2026",kx="Type your own answer here",Ex="Send",hv="Next",xv="Back",yv="Submit all",bv="Skip",wv=3,nu="data-ask-current-index",ou="data-ask-question-count",Lx="data-ask-answers",au="data-ask-grouped",Px="data-ask-layout",vv=t=>t.layout==="pills"?"pills":"rows",Cv=t=>t.getAttribute(Px)==="pills"?"pills":"rows",Mx=!1,Ix=t=>t.replace(/["\\]/g,"\\$&"),wo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===ru,$l=t=>{var e,r;return(r=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?r:{}},vo=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,$o.parse)(o,$o.STR|$o.OBJ|$o.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},Ys=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>tu&&!Mx&&(Mx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${tu}.`)),e.slice(0,tu)},Av=t=>{var e;return(e=Ys(t)[0])!=null?e:null},Sv=(t,e)=>{var r;return(r=Ys(t)[e])!=null?r:null},Rx=(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))},Wx=(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},Tv=(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=Wx(r,n,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Mv=t=>{let r=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},kv=(t,e,r,n)=>{var p,u,f;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(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!r){for(let m=0;m<wv;m++)s.appendChild(Mv(n));return s}if(d.forEach((m,y)=>{s.appendChild(Tv(m,y,n,a))}),(t==null?void 0:t.allowFreeText)!==!1){let m=n==="rows"?mv:gv;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 x=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:kx,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(u=e.freeTextLabel)!=null?u:m),x.appendChild(S),y.appendChild(x);let M=Wx(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=(f=e.freeTextLabel)!=null?f:m,s.appendChild(y)}}return s},Bx=(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:kx,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:Ex,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},Ev=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:Ex,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,e.appendChild(r),e},Lv=(t,e,r)=>{var l,p,u,f;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:xv,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:bv,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?(u=r.submitAllLabel)!=null?u:yv:(f=r.nextLabel)!=null?f:hv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},ya=t=>{let e=t.getAttribute(Lx);if(!e)return{};try{let r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}},Hx=(t,e)=>{t.setAttribute(Lx,JSON.stringify(e))},Bn=t=>{var r;let e=Number((r=t.getAttribute(nu))!=null?r:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Pv=(t,e)=>{t.setAttribute(nu,String(Math.max(0,Math.floor(e))))},Xa=t=>{var r;let e=Number((r=t.getAttribute(ou))!=null?r:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Uo=t=>t.getAttribute(au)==="true",Iv=(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},Rv=(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)))},Ul=(t,e)=>{let{payload:r}=vo(e),n=Ys(r),o=ya(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},Dx=t=>{let e=ya(t),r=Bn(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 u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=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=""},Ox=t=>{if(!Uo(t))return;let e=ya(t),r=Bn(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}},su=(t,e,r)=>{let n=$l(r),o=Cv(t),{payload:s,complete:a}=vo(e),i=Uo(t),d=Bn(t),l=Xa(t),p=i?Sv(s,d):Av(s),u=!!(p!=null&&p.multiSelect),f=t.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=t.querySelector('[data-ask-stepper="true"]');m&&m.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 x=t.querySelector('[data-ask-pill-list="true"]');if(x){let k=kv(p,n,a,o);x.replaceWith(k)}if(o!=="rows"){let k=t.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Bx(n,o))}let S=t.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?t.appendChild(Ev(n)):(!u||i)&&S&&S.remove(),t.setAttribute("data-multi-select",u?"true":"false");let M=t.querySelector('[data-ask-nav-row="true"]');if(i){let k=Lv(d,l,n);M?M.replaceWith(k):t.appendChild(k)}else M&&M.remove();Dx(t),Ox(t)},Wv=(t,e,r)=>{let n=$l(e),o=vv(n),s=t.toolCall.id,a=Ys(r),i=Math.max(1,a.length),d=i>1,l=Iv(t,a),p=d?Rv(t,i):0,u=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ka,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(ou,String(i)),u.setAttribute(nu,String(p)),u.setAttribute(au,d?"true":"false"),u.setAttribute(Px,o),Hx(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Rx(u,n);let f=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),u.appendChild(f);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"),u.appendChild(S),o!=="rows"&&u.appendChild(Bx(n,o)),su(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Bv=(t,e,r)=>{let{payload:n}=vo(e),o=Math.max(1,Ys(n).length);o>Xa(t)&&(t.setAttribute(ou,String(o)),o>1&&!Uo(t)&&t.setAttribute(au,"true")),su(t,e,r)},Nx=(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=$l(e);Rx(r,n);let o=v("span","persona-ask-stub-label"),{complete:s}=vo(t);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},Ja=(t,e,r)=>{if(!r||!wo(t)||$l(e).enabled===!1)return;let o=t.toolCall.id;r.querySelectorAll(`[${Ka}]`).forEach(l=>{l.getAttribute(Ka)!==o&&l.remove()});let a=r.querySelector(`[${Ka}="${Ix(o)}"]`);if(a){Bv(a,t,e);return}let{payload:i}=vo(t),d=Wv(t,e,i);r.appendChild(d)},qo=(t,e)=>{if(!t)return;let r=e?`[${Ka}="${Ix(e)}"]`:`[${Ka}]`;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)})},iu=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),zo=(t,e)=>{let r=ya(t),n=Bn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete r[n]:r[n]=e,Hx(t,r),Dx(t),Ox(t)},ql=(t,e,r,n)=>{let o=Xa(t),s=Math.max(0,Math.min(o-1,n));Pv(t,s),su(t,e,r)};var zl=new Map,Hv=t=>{let r=(t.startsWith(ho)?t.slice(ho.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return t;let n=r.join(" ").toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},_x=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,Fx=(t,e)=>{var n,o,s;let r=(o=(n=_x(e))==null?void 0:n.detailsDisplay)!=null?o:"collapsed";return(s=zl.get(t))!=null?s:r==="expanded"},$x=(t,e,r)=>{var a,i;let n=_x(r);t.setAttribute("aria-expanded",e?"true":"false");let o=t.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=n==null?void 0:n.hideDetailsLabel)!=null?a:"Hide details":(i=n==null?void 0:n.showDetailsLabel)!=null?i:"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Be(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Ux=(t,e,r)=>{let n=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!n||!o)return;let s=Fx(t,r);$x(n,s,r),o.style.display=s?"":"none"};var Vl=(t,e)=>{var E,W,P,R,N,j,oe,ve,nt,Te,$e,Se,Xe,He;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=(E=n==null?void 0:n.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(W=n==null?void 0:n.borderColor)!=null?W:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(n==null?void 0:n.shadow)!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!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)":(P=n==null?void 0:n.titleColor)!=null?P:"currentColor",p=Be(d,20,l,2);p&&i.appendChild(p);let u=v("div","persona-flex-1 persona-min-w-0"),f=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(R=n==null?void 0:n.title)!=null?R:"Approval Required",f.appendChild(m),!o){let V=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");V.setAttribute("data-approval-status",r.status),r.status==="approved"?(V.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",V.style.color="var(--persona-palette-colors-success-700, #15803d)",V.textContent="Approved"):r.status==="denied"?(V.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",V.style.color="var(--persona-palette-colors-error-700, #b91c1c)",V.textContent="Denied"):r.status==="timeout"&&(V.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",V.style.color="var(--persona-palette-colors-warning-700, #b45309)",V.textContent="Timeout"),f.appendChild(V)}u.appendChild(f);let x=r.toolType==="webmcp"||r.toolName.startsWith(ho)?Hd(r.toolName):void 0,S=(N=n==null?void 0:n.formatDescription)==null?void 0:N.call(n,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...x?{displayTitle:x}:{}}),M=!r.toolName,k=S||(M?r.description:`The assistant wants to use \u201C${x!=null?x:Hv(r.toolName)}\u201D.`),T=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");T.setAttribute("data-approval-summary","true"),n!=null&&n.descriptionColor&&(T.style.color=n.descriptionColor),T.textContent=k,u.appendChild(T);let h=(j=n==null?void 0:n.detailsDisplay)!=null?j:"collapsed",C=!!r.description&&!M,w=C||!!r.parameters;if(h!=="hidden"&&w){let V=Fx(t.id,e),be=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");be.type="button",be.setAttribute("data-expand-header","true"),be.setAttribute("data-bubble-type","approval"),n!=null&&n.descriptionColor&&(be.style.color=n.descriptionColor);let G=v("span");G.setAttribute("data-approval-details-label","true");let Ae=v("span","persona-inline-flex persona-items-center");Ae.setAttribute("data-approval-details-chevron","true"),be.append(G,Ae),$x(be,V,e),u.appendChild(be);let J=v("div");if(J.setAttribute("data-approval-details","true"),J.style.display=V?"":"none",C){let ie=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");n!=null&&n.descriptionColor&&(ie.style.color=n.descriptionColor),ie.textContent=r.description,J.appendChild(ie)}if(r.parameters){let ie=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&&(ie.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(ie.style.color=n.parameterTextColor),ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",ie.textContent=Oa(r.parameters),J.appendChild(ie)}u.appendChild(J)}if(o){let V=v("div","persona-flex persona-gap-2 persona-mt-2");V.setAttribute("data-approval-buttons","true");let be=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");be.type="button",be.style.backgroundColor=(oe=n==null?void 0:n.approveButtonColor)!=null?oe:"var(--persona-approval-approve-bg, #22c55e)",be.style.color=(ve=n==null?void 0:n.approveButtonTextColor)!=null?ve:"#ffffff",be.setAttribute("data-approval-action","approve");let G=Be("shield-check",14,(nt=n==null?void 0:n.approveButtonTextColor)!=null?nt:"#ffffff",2);G&&(G.style.marginRight="4px",be.appendChild(G));let Ae=document.createTextNode((Te=n==null?void 0:n.approveLabel)!=null?Te:"Approve");be.appendChild(Ae);let J=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");J.type="button",J.style.backgroundColor=($e=n==null?void 0:n.denyButtonColor)!=null?$e:"transparent",J.style.color=(Se=n==null?void 0:n.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",J.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,J.setAttribute("data-approval-action","deny");let ie=Be("shield-x",14,(Xe=n==null?void 0:n.denyButtonTextColor)!=null?Xe:"var(--persona-feedback-error, #dc2626)",2);ie&&(ie.style.marginRight="4px",J.appendChild(ie));let Me=document.createTextNode((He=n==null?void 0:n.denyLabel)!=null?He:"Deny");J.appendChild(Me),V.append(be,J),u.appendChild(V)}return a.append(i,u),s.appendChild(a),s};var qx=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(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=o?o.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let y=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=m,y.disabled=u,i!=null&&i.fontFamily&&(y.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(y.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(y.style.paddingLeft=i.paddingX,y.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(y.style.paddingTop=i.paddingY,y.style.paddingBottom=i.paddingY),y.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),p.appendChild(y),e.push(y)}),t.appendChild(p)}}};var Zs=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 ei=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 Dv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ov=new Set(["step_start","execution_start"]),Nv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),_v=new Set(["step_complete","agent_turn_complete"]),Fv=new Set(["flow_complete","agent_complete"]),zx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),vn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ba=(t,e)=>{let r=t[e];return jx(r)?r:void 0};function lu(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function jl(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function $v(t,e){return typeof e.type=="string"?e.type:t}function Uv(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 qv(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 Vx(t){var n,o,s,a,i;let e=ba(t,"result"),r=[ba(t,"tokens"),ba(t,"totalTokens"),e?ba(e,"tokens"):void 0,ba(t,"usage"),e?ba(e,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=vn(d.output))!=null?n:vn(d.outputTokens))!=null?o:vn(d.completionTokens);if(l!==void 0)return l}return(i=(s=vn(t.outputTokens))!=null?s:vn(t.completionTokens))!=null?i:e?(a=vn(e.outputTokens))!=null?a:vn(e.completionTokens):void 0}function zv(t){var r,n,o,s,a;let e=ba(t,"result");return(a=(o=(n=(r=vn(t.executionTime))!=null?r:vn(t.executionTimeMs))!=null?n:vn(t.execution_time))!=null?o:vn(t.duration))!=null?a:e?(s=vn(e.executionTime))!=null?s:vn(e.executionTimeMs):void 0}function Vv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ti=class{constructor(e=Vv){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:jl(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(!jx(r)){zx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=$v(e,r),o=this.now();if(Dv.has(n)){this.startRun(o);return}if(Ov.has(n)){this.run||this.startRun(o);return}if(Nv.has(n)){if(!qv(n,r))return;let a=Uv(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+lu(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:jl(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(_v.has(n)){if(!this.run)return;let a=this.run,i=Vx(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+lu(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:jl(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Fv.has(n)){if(!this.run)return;let a=this.run,i=Vx(r),d=i!=null?i:a.exactOutputTokens+lu(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:jl(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(zx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,r,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=zv(r);return s!=null?s:n-e.startedAt}};function Qa(t,e){e&&e.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var jv={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)"}},Gv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Kv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Xv=100;function Jv(t,e){let r={...jv,...e};if(r[t])return r[t];for(let n of Object.keys(r))if(n.endsWith("_")&&t.startsWith(n))return r[n];return Gv}function Qv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Yv(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 Zv(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 eC(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 tC(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 rC(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function nC(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 oC(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 du(t,e,r,n,o,s,a,i){var f;let d=o.has(t.id),l=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Qa(l,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var j,oe;let m=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 x=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=Be(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&x.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=(j=n.timestampFormat)!=null?j:"relative";M.textContent=k==="relative"?Qv(t.timestamp,r):Yv(t.timestamp);let T=null;n.showSequenceNumbers!==!1&&(T=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(e+1));let h=Jv(t.type,n.badgeColors),C=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");C.style.backgroundColor=h.bg,C.style.color=h.text,C.style.borderColor=h.text+"50",C.textContent=t.type;let w=(oe=n.descriptionFields)!=null?oe:Kv,E=Zv(t.payload,w),W=null;E&&(W=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.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"),N=Be("clipboard","12px","currentColor",1.5);return N&&R.appendChild(N),R.addEventListener("click",async ve=>{ve.stopPropagation(),await eC(tC(t)),R.innerHTML="";let nt=Be("check","12px","currentColor",1.5);nt&&R.appendChild(nt),setTimeout(()=>{R.innerHTML="";let Te=Be("clipboard","12px","currentColor",1.5);Te&&R.appendChild(Te)},1500)}),y.appendChild(x),y.appendChild(M),T&&y.appendChild(T),y.appendChild(C),W&&y.appendChild(W),y.appendChild(P),y.appendChild(R),m.appendChild(y),d&&m.appendChild(oC(t,a,i)),m}}function Gx(t){var y,x,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=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",u=(k=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?k:{},f=s.find(T=>T.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let T=f.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:n});if(T)return{element:T,update:()=>{},destroy:()=>{}}}return m();function m(){let T=u.classNames,h=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Qa(h,T==null?void 0:T.panel);let C=[],w="",E="",W=null,P=[],R={},N=0,j=Sl(),oe=0,ve=0,nt=!1,Te=null,$e=!1,Se=0,Xe=new Set,He=new Map,V="",be="",G=null,Ae,J,ie,Me,Ge,ce=null,re=null,le=null;function gt(){let de=v("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=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");Qa(we,T==null?void 0:T.headerBar);let Ot=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ot.textContent="Events",Ae=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"),Ae.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 ur=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");ur.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 Cr=re,Br=le,Ur=()=>{if(!Br.textContent)return;let sn=Cr.getBoundingClientRect(),gr=de.getBoundingClientRect();Br.style.left=`${sn.left-gr.left}px`,Br.style.top=`${sn.bottom-gr.top+4}px`,Br.style.display="block"},bt=()=>{Br.style.display="none"};re.addEventListener("mouseenter",Ur),re.addEventListener("mouseleave",bt),re.appendChild(ur),re.appendChild(ce)}let lr=v("div","persona-flex-1");J=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 It=v("option","");It.value="",It.textContent="All events",J.appendChild(It),ie=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"),ie.type="button",ie.title="Copy All";let Ut=Be("clipboard-copy","12px","currentColor",1.5);Ut&&ie.appendChild(Ut);let Nt=v("span","persona-text-xs");Nt.textContent="Copy All",ie.appendChild(Nt),we.appendChild(Ot),we.appendChild(Ae),re&&we.appendChild(re),we.appendChild(lr),we.appendChild(J),we.appendChild(ie);let Mt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Qa(Mt,T==null?void 0:T.searchBar);let Rt=Be("search","14px","var(--persona-muted, #9ca3af)",1.5),dr=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");Rt&&dr.appendChild(Rt),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"),Qa(Me,T==null?void 0:T.searchInput),Me.type="text",Me.placeholder="Search event payloads...",Ge=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"),Ge.type="button",Ge.style.display="none";let ht=Be("x","12px","currentColor",2);return ht&&Ge.appendChild(ht),Mt.appendChild(dr),Mt.appendChild(Me),Mt.appendChild(Ge),de.appendChild(we),de.appendChild(Mt),le&&de.appendChild(le),de}let ke,ye=s.find(de=>de.renderEventStreamToolbar);if(ye!=null&&ye.renderEventStreamToolbar&&o){let de=ye.renderEventStreamToolbar({config:o,defaultRenderer:()=>gt(),eventCount:e.getSize(),filteredCount:0,onFilterChange:we=>{w=we,ue(),O()},onSearchChange:we=>{E=we,ue(),O()}});ke=de!=null?de:gt()}else ke=gt();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 Ue(){if(!a||!ce||!re)return;let de=a();ce.textContent=rC(de);let we=nC(de);le&&(le.textContent=we,we||(le.style.display="none")),we?re.setAttribute("aria-label",we):re.removeAttribute("aria-label")}let he=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Q=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Q.style.height="100%";let Ve=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");Qa(Ve,T==null?void 0:T.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let ee=Be(l,"14px","currentColor",2);ee&&Ve.appendChild(ee);let xe=v("span","");xe.textContent=p,Ve.appendChild(xe);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",he.appendChild(Q),he.appendChild(z),he.appendChild(Ve),h.setAttribute("tabindex","0"),h.appendChild(ke),h.appendChild(tt),h.appendChild(he);function De(){let de=e.getAll(),we={};for(let Nt of de)we[Nt.type]=(we[Nt.type]||0)+1;let Ot=Object.keys(we).sort(),lr=Ot.length!==P.length||!Ot.every((Nt,Mt)=>Nt===P[Mt]),It=!lr&&Ot.some(Nt=>we[Nt]!==R[Nt]),hr=de.length!==Object.values(R).reduce((Nt,Mt)=>Nt+Mt,0);if(!lr&&!It&&!hr||(P=Ot,R=we,!J))return;let Ut=J.value;if(J.options[0].textContent="All events",lr){for(;J.options.length>1;)J.remove(1);for(let Nt of Ot){let Mt=v("option","");Mt.value=Nt,Mt.textContent=`${Nt} (${we[Nt]||0})`,J.appendChild(Mt)}Ut&&Ot.includes(Ut)?J.value=Ut:Ut&&(J.value="",w="")}else for(let Nt=1;Nt<J.options.length;Nt++){let Mt=J.options[Nt];Mt.textContent=`${Mt.value} (${we[Mt.value]||0})`}}function Le(){let de=e.getAll();if(w&&(de=de.filter(we=>we.type===w)),E){let we=E.toLowerCase();de=de.filter(Ot=>Ot.type.toLowerCase().includes(we)||Ot.payload.toLowerCase().includes(we))}return de}function ge(){return w!==""||E!==""}function ue(){N=0,oe=0,j.resume(),Ve.style.display="none"}function Oe(de){Xe.has(de)?Xe.delete(de):Xe.add(de),G=de;let we=Q.scrollTop,Ot=j.isFollowing();$e=!0,j.pause(),O(),Q.scrollTop=we,Ot&&j.resume(),$e=!1}function Z(){return qs(Q,50)}function O(){ve=Date.now(),nt=!1,Ue(),De();let de=e.getEvictedCount();de>0?(tt.textContent=`${de.toLocaleString()} older events truncated`,tt.style.display=""):tt.style.display="none",C=Le();let we=C.length,Ot=e.getSize()>0;Ae&&(Ae.textContent=String(e.getSize())),we===0&&Ot&&ge()?(z.textContent=E?`No events matching '${E}'`:"No events matching filter",z.style.display="",Q.style.display="none"):(z.style.display="none",Q.style.display=""),ie&&(ie.title=ge()?`Copy Filtered (${we})`:"Copy All"),d&&!j.isFollowing()&&we>N&&(oe+=we-N,xe.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",Ve.style.display=""),N=we;let lr=e.getAll(),It=lr.length>0?lr[0].timestamp:0,hr=new Set(C.map(Mt=>Mt.id));for(let Mt of Xe)hr.has(Mt)||Xe.delete(Mt);let Ut=w!==V||E!==be,Nt=He.size===0&&C.length>0;if(Ut||Nt||C.length===0){Q.innerHTML="",He.clear();let Mt=document.createDocumentFragment();for(let Rt=0;Rt<C.length;Rt++){let dr=du(C[Rt],Rt,It,u,Xe,Oe,s,o);He.set(C[Rt].id,dr),Mt.appendChild(dr)}Q.appendChild(Mt),V=w,be=E,G=null}else{if(G!==null){let Rt=He.get(G);if(Rt&&Rt.parentNode===Q){let dr=C.findIndex(ht=>ht.id===G);if(dr>=0){let ht=du(C[dr],dr,It,u,Xe,Oe,s,o);Q.insertBefore(ht,Rt),Rt.remove(),He.set(G,ht)}}G=null}let Mt=new Set(C.map(Rt=>Rt.id));for(let[Rt,dr]of He)Mt.has(Rt)||(dr.remove(),He.delete(Rt));for(let Rt=0;Rt<C.length;Rt++){let dr=C[Rt];if(!He.has(dr.id)){let ht=du(dr,Rt,It,u,Xe,Oe,s,o);He.set(dr.id,ht),Q.appendChild(ht)}}}j.isFollowing()&&(Q.scrollTop=Q.scrollHeight)}function Ie(){if(Date.now()-ve>=Xv){Te!==null&&(cancelAnimationFrame(Te),Te=null),O();return}nt||(nt=!0,Te=requestAnimationFrame(()=>{Te=null,O()}))}let Ne=(de,we)=>{if(!ie)return;ie.innerHTML="";let Ot=Be(de,"12px","currentColor",1.5);Ot&&ie.appendChild(Ot);let lr=v("span","persona-text-xs");lr.textContent="Copy All",ie.appendChild(lr),setTimeout(()=>{ie.innerHTML="";let It=Be("clipboard-copy","12px","currentColor",1.5);It&&ie.appendChild(It);let hr=v("span","persona-text-xs");hr.textContent="Copy All",ie.appendChild(hr),ie.disabled=!1},we)},je=async()=>{if(ie){ie.disabled=!0;try{let de;ge()?de=C:r?(de=await r(),de.length===0&&(de=e.getAll())):de=e.getAll();let we=de.map(Ot=>{try{return JSON.parse(Ot.payload)}catch{return Ot.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),Ne("check",1500)}catch{Ne("x",1500)}}},Ke=()=>{J&&(w=J.value,ue(),O())},xt=()=>{!Me||!Ge||(Ge.style.display=Me.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{E=Me.value,ue(),O()},150))},st=()=>{!Me||!Ge||(Me.value="",E="",Ge.style.display="none",W&&clearTimeout(W),ue(),O())},Pt=()=>{if($e)return;let de=Q.scrollTop,{action:we,nextLastScrollTop:Ot}=Tl({following:j.isFollowing(),currentScrollTop:de,lastScrollTop:Se,nearBottom:Z(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Se=Ot,we==="resume"?(j.resume(),oe=0,Ve.style.display="none"):we==="pause"&&(j.pause(),d&&(xe.textContent=p,Ve.style.display=""))},Zt=de=>{let we=Ml({following:j.isFollowing(),deltaY:de.deltaY,nearBottom:Z(),resumeWhenNearBottom:!0});we==="pause"?(j.pause(),d&&(xe.textContent=p,Ve.style.display="")):we==="resume"&&(j.resume(),oe=0,Ve.style.display="none")},X=()=>{d&&(Q.scrollTop=Q.scrollHeight,j.resume(),oe=0,Ve.style.display="none")},er=de=>{let we=de.target;if(!we||we.closest("button"))return;let Ot=we.closest("[data-event-id]");if(!Ot)return;let lr=Ot.getAttribute("data-event-id");lr&&Oe(lr)},it=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?(st(),Me.blur(),h.focus()):n&&n())};ie&&ie.addEventListener("click",je),J&&J.addEventListener("change",Ke),Me&&Me.addEventListener("input",xt),Ge&&Ge.addEventListener("click",st),Q.addEventListener("scroll",Pt),Q.addEventListener("wheel",Zt,{passive:!0}),Q.addEventListener("click",er),Ve.addEventListener("click",X),h.addEventListener("keydown",it);function Vt(){W&&clearTimeout(W),Te!==null&&(cancelAnimationFrame(Te),Te=null),nt=!1,He.clear(),ie&&ie.removeEventListener("click",je),J&&J.removeEventListener("change",Ke),Me&&Me.removeEventListener("input",xt),Ge&&Ge.removeEventListener("click",st),Q.removeEventListener("scroll",Pt),Q.removeEventListener("wheel",Zt),Q.removeEventListener("click",er),Ve.removeEventListener("click",X),h.removeEventListener("keydown",it)}return{element:h,update:Ie,destroy:Vt}}}function Kx(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 u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${r}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var Xx=(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:()=>Kx(t,e)});if(p)return p}return Kx(t,e)};var cu=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)})}},Co=new cu;Co.register("PersonaArtifactCard",Xx);function aC(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 Jx(t,e){var J,ie,Me,Ge;let r=(ie=(J=t.features)==null?void 0:J.artifacts)==null?void 0:ie.layout,o=((Me=r==null?void 0:r.toolbarPreset)!=null?Me:"default")==="document",s=(Ge=r==null?void 0:r.panePadding)==null?void 0:Ge.trim(),a=t.markdown?ia(t.markdown):null,i=Wa(t.sanitize),d=ce=>{let re=a?a(ce):la(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"),u.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};l&&l.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let m=v("span","persona-text-xs persona-font-medium persona-truncate");m.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 x="rendered",S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Wr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Wr({icon:"eye",label:"Rendered view"}),k=o?Wr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Wr({icon:"code-2",label:"Source"}),T=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),h=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,C=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,w=r==null?void 0:r.documentToolbarCopyMenuItems,E=!!(C&&w&&w.length>0),W=null,P,R=null,N=null;if(o&&(h||C)&&!E){if(P=h?Qs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),C){let ce=Be("chevron-down",14,"currentColor",2);ce&&P.appendChild(ce)}}else o&&E?(W=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),P=h?Qs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Wr({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(P,R)):o?P=Wr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):P=Wr({icon:"copy",label:"Copy"});let j=o?Wr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Wr({icon:"refresh-cw",label:"Refresh"}),oe=o?Wr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Wr({icon:"x",label:"Close"}),ve=()=>{var ke,ye,tt;let ce=(ke=He.find(Ue=>Ue.id===V))!=null?ke:He[He.length-1],re=(ye=ce==null?void 0:ce.id)!=null?ye:null,le=(ce==null?void 0:ce.artifactType)==="markdown"&&(tt=ce.markdown)!=null?tt:"",gt=ce?JSON.stringify({component:ce.component,props:ce.props},null,2):"";return{markdown:le,jsonPayload:gt,id:re}},nt=async()=>{var ke;let{markdown:ce,jsonPayload:re}=ve(),le=(ke=He.find(ye=>ye.id===V))!=null?ke:He[He.length-1],gt=(le==null?void 0:le.artifactType)==="markdown"?ce:le?re:"";try{await navigator.clipboard.writeText(gt)}catch{}};if(P.addEventListener("click",async()=>{let ce=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ce&&E){let{markdown:re,jsonPayload:le,id:gt}=ve();try{await ce({actionId:"primary",artifactId:gt,markdown:re,jsonPayload:le})}catch{}return}await nt()}),R&&(w!=null&&w.length)){let ce=()=>{var le;return(le=u.closest("[data-persona-root]"))!=null?le:document.body},re=()=>{N=Fo({items:w.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:gt,jsonPayload:ke,id:ye}=ve(),tt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{tt?await tt({actionId:le,artifactId:ye,markdown:gt,jsonPayload:ke}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(gt):le==="json"||le==="source"?await navigator.clipboard.writeText(ke):await navigator.clipboard.writeText(gt||ke)}catch{}},anchor:W!=null?W:R,position:"bottom-right",portal:ce()})};u.isConnected?re():requestAnimationFrame(re),R.addEventListener("click",le=>{le.stopPropagation(),N==null||N.toggle()})}j.addEventListener("click",async()=>{var ce;try{await((ce=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ce.call(r))}catch{}G()}),oe.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let Te=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),k.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",Te(),G()}),k.addEventListener("click",()=>{x="source",Te(),G()});let $e=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?(f.replaceChildren(),S.append(M,k),W?T.append(W,j,oe):T.append(P,j,oe),f.append(S,$e,T),Te()):(f.appendChild(m),f.appendChild(y)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Se=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"),Xe=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Se.style.paddingLeft=s,Se.style.paddingRight=s,Xe.style.padding=s),u.appendChild(f),u.appendChild(Se),u.appendChild(Xe);let He=[],V=null,be=!1,G=()=>{var gt,ke,ye,tt;let ce=o&&He.length<=1;Se.classList.toggle("persona-hidden",ce),Se.replaceChildren();for(let Ue of He){let he=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");he.type="button",he.textContent=Ue.title||Ue.id.slice(0,8),Ue.id===V&&he.classList.add("persona-bg-persona-container","persona-border-persona-border"),he.addEventListener("click",()=>e.onSelect(Ue.id)),Se.appendChild(he)}Xe.replaceChildren();let re=V&&He.find(Ue=>Ue.id===V)||He[He.length-1];if(!re)return;if(o){let Ue=re.artifactType==="markdown"?"MD":(gt=re.component)!=null?gt:"Component",Q=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";$e.textContent=`${Q} \xB7 ${Ue}`}else m.textContent="Artifacts";if(re.artifactType==="markdown"){if(o&&x==="source"){let he=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");he.textContent=(ke=re.markdown)!=null?ke:"",Xe.appendChild(he);return}let Ue=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ue.innerHTML=d((ye=re.markdown)!=null?ye:""),Xe.appendChild(Ue);return}let le=re.component?Co.get(re.component):void 0;if(le){let he={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let Q=le((tt=re.props)!=null?tt:{},he);if(Q){Xe.appendChild(Q);return}}catch{}}Xe.appendChild(aC(re))},Ae=()=>{var re;let ce=He.length>0;if(u.classList.toggle("persona-hidden",!ce),l){let le=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,ke=((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&&ke&&be?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(ce){var re,le,gt;He=ce.artifacts,V=(gt=(le=ce.selectedId)!=null?le:(re=ce.artifacts[ce.artifacts.length-1])==null?void 0:re.id)!=null?gt:null,He.length>0&&(be=!0),G(),Ae()},setMobileOpen(ce){be=ce,!ce&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):Ae()}}}function Hn(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 Qx(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"),!Hn(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 sC(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 Gl(t,e){var d,l,p,u,f,m,y,x,S,M;if(!Hn(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"),sC(t),Qx(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",(u=r==null?void 0:r.paneWidth)!=null?u:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(f=r==null?void 0:r.paneMaxWidth)!=null?f:"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=(m=r==null?void 0:r.paneBackground)==null?void 0:m.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=(x=r==null?void 0:r.documentToolbarIconColor)==null?void 0:x.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"),Qx(t,e)}var Yx=["panel","seamless"];function Kl(t,e){var i,d,l,p,u,f;for(let m of Yx)t.classList.remove(`persona-artifact-appearance-${m}`);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"),!Hn(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=Yx.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=(u=r==null?void 0:r.paneShadow)==null?void 0:u.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 m=((f=r.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;m&&t.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Zx(t,e){var r,n,o;return!e||!Hn(t)?!1:((o=(n=(r=t.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function iC(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 lC(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 dC(t,e,r){return r<e?e:Math.min(r,Math.max(e,t))}function cC(t,e,r,n){let o=t-n-2*e-r;return Math.max(0,o)}function ey(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 ty(t,e,r,n,o,s){let a=iC(o,200),i=cC(e,r,n,200);i=Math.max(a,i);let d=lC(s);return d!==null&&(i=Math.min(i,d)),dC(t,a,i)}var ry={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"}},pu=(t,e,r,n)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,x,S;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(x=ry[a])!=null?x:ry.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 w,E;let k=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${e.id}-${a}-${M.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=M.label,k.appendChild(T);let h=(w=M.type)!=null?w:"text",C;h==="textarea"?(C=document.createElement("textarea"),C.rows=3):(C=document.createElement("input"),C.type=h),C.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",C.id=`${e.id}-${a}-${M.name}`,C.name=M.name,C.placeholder=(E=M.placeholder)!=null?E:"",M.required&&(C.required=!0),k.appendChild(C),p.appendChild(k)});let u=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=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");m.type="submit",m.textContent=(S=i.submitLabel)!=null?S:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async M=>{var C,w;M.preventDefault();let k=(C=r.formEndpoint)!=null?C:"/form",T=new FormData(p),h={};T.forEach((E,W)=>{h[W]=E}),h.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let W=await E.json();f.textContent=(w=W.message)!=null?w:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await n.sendMessage(String(W.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var uu=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()}},ri=new uu;var ny=()=>{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 pC=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},uC=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},ni=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=pC(t),r=uC(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}},fu=t=>typeof t=="string"?t:t==null?"":String(t),wa={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:fu(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,n=fu(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:fu(r.text)}}},oy=t=>Array.isArray(t)?t.map(e=>String(e)):[],oi=t=>{let e=new Set(oy(t.getSessionMetadata().processedActionMessageIds)),r=()=>{e=new Set(oy(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)},u=l(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var fC=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}},mC=t=>t.map(e=>({...e,streaming:!1})),gC=t=>t.map(e=>({...e,status:"complete"})),Xl=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?fC(r.getItem(t)):null},save:r=>{let n=e();if(n)try{let o={...r,messages:r.messages?mC(r.messages):void 0,artifacts:r.artifacts?gC(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 Ya=ld(zi(),1);function hC(t){if(!t||typeof t!="object"||!("component"in t))return!1;let e=t.component;return typeof e=="string"&&e.length>0}function xC(t,e){if(!hC(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,Ya.parse)(r,Ya.STR|Ya.OBJ),s=xC(o,r);s&&(t=s)}catch{}return e=r.length,t},reset:()=>{t=null,e=0}}}function ay(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function Ql(t,e){let{config:r,message:n,onPropsUpdate:o}=e,s=Co.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 sy(){let t=Jl();return{processChunk:e=>t.processChunk(e),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function iy(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 Yl(t){let e=iy(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 Zl(t){let e=iy(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 yC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ed(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=yC}=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 u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=n,m.appendChild(y);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),f.appendChild(m);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 w=1;w<=5;w++){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",`${w} star${w>1?"s":""}: ${l[w-1]}`),E.title=l[w-1],E.dataset.rating=String(w),E.innerHTML=`
70
+ `,t.addEventListener("click",e);let n=a=>{var k,h,w,C,T,W,R,I,N,V,ie,xe,Je;let s=(k=a.launcher)!=null?k:{},i=Rr(a),d=t.querySelector("[data-role='launcher-title']");if(d){let we=(h=s.title)!=null?h:"Chat Assistant";d.textContent=we,d.setAttribute("title",we)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let we=(w=s.subtitle)!=null?w:"Get answers fast";l.textContent=we,l.setAttribute("title",we)}let p=t.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let we=(C=s.agentIconSize)!=null?C:"40px";if(f.style.height=we,f.style.width=we,f.innerHTML="",s.agentIconName){let De=parseFloat(we)||24,Ae=Me(s.agentIconName,De*.6,"var(--persona-text-inverse, #ffffff)",2);Ae?(f.appendChild(Ae),f.style.display=""):(f.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}let u=t.querySelector("[data-role='launcher-image']");if(u){let we=(R=s.agentIconSize)!=null?R:"40px";u.style.height=we,u.style.width=we,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(u.src=s.iconUrl,u.style.display="block"):u.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let we=(I=s.callToActionIconSize)!=null?I:"32px";m.style.height=we,m.style.width=we,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let De=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,De=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Ae=parseFloat(we)||24,qe=Math.max(Ae-De,8),Ie=Me(s.callToActionIconName,qe,"currentColor",2);Ie?m.appendChild(Ie):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(V=s.callToActionIconText)!=null?V:"\u2197"}let v=s.position&&Vn[s.position]?Vn[s.position]:Vn["bottom-right"],x="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";t.className=i?S:`${x} ${v}`,i||(t.style.zIndex=String((ie=s.zIndex)!=null?ie:Gr));let M="1px solid var(--persona-border, #e5e7eb)",E="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(xe=s.border)!=null?xe:M,t.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:E,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Je=s.collapsedMaxWidth)!=null?Je:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return r&&n(r),{element:t,update:n,destroy:o}};var q0="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Sl=(r,e={})=>{var x,S,M,E,k,h;let{showClose:t=!0,wrapperClassName:n=q0,buttonSize:o,iconSize:a="28px"}=e,s=(x=r==null?void 0:r.launcher)!=null?x:{},i=(S=o!=null?o:s.closeButtonSize)!=null?S:"32px",d=y("div",n),l=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(M=s.closeButtonTooltipText)!=null?M:"Close chat",f=(E=s.closeButtonShowTooltip)!=null?E:!0;l.setAttribute("aria-label",p),l.style.display=t?"":"none";let u=(k=s.closeButtonIconName)!=null?k:"x",m=(h=s.closeButtonIconText)!=null?h:"\xD7";l.style.color=s.closeButtonColor||rn.actionIconColor;let v=Me(u,a,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,s.closeButtonBackgroundColor?(l.style.backgroundColor=s.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let w=s.closeButtonBorderWidth||"0px",C=s.closeButtonBorderColor||"transparent";l.style.border=`${w} solid ${C}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(l.style.borderRadius=s.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(l.style.paddingLeft=s.closeButtonPaddingX,l.style.paddingRight=s.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),s.closeButtonPaddingY?(l.style.paddingTop=s.closeButtonPaddingY,l.style.paddingBottom=s.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),f&&p){let w=null,C=()=>{if(w)return;let W=l.ownerDocument,R=W.body;if(!R)return;w=to(W,"div","persona-clear-chat-tooltip"),w.textContent=p;let I=to(W,"div");I.className="persona-clear-chat-tooltip-arrow",w.appendChild(I);let N=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(Fo),w.style.left=`${N.left+N.width/2}px`,w.style.top=`${N.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",C),d.addEventListener("mouseleave",T),l.addEventListener("focus",C),l.addEventListener("blur",T),d._cleanupTooltip=()=>{T(),d.removeEventListener("mouseenter",C),d.removeEventListener("mouseleave",T),l.removeEventListener("focus",C),l.removeEventListener("blur",T)}}return{button:l,wrapper:d}},z0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tl=(r,e={})=>{var w,C,T,W,R,I,N,V,ie,xe,Je,we,De;let{wrapperClassName:t=z0,buttonSize:n,iconSize:o="20px"}=e,s=(C=((w=r==null?void 0:r.launcher)!=null?w:{}).clearChat)!=null?C:{},i=(T=n!=null?n:s.size)!=null?T:"32px",d=(W=s.iconName)!=null?W:"refresh-cw",l=(R=s.iconColor)!=null?R:"",p=(I=s.backgroundColor)!=null?I:"",f=(N=s.borderWidth)!=null?N:"",u=(V=s.borderColor)!=null?V:"",m=(ie=s.borderRadius)!=null?ie:"",v=(xe=s.paddingX)!=null?xe:"",x=(Je=s.paddingY)!=null?Je:"",S=(we=s.tooltipText)!=null?we:"Clear chat",M=(De=s.showTooltip)!=null?De:!0,E=y("div",t),k=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",S),k.style.color=l||rn.actionIconColor;let h=Me(d,o,"currentColor",1);if(h&&(h.style.display="block",k.appendChild(h)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),f||u){let Ae=f||"0px",qe=u||"transparent";k.style.border=`${Ae} solid ${qe}`,k.classList.remove("persona-border-none")}if(m&&(k.style.borderRadius=m,k.classList.remove("persona-rounded-full")),v&&(k.style.paddingLeft=v,k.style.paddingRight=v),x&&(k.style.paddingTop=x,k.style.paddingBottom=x),E.appendChild(k),M&&S){let Ae=null,qe=()=>{if(Ae)return;let J=k.ownerDocument,re=J.body;if(!re)return;Ae=to(J,"div","persona-clear-chat-tooltip"),Ae.textContent=S;let Q=to(J,"div");Q.className="persona-clear-chat-tooltip-arrow",Ae.appendChild(Q);let ge=k.getBoundingClientRect();Ae.style.position="fixed",Ae.style.zIndex=String(Fo),Ae.style.left=`${ge.left+ge.width/2}px`,Ae.style.top=`${ge.top-8}px`,Ae.style.transform="translate(-50%, -100%)",re.appendChild(Ae)},Ie=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};E.addEventListener("mouseenter",qe),E.addEventListener("mouseleave",Ie),k.addEventListener("focus",qe),k.addEventListener("blur",Ie),E._cleanupTooltip=()=>{Ie(),E.removeEventListener("mouseenter",qe),E.removeEventListener("mouseleave",Ie),k.removeEventListener("focus",qe),k.removeEventListener("blur",Ie)}}return{button:k,wrapper:E}};var rn={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))"},bo=r=>{var w,C,T,W,R,I,N,V,ie,xe,Je,we,De,Ae,qe,Ie;let{config:e,showClose:t=!0}=r,n=y("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(w=e==null?void 0:e.launcher)!=null?w:{},a=(C=o.headerIconSize)!=null?C:"48px",s=(T=o.closeButtonPlacement)!=null?T:"inline",i=(W=o.headerIconHidden)!=null?W:!1,d=o.headerIconName,l=y("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=a,l.style.width=a,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let J=parseFloat(a)||24,re=Me(d,J*.6,"currentColor",1);re?l.replaceChildren(re):l.textContent=(I=(R=e==null?void 0:e.launcher)==null?void 0:R.agentIconText)!=null?I:"\u{1F4AC}"}else if((N=e==null?void 0:e.launcher)!=null&&N.iconUrl){let J=y("img");J.src=e.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=a,J.style.width=a,l.replaceChildren(J)}else l.textContent=(ie=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?ie:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=y("span","persona-text-base persona-font-semibold");f.style.color=rn.titleColor,f.textContent=(Je=(xe=e==null?void 0:e.launcher)==null?void 0:xe.title)!=null?Je:"Chat Assistant";let u=y("span","persona-text-xs");u.style.color=rn.subtitleColor,u.textContent=(De=(we=e==null?void 0:e.launcher)==null?void 0:we.subtitle)!=null?De:"Here to help you get answers fast",p.append(f,u),i?n.append(p):n.append(l,p);let m=(Ae=o.clearChat)!=null?Ae:{},v=(qe=m.enabled)!=null?qe:!0,x=(Ie=m.placement)!=null?Ie:"inline",S=null,M=null;if(v){let re=Tl(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=re.button,M=re.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&n.appendChild(M)}let E=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:h}=Sl(e,{showClose:t,wrapperClassName:E});return s!=="top-right"&&n.appendChild(h),{header:n,iconHolder:l,headerTitle:f,headerSubtitle:u,closeButton:k,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:M}},ha=(r,e,t)=>{var s,i,d,l;let n=(s=t==null?void 0:t.launcher)!=null?s:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",a=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";r.appendChild(e.header),o==="top-right"&&(r.style.position="relative",r.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&a==="top-right"&&(r.style.position="relative",r.appendChild(e.clearChatButtonWrapper))};function _o(r){let{items:e,onSelect:t,anchor:n,position:o="bottom-left",portal:a}=r,s=y("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Fo)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",o==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of e){if(m.dividerBefore){let S=document.createElement("hr");s.appendChild(S)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let S=Me(m.icon,16,"currentColor",1.5);S&&v.appendChild(S)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",S=>{S.stopPropagation(),p(),t(m.id)}),s.appendChild(v)}let i=null;function d(){if(!a)return;let m=n.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,o==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){d(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!s.contains(v.target)&&!n.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():p()}function u(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:f,destroy:u}}function Dr(r){let{icon:e,label:t,size:n,strokeWidth:o,className:a,onClick:s,aria:i}=r,d=y("button","persona-icon-btn"+(a?" "+a:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Me(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),s&&d.addEventListener("click",s),i)for(let[p,f]of Object.entries(i))d.setAttribute(p,f);return d}function Qs(r){let{icon:e,label:t,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:d}=r,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,s&&(l+=" "+s);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",t),e){let u=Me(e,a!=null?a:14,"currentColor",2);u&&p.appendChild(u)}let f=y("span");if(f.textContent=t,p.appendChild(f),i&&p.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))p.setAttribute(u,m);return p}function rx(r){let{items:e,selectedId:t,onSelect:n,className:o}=r,a=y("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of e){let f;p.icon?f=Dr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,d(),n(p.id)}}):(f=y("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{s=p.id,d(),n(p.id)})),f.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:f}),a.appendChild(f)}function l(p){s=p,d()}return{element:a,setSelected:l}}function Ml(r){var m,v;let{label:e,icon:t="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:d}=r,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",e);let p=y("span","persona-combo-btn-label");p.textContent=e,l.appendChild(p);let f=Me(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(v=d.padding)!=null?v:"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 x,S;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=_o({items:n,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:a,portal:s});return s||l.appendChild(u.element),l.addEventListener("click",x=>{x.stopPropagation();let S=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),u.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Bp=r=>{var n;let e=bo({config:r.config,showClose:r.showClose,onClose:r.onClose,onClearChat:r.onClearChat}),t=(n=r.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),t())}))}return e};function $0(r,e,t){var n,o,a;if(e!=null&&e.length)for(let s of e){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=s.ariaLabel)!=null?n:s.label)!=null?o:s.id),s.icon){let d=Me(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let d=y("div","persona-relative");d.appendChild(i);let l=_o({items:s.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),r.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(s.id)),r.appendChild(i)}}var Dp=r=>{var E,k,h,w,C,T,W,R,I;let{config:e,showClose:t=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=r,s=(E=e==null?void 0:e.launcher)!=null?E:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Ml({label:(k=s.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=rn.titleColor,p=(h=l.querySelector(".persona-combo-btn-label"))!=null?h:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=rn.titleColor,p.textContent=(w=s.title)!=null?w:"Chat Assistant",l.appendChild(p),$0(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:a),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=o.onTitleClick;l.addEventListener("click",ie=>{ie.target.closest("button")||V()}),l.addEventListener("keydown",ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),V())})}let N=o==null?void 0:o.titleRowHover;N&&(l.style.borderRadius=(T=N.borderRadius)!=null?T:"10px",l.style.padding=(W=N.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,ie;l.style.backgroundColor=(V=N.background)!=null?V:"",l.style.borderColor=(ie=N.border)!=null?ie:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(R=s.closeButtonSize)!=null?R:"32px",u=y("div",""),m=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=s.closeButtonColor||rn.actionIconColor;let v=(I=s.closeButtonIconName)!=null?I:"x",x=Me(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",n&&m.addEventListener("click",n),u.appendChild(m),i.appendChild(u);let S=y("div");S.style.display="none";let M=y("span");return M.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:M,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},kl={default:Bp,minimal:Dp},Fp=r=>{var e;return(e=kl[r])!=null?e:kl.default},$a=(r,e,t)=>{var s,i,d;if(e!=null&&e.render){let l=e.render({config:r,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=y("div");p.style.display="none";let f=y("span"),u=y("span"),m=y("button");m.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(s=e==null?void 0:e.layout)!=null?s:"default",a=Fp(n)({config:r,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(a.iconHolder.style.display="none"),e.showTitle===!1&&(a.headerTitle.style.display="none"),e.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(a.closeButton.style.display="none"),e.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var El=r=>{var s,i;let e=y("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(s=r==null?void 0:r.copy)==null?void 0:s.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 t=3,n=20;e.style.maxHeight=`${t*n}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*n},a=()=>{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:a}},Ll=r=>{var w,C,T,W,R,I,N,V,ie,xe,Je,we;let e=(w=r==null?void 0:r.sendButton)!=null?w:{},t=(C=e.useIcon)!=null?C:!1,n=(T=e.iconText)!=null?T:"\u2191",o=e.iconName,a=(W=e.stopIconName)!=null?W:"square",s=(R=e.tooltipText)!=null?R:"Send message",i=(I=e.stopTooltipText)!=null?I:"Stop generating",d=(V=(N=r==null?void 0:r.copy)==null?void 0:N.sendButtonLabel)!=null?V:"Send",l=(xe=(ie=r==null?void 0:r.copy)==null?void 0:ie.stopButtonLabel)!=null?xe:"Stop",p=(Je=e.showTooltip)!=null?Je:!1,f=(we=e.size)!=null?we:"40px",u=e.backgroundColor,m=e.textColor,v=y("div","persona-send-button-wrapper"),x=y("button",t?"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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let S=null,M=null;if(t){x.style.width=f,x.style.height=f,x.style.minWidth=f,x.style.minHeight=f,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let De=parseFloat(f)||24,Ae=(m==null?void 0:m.trim())||"currentColor";o?(S=Me(o,De,Ae,2),S?x.appendChild(S):x.textContent=n):x.textContent=n,M=Me(a,De,Ae,2),u?x.style.backgroundColor=u:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");e.borderWidth&&(x.style.borderWidth=e.borderWidth,x.style.borderStyle="solid"),e.borderColor&&(x.style.borderColor=e.borderColor),e.paddingX?(x.style.paddingLeft=e.paddingX,x.style.paddingRight=e.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),e.paddingY?(x.style.paddingTop=e.paddingY,x.style.paddingBottom=e.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let E=null;p&&s&&(E=y("div","persona-send-button-tooltip"),E.textContent=s,v.appendChild(E)),x.setAttribute("aria-label",s),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:De=>{if(De===k)return;k=De;let Ae=De==="stop"?i:s;if(x.setAttribute("aria-label",Ae),E&&(E.textContent=Ae),t){if(S&&M){let qe=De==="stop"?M:S;x.replaceChildren(qe)}}else x.textContent=De==="stop"?l:d}}},Pl=r=>{var E,k,h,w,C,T,W,R,I,N,V,ie;let e=(E=r==null?void 0:r.voiceRecognition)!=null?E:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(n||o))return null;let s=(w=(h=r==null?void 0:r.sendButton)==null?void 0:h.size)!=null?w:"40px",i=y("div","persona-send-button-wrapper"),d=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(C=e.iconName)!=null?C:"mic",p=(T=e.iconSize)!=null?T:s,f=parseFloat(p)||24,u=(R=e.backgroundColor)!=null?R:(W=r==null?void 0:r.sendButton)==null?void 0:W.backgroundColor,m=(N=e.iconColor)!=null?N:(I=r==null?void 0:r.sendButton)==null?void 0:I.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Me(l,f,m||"currentColor",1.5);x?d.appendChild(x):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(((ie=e.showTooltip)!=null?ie:!1)&&S){let xe=y("div","persona-send-button-tooltip");xe.textContent=S,i.appendChild(xe)}return{button:d,wrapper:i}},Rl=r=>{var v,x,S,M,E,k,h,w;let e=(v=r==null?void 0:r.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(S=(x=r==null?void 0:r.sendButton)==null?void 0:x.size)!=null?S:"40px",n=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=y("input");o.type="file",o.accept=((M=e.allowedTypes)!=null?M:ho).join(","),o.multiple=((E=e.maxFiles)!=null?E:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let a=y("div","persona-send-button-wrapper"),s=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");s.type="button",s.setAttribute("aria-label",(k=e.buttonTooltipText)!=null?k:"Attach file");let i=(h=e.buttonIconName)!=null?h:"paperclip",d=t,l=parseFloat(d)||40,p=Math.round(l*.6);s.style.width=d,s.style.height=d,s.style.minWidth=d,s.style.minHeight=d,s.style.fontSize="18px",s.style.lineHeight="1",s.style.backgroundColor="transparent",s.style.color="var(--persona-primary, #111827)",s.style.border="none",s.style.borderRadius="6px",s.style.transition="background-color 0.15s ease",s.addEventListener("mouseenter",()=>{s.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),s.addEventListener("mouseleave",()=>{s.style.backgroundColor="transparent"});let f=Me(i,p,"currentColor",1.5);f?s.appendChild(f):s.textContent="\u{1F4CE}",s.addEventListener("click",C=>{C.preventDefault(),o.click()}),a.appendChild(s);let u=(w=e.buttonTooltipText)!=null?w:"Attach file",m=y("div","persona-send-button-tooltip");return m.textContent=u,a.appendChild(m),{button:s,wrapper:a,input:o,previewsContainer:n}},Il=r=>{var s,i,d;let e=(s=r==null?void 0:r.statusIndicator)!=null?s:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",n=y("div",`persona-mt-2 ${t} 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 a=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=y("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=a;return n},Wl=()=>y("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Va=r=>{var v,x,S,M,E,k;let{config:e}=r,t=y("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=Wl(),o=y("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:a,attachAutoResize:s}=El(e);s();let i=Ll(e),d=Pl(e),l=Rl(e),p=Il(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(a);let f=y("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),u=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),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)&&a.focus()}),t.append(n,o,p),{footer:t,suggestions:n,composerForm:o,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x: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:(E=l==null?void 0:l.input)!=null?E:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var nx=()=>{let r=y("button","persona-pill-peek");r.type="button",r.setAttribute("data-persona-pill-peek",""),r.setAttribute("aria-label","Show conversation"),r.setAttribute("tabindex","-1");let e=y("span","persona-pill-peek__icon"),t=Me("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let n=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),a=Me("chevron-up",16,"currentColor",1.5);return a&&o.appendChild(a),r.append(e,n,o),{root:r,textNode:n}},ox=r=>{var v,x,S,M,E,k;let{config:e}=r,t=y("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let n=Wl();n.style.display="none";let o=Il(e);o.style.display="none";let{textarea:a,attachAutoResize:s}=El(e);a.style.maxHeight="100px",s();let i=Ll(e),d=Pl(e),l=Rl(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=y("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let f=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let u=y("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)&&a.focus()}),l&&p.append(l.input),p.append(f,a,u),l&&t.append(l.previewsContainer),t.append(p,n,o);let m=p;return{footer:t,suggestions:n,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x: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:(E=l==null?void 0:l.input)!=null?E:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var ax=r=>{var p,f,u,m,v,x,S,M,E,k,h,w,C,T,W,R,I;let e=(f=(p=r==null?void 0:r.launcher)==null?void 0:p.enabled)!=null?f:!0,t=Rr(r);if(Oo(r)){let N=(m=(u=r==null?void 0:r.launcher)==null?void 0:u.composerBar)!=null?m:{},V=y("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=N.expandedSize)!=null?v:"anchored",V.style.zIndex=String((S=(x=r==null?void 0:r.launcher)==null?void 0:x.zIndex)!=null?S:Gr);let ie=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ie.style.width="100%",V.appendChild(ie);let xe=y("div","persona-widget-pill-root");return xe.setAttribute("data-persona-composer-bar",""),xe.dataset.state="collapsed",xe.dataset.expandedSize=(M=N.expandedSize)!=null?M:"anchored",xe.style.zIndex=String((k=(E=r==null?void 0:r.launcher)==null?void 0:E.zIndex)!=null?k:Gr),{wrapper:V,panel:ie,pillRoot:xe}}if(t){let N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(V),{wrapper:N,panel:V}}if(!e){let N=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ie=(w=(h=r==null?void 0:r.launcher)==null?void 0:h.width)!=null?w:"100%";return N.style.width=ie,V.style.width="100%",N.appendChild(V),{wrapper:N,panel:V}}let o=(C=r==null?void 0:r.launcher)!=null?C:{},a=o.position&&Vn[o.position]?Vn[o.position]:Vn["bottom-right"],s=y("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((W=(T=r==null?void 0:r.launcher)==null?void 0:T.zIndex)!=null?W:Gr);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(I=(R=r==null?void 0:r.launcher)==null?void 0:R.width)!=null?I:r==null?void 0:r.launcherWidth,l=d!=null?d:Cn;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},V0=(r,e)=>{var h,w,C,T,W,R,I,N,V;let t=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Sl(r,{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 a=(C=(w=(h=r==null?void 0:r.launcher)==null?void 0:h.clearChat)==null?void 0:w.enabled)!=null?C:!0,s=null,i=null;if(a){let ie=Tl(r,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=ie.button,i=ie.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=y("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=y("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages"),l.style.setProperty("scrollbar-gutter","stable");let p=y("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let f=y("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");f.textContent=(W=(T=r==null?void 0:r.copy)==null?void 0:T.welcomeTitle)!=null?W:"Hello \u{1F44B}";let u=y("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(I=(R=r==null?void 0:r.copy)==null?void 0:R.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",p.append(f,u);let m=y("div","persona-flex persona-flex-col persona-gap-3"),v=(N=r==null?void 0:r.layout)==null?void 0:N.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=r==null?void 0:r.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,m);let S=y("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=ox({config:r}),{root:E,textNode:k}=nx();return t.append(d,o,l,S),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,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:f,introSubtitle:u,closeButton:n,closeButtonWrapper:o,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("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:E,peekTextNode:k}},sx=(r,e=!0)=>{var S,M,E,k,h,w,C,T,W;if(Oo(r))return V0(r,e);let t=y("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(S=r==null?void 0:r.layout)==null?void 0:S.header,o=((M=r==null?void 0:r.layout)==null?void 0:M.showHeader)!==!1,a=n?$a(r,n,{showClose:e}):bo({config:r,showClose:e}),s=y("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages"),s.style.setProperty("scrollbar-gutter","stable");let i=y("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Rr(r)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=y("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(E=r==null?void 0:r.copy)==null?void 0:E.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=y("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(h=r==null?void 0:r.copy)==null?void 0:h.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let p=y("div","persona-flex persona-flex-col persona-gap-3"),f=(C=r==null?void 0:r.layout)==null?void 0:C.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((T=r==null?void 0:r.copy)==null?void 0:T.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,p);let m=Va({config:r}),v=((W=r==null?void 0:r.layout)==null?void 0:W.showFooter)!==!1;o?ha(t,a,r):(a.header.style.display="none",ha(t,a,r)),t.append(s);let x=y("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(m.footer.style.display="none"),t.append(m.footer),t.append(x),{container:t,body:s,messagesWrapper:p,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var j0=r=>{switch(r){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}},G0=(r,e)=>{if(!r)return null;let t=j0(r);if(t===null)return null;let n=e==null?void 0:e[r],o=n!==void 0?n:t;return o||null},K0=(r,e)=>{let t=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",r),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},X0=r=>{let e=r.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(r)||e.startsWith("data:image/")||!r.includes(":"))},Np=r=>{let e=r.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(r)||e.startsWith("data:")||!r.includes(":"))},Op=320,lx=320,Q0=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),J0=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Y0=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Z0=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),ev=(r,e,t)=>{if(r.length===0)return null;try{let n=y("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),e&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),t==null||t())};return r.forEach((i,d)=>{var f;let l=y("img");l.alt=((f=i.alt)==null?void 0:f.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=`${Op}px`,l.style.maxHeight=`${lx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&s())}),l.addEventListener("load",()=>{p=!0}),X0(i.image)?(l.src=i.image,n.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(s(),null):n}catch{return t==null||t(),null}},tv=r=>{if(r.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return r.forEach(n=>{if(!Np(n.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Op}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},rv=r=>{if(r.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return r.forEach(n=>{if(!Np(n.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Op}px`,o.style.maxHeight=`${lx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},nv=r=>{if(r.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return r.forEach(n=>{if(!Np(n.data))return;let o=y("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},xa=()=>{let r=document.createElement("div");r.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 t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="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",r.appendChild(e),r.appendChild(t),r.appendChild(n),r.appendChild(o),r},_p=(r,e,t)=>{let n={config:t!=null?t:{},streaming:!0,location:r,defaultRenderer:xa};if(e){let o=e(n);if(o!==null)return o}return xa()},ov=(r,e)=>{let t=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=e==="user"?r.userAvatar:r.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=y("img");o.src=n,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=n,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},ix=(r,e)=>{let t=y("div","persona-text-xs persona-text-persona-muted"),n=new Date(r.createdAt);return e.format?t.textContent=e.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},av=(r,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.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 t},Up=(r,e,t)=>{var m,v,x,S,M,E;let n=(m=e.showCopy)!=null?m:!0,o=(v=e.showUpvote)!=null?v:!0,a=(x=e.showDownvote)!=null?x:!0;if(!n&&!o&&!a){let k=y("div");return k.style.display="none",k.id=`actions-${r.id}`,k.setAttribute("data-actions-for",r.id),k}let s=(S=e.visibility)!=null?S:"hover",i=(M=e.align)!=null?M:"right",d=(E=e.layout)!=null?E:"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],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${s==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${r.id}`,f.setAttribute("data-actions-for",r.id);let u=(k,h,w)=>{let C=Dr({icon:k,label:h,size:14,className:"persona-message-action-btn"});return C.setAttribute("data-action",w),C};return n&&f.appendChild(u("copy","Copy message","copy")),o&&f.appendChild(u("thumbs-up","Upvote","upvote")),a&&f.appendChild(u("thumbs-down","Downvote","downvote")),f},ja=(r,e,t,n,o,a)=>{var J,re,Q,ge,Z,G,pe,ke,le,ne,de,Lt,St,We,he,at,Pe;let s=t!=null?t:{},i=(J=s.layout)!=null?J:"bubble",d=s.avatar,l=s.timestamp,p=(re=d==null?void 0:d.show)!=null?re:!1,f=(Q=l==null?void 0:l.show)!=null?Q:!1,u=(ge=d==null?void 0:d.position)!=null?ge:"left",m=(Z=l==null?void 0:l.position)!=null?Z:"below",v=av(r.role,i),x=y("div",v.join(" "));x.id=`bubble-${r.id}`,x.setAttribute("data-message-id",r.id),x.setAttribute("data-persona-theme-zone",r.role==="user"?"user-message":"assistant-message"),r.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):r.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Q0(r),M=(pe=(G=r.content)==null?void 0:G.trim())!=null?pe:"",k=S.length>0&&M===Ki,h=vl((le=(ke=a==null?void 0:a.widgetConfig)==null?void 0:ke.features)==null?void 0:le.streamAnimation),w=(Lt=(de=(ne=a==null?void 0:a.widgetConfig)==null?void 0:ne.features)==null?void 0:de.streamAnimation)==null?void 0:Lt.plugins,C=r.role==="assistant"&&h.type!=="none"?Vs(h.type,w):null,T=r.role==="assistant"&&((St=C==null?void 0:C.isAnimating)==null?void 0:St.call(C,r))===!0,W=r.role==="assistant"&&C!==null&&(!!r.streaming||T);W&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let R=document.createElement("div");R.classList.add("persona-message-content"),W&&C&&(C.containerClass&&R.classList.add(C.containerClass),R.style.setProperty("--persona-stream-step",`${h.speed}ms`),R.style.setProperty("--persona-stream-duration",`${h.duration}ms`));let I=W?Cl((We=r.content)!=null?We:"",h.buffer,C,r,!!r.streaming):(he=r.content)!=null?he:"",N=e({text:I,message:r,streaming:!!r.streaming,raw:r.rawContent}),V=N;W&&(C==null?void 0:C.wrap)==="char"?V=js(N,"char",r.id,{skipTags:C.skipTags}):W&&(C==null?void 0:C.wrap)==="word"&&(V=js(N,"word",r.id,{skipTags:C.skipTags}));let ie=null;if(k?(ie=document.createElement("div"),ie.innerHTML=V,ie.style.display="none",R.appendChild(ie)):R.innerHTML=V,W&&(C!=null&&C.useCaret)&&!k&&M){let j=wl(),ue=R.querySelectorAll(".persona-stream-char, .persona-stream-word"),nt=ue[ue.length-1];if(nt!=null&&nt.parentNode)nt.parentNode.insertBefore(j,nt.nextSibling);else{let It=R.lastElementChild;It?It.appendChild(j):R.appendChild(j)}}if(f&&m==="inline"&&r.createdAt){let j=ix(r,l);j.classList.add("persona-ml-2","persona-inline"),R.appendChild(j)}if(S.length>0){let j=ev(S,!k&&!!M,()=>{k&&ie&&(ie.style.display="")});j?x.appendChild(j):k&&ie&&(ie.style.display="")}let xe=J0(r);if(xe.length>0){let j=tv(xe);j&&x.appendChild(j)}let Je=Y0(r);if(Je.length>0){let j=rv(Je);j&&x.appendChild(j)}let we=Z0(r);if(we.length>0){let j=nv(we);j&&x.appendChild(j)}if(x.appendChild(R),f&&m==="below"&&r.createdAt){let j=ix(r,l);j.classList.add("persona-mt-1"),x.appendChild(j)}let De=r.role==="assistant"?G0(r.stopReason,(Pe=(at=a==null?void 0:a.widgetConfig)==null?void 0:at.copy)==null?void 0:Pe.stopReasonNotice):null;if(r.streaming&&r.role==="assistant"){let j=!!(I&&I.trim()),ue=h.placeholder==="skeleton",nt=ue&&h.buffer==="line"&&j;if(j)nt&&x.appendChild(Gs());else if(ue)x.appendChild(Gs());else{let It=_p("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);It&&x.appendChild(It)}}if(De&&r.stopReason&&!r.streaming&&(M||(R.style.display="none"),x.appendChild(K0(r.stopReason,De))),r.role==="assistant"&&!r.streaming&&r.content&&r.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let j=Up(r,n,o);x.appendChild(j)}if(!p||r.role==="system")return x;let qe=y("div",`persona-flex persona-gap-2 ${r.role==="user"?"persona-flex-row-reverse":""}`),Ie=ov(d,r.role);return u==="right"||u==="left"&&r.role==="user"?qe.append(x,Ie):qe.append(Ie,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),qe},dx=(r,e,t,n,o,a)=>{let s=t!=null?t:{};return r.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:r,config:{},streaming:!!r.streaming}):r.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:r,config:{},streaming:!!r.streaming}):ja(r,e,t,n,o,a)};var Ga=new Set,sv=(r,e)=>e==null?!1:typeof e=="string"?(r.textContent=e,!0):(r.appendChild(e),!0),iv=(r,e)=>{var n,o;let t=(o=(n=r.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
71
+ `):""},cx=(r,e)=>{let t=Ga.has(r),n=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),a=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",t?"true":"false");let s=n.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Me(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",a&&(a.style.display=t?"none":a.textContent||a.childNodes.length?"":"none")},qp=(r,e)=>{var Je,we,De,Ae,qe,Ie,J,re,Q,ge,Z;let t=r.reasoning,n=y("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-${r.id}`,n.setAttribute("data-message-id",r.id),!t)return n;let o=(we=(Je=e==null?void 0:e.features)==null?void 0:Je.reasoningDisplay)!=null?we:{},a=o.expandable!==!1,s=a&&Ga.has(r.id),i=t.status!=="complete",d=iv(r,(De=o.previewMaxLines)!=null?De:3),l=y("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");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(Ae=e==null?void 0:e.reasoning)!=null?Ae:{},v=String((qe=t.startedAt)!=null?qe:Date.now()),x=()=>{let G=y("span","");return G.setAttribute("data-tool-elapsed",v),G.textContent=_i(t),G},S=(Ie=m.renderCollapsedSummary)==null?void 0:Ie.call(m,{message:r,reasoning:t,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:_i(t),createElapsedElement:x});typeof S=="string"&&S.trim()?(f.textContent=S,p.appendChild(f)):S instanceof HTMLElement?p.appendChild(S):(f.textContent=u,p.appendChild(f));let M=y("span","persona-text-xs persona-text-persona-primary");M.textContent=vh(t),p.appendChild(M);let E=(J=o.loadingAnimation)!=null?J:"none",k=m.activeTextTemplate,h=m.completeTextTemplate,w=i?k:h,C=S instanceof HTMLElement,T=(G,pe,ke)=>{let le=ke;for(let ne of pe){let de=y("span","persona-tool-char");de.style.setProperty("--char-index",String(le)),de.textContent=ne===" "?"\xA0":ne,G.appendChild(de),le++}return le},W=(G,pe)=>{f.textContent="";let ke=Ui(G,""),le=0;for(let ne of ke){let de=ne.styles.length>0?(()=>{let Lt=y("span",ne.styles.map(St=>`persona-tool-text-${St}`).join(" "));return f.appendChild(Lt),Lt})():f;if(ne.isDuration&&i)de.appendChild(x());else{let Lt=ne.isDuration?_i(t):ne.text;pe?le=T(de,Lt,le):de.appendChild(document.createTextNode(Lt))}}};if(!C&&w)if(M.style.display="none",f.style.display="",i&&E!=="none"){let G=(re=m.loadingAnimationDuration)!=null?re:2e3;f.setAttribute("data-preserve-animation","true"),E==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),W(w,!1)):(f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),E==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),W(w,!0))}else W(w,!1);else if(!C&&i&&E!=="none"){f.style.display="";let G=(Q=m.loadingAnimationDuration)!=null?Q:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),E==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let pe=f.textContent||u;f.textContent="",T(f,pe,0)}t.status==="complete"&&(f.style.display="none")}else C||(t.status==="complete"?f.style.display="none":f.style.display="");let R=null;if(a){R=y("div","persona-flex persona-items-center");let pe=Me(s?"chevron-up":"chevron-down",16,"currentColor",2);pe?R.appendChild(pe):R.textContent=s?"Hide":"Show";let ke=y("div","persona-flex persona-items-center persona-ml-auto");ke.append(R),l.append(p,ke)}else l.append(p);let I=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","reasoning"),I.style.display="none",I.style.whiteSpace="pre-wrap",!s&&i&&o.activePreview&&d){let G=(Z=(ge=e==null?void 0:e.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:Z.call(ge,{message:r,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});sv(I,G)||(I.textContent=d),I.style.display=""}if(!s&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!a)return n.append(l,I),n;let N=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=s?"":"none";let V=t.chunks.join(""),ie=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ie.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(ie),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),R){R.innerHTML="";let pe=Me(s?"chevron-up":"chevron-down",16,"currentColor",2);pe?R.appendChild(pe):R.textContent=s?"Hide":"Show"}N.style.display=s?"":"none",I.style.display=s?"none":I.textContent||I.childNodes.length?"":"none"})(),n.append(l,I,N),n};var Ka=new Set,lv=(r,e)=>e==null?!1:typeof e=="string"?(r.textContent=e,!0):(r.appendChild(e),!0),dv=(r,e)=>{var a;let t=r.toolCall;if(!t)return"";let n=((a=t.chunks)!=null?a:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
72
+ `);let o=Na(t.args).trim();return o?o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
73
+ `):""},cv=(r,e)=>{var p,f,u,m,v;let t=r.toolCall,n=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(f=n==null?void 0:n.collapsedMode)!=null?f:"tool-call",a=dv(r,(u=n==null?void 0:n.previewMaxLines)!=null?u:3),s=t?Ch(t):"";if(!t)return{summary:s,previewText:a,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},l=s;return o==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||s:o==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=Md(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Md(t,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},px=(r,e,t)=>{var p;let n=Ka.has(r),o=(p=t==null?void 0:t.toolCall)!=null?p:{},a=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",n?"true":"false");let d=a.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"currentColor",u=Me(n?"chevron-up":"chevron-down",16,f,2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},zp=(r,e)=>{var V,ie,xe,Je,we,De,Ae,qe,Ie;let t=r.toolCall,n=(V=e==null?void 0:e.toolCall)!=null?V:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${r.id}`,o.setAttribute("data-message-id",r.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),o.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let a=(xe=(ie=e==null?void 0:e.features)==null?void 0:ie.toolCallDisplay)!=null?xe:{},s=a.expandable!==!1,i=s&&Ka.has(r.id),{summary:d,previewText:l,isActive:p}=cv(r,e),f=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",s&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(f.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(f.style.paddingLeft=n.headerPaddingX,f.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(f.style.paddingTop=n.headerPaddingY,f.style.paddingBottom=n.headerPaddingY);let u=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let v=String((Je=t.startedAt)!=null?Je:Date.now()),x=()=>{let J=y("span","");return J.setAttribute("data-tool-elapsed",v),J.textContent=Ds(t),J},S=(De=n.renderCollapsedSummary)==null?void 0:De.call(n,{message:r,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(we=a.collapsedMode)!=null?we:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Ds(t),createElapsedElement:x});typeof S=="string"&&S.trim()?(m.textContent=S,u.appendChild(m)):S instanceof HTMLElement?u.appendChild(S):(m.textContent=d,u.appendChild(m));let M=(Ae=a.loadingAnimation)!=null?Ae:"none",E=n.activeTextTemplate,k=n.completeTextTemplate,h=p?E:k,w=S instanceof HTMLElement,C=(J,re,Q)=>{let ge=Q;for(let Z of re){let G=y("span","persona-tool-char");G.style.setProperty("--char-index",String(ge)),G.textContent=Z===" "?"\xA0":Z,J.appendChild(G),ge++}return ge},T=(J,re)=>{var G;m.textContent="";let Q=((G=t.name)==null?void 0:G.trim())||"tool",ge=Ui(J,Q),Z=0;for(let pe of ge){let ke=pe.styles.length>0?(()=>{let le=y("span",pe.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return m.appendChild(le),le})():m;if(pe.isDuration&&p)ke.appendChild(x());else{let le=pe.isDuration?Ds(t):pe.text;re?Z=C(ke,le,Z):ke.appendChild(document.createTextNode(le))}}};if(!w)if(p&&M!=="none"){let J=(qe=n.loadingAnimationDuration)!=null?qe:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),h&&T(h,!1);else if(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),M==="shimmer-color"&&(n.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),h)T(h,!0);else{let re=m.textContent||d;m.textContent="",C(m,re,0)}}else h&&T(h,!1);let W=null;if(s){W=y("div","persona-flex persona-items-center");let J=n.toggleTextColor||n.headerTextColor||"currentColor",re=Me(i?"chevron-up":"chevron-down",16,J,2);re?W.appendChild(re):W.textContent=i?"Hide":"Show";let Q=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(W),f.append(u,Q)}else f.append(u);let R=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","tool"),R.style.display="none",R.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&l){let J=(Ie=n.renderCollapsedPreview)==null?void 0:Ie.call(n,{message:r,toolCall:t,defaultPreview:l,isActive:p,config:e!=null?e:{}});lv(R,J)||(R.textContent=l),R.style.display=""}if(!i&&p&&a.activeMinHeight&&(o.style.minHeight=a.activeMinHeight),!s)return o.append(f,R),o;let I=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=i?"":"none",n.contentBackgroundColor&&(I.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(I.style.color=n.contentTextColor),n.contentPaddingX&&(I.style.paddingLeft=n.contentPaddingX,I.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(I.style.paddingTop=n.contentPaddingY,I.style.paddingBottom=n.contentPaddingY),t.name){let J=y("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?J.style.color=n.contentTextColor:n.headerTextColor&&(J.style.color=n.headerTextColor),J.textContent=t.name,I.appendChild(J)}if(t.args!==void 0){let J=y("div","persona-space-y-1"),re=y("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(re.style.color=n.labelTextColor),re.textContent="Arguments";let Q=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(Q.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(Q.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(Q.style.color=n.codeBlockTextColor),Q.textContent=Na(t.args),J.append(re,Q),I.appendChild(J)}if(t.chunks&&t.chunks.length){let J=y("div","persona-space-y-1"),re=y("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(re.style.color=n.labelTextColor),re.textContent="Activity";let Q=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(Q.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(Q.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(Q.style.color=n.codeBlockTextColor),Q.textContent=t.chunks.join(""),J.append(re,Q),I.appendChild(J)}if(t.status==="complete"&&t.result!==void 0){let J=y("div","persona-space-y-1"),re=y("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(re.style.color=n.labelTextColor),re.textContent="Result";let Q=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(Q.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(Q.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(Q.style.color=n.codeBlockTextColor),Q.textContent=Na(t.result),J.append(re,Q),I.appendChild(J)}if(t.status==="complete"&&typeof t.duration=="number"){let J=y("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(J.style.color=n.contentTextColor),J.textContent=`Duration: ${t.duration}ms`,I.appendChild(J)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let J=n.toggleTextColor||n.headerTextColor||"currentColor",re=Me(i?"chevron-up":"chevron-down",16,J,2);re?W.appendChild(re):W.textContent=i?"Hide":"Show"}I.style.display=i?"":"none",R.style.display=i?"none":R.textContent||R.childNodes.length?"":"none"})(),o.append(f,R,I),o};var Uo=Ai(Fi(),1);var Vp="ask_user_question",$p=8,Xa="data-persona-ask-sheet-for",pv="Other",uv="Other\u2026",fx="Type your own answer here",mx="Send",fv="Next",mv="Back",gv="Submit all",hv="Skip",xv=3,jp="data-ask-current-index",Gp="data-ask-question-count",gx="data-ask-answers",Kp="data-ask-grouped",hx="data-ask-layout",bv=r=>r.layout==="pills"?"pills":"rows",yv=r=>r.getAttribute(hx)==="pills"?"pills":"rows",ux=!1,xx=r=>r.replace(/["\\]/g,"\\$&"),yo=r=>r.variant==="tool"&&!!r.toolCall&&r.toolCall.name===Vp,Hl=r=>{var e,t;return(t=(e=r==null?void 0:r.features)==null?void 0:e.askUserQuestion)!=null?t:{}},vo=r=>{let e=r.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let n=e.chunks;if(!n||n.length===0)return{payload:null,complete:t};try{let o=n.join(""),a=(0,Uo.parse)(o,Uo.STR|Uo.OBJ|Uo.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Js=r=>{let e=Array.isArray(r==null?void 0:r.questions)?r.questions:[];return e.length>$p&&!ux&&(ux=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${$p}.`)),e.slice(0,$p)},vv=r=>{var e;return(e=Js(r)[0])!=null?e:null},Cv=(r,e)=>{var t;return(t=Js(r)[e])!=null?t:null},bx=(r,e)=>{let t=e.styles;t&&(t.sheetBackground&&r.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&r.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&r.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&r.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&r.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&r.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&r.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&r.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&r.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},yx=(r,e,t)=>{if(r!=="rows")return null;let n=y("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),e){let o=y("span","persona-ask-row-check");n.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(t+1),n.appendChild(o)}return n},wv=(r,e,t,n)=>{let a=y("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(e)),a.setAttribute("data-option-label",r.label),t==="rows"){let s=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=r.label,s.appendChild(i),r.description){let l=y("span","persona-ask-row-description");l.textContent=r.description,s.appendChild(l)}a.appendChild(s);let d=yx(t,n,e);d&&a.appendChild(d)}else a.textContent=r.label,r.description&&(a.title=r.description);return a},Av=r=>{let t=y("span",r==="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 t.setAttribute("aria-hidden","true"),t},Sv=(r,e,t,n)=>{var p,f,u;let a=y("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(r!=null&&r.multiSelect),d=(Array.isArray(r==null?void 0:r.options)?r.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<xv;m++)a.appendChild(Av(n));return a}if(d.forEach((m,v)=>{a.appendChild(wv(m,v,n,s))}),(r==null?void 0:r.allowFreeText)!==!1){let m=n==="rows"?pv:uv;if(n==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("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:fx,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),x.appendChild(S),v.appendChild(x);let M=yx(n,s,d.length);M&&v.appendChild(M),a.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(u=e.freeTextLabel)!=null?u:m,a.appendChild(v)}}return a},vx=(r,e)=>{var a,s;let n=y("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=(a=r.freeTextPlaceholder)!=null?a:fx,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),e!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=r.submitLabel)!=null?s:mx,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},Tv=r=>{var n;let e=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=y("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(n=r.submitLabel)!=null?n:mx,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Mv=(r,e,t)=>{var l,p,f,u;let n=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:mv,o.setAttribute("data-ask-user-action","back"),o.disabled=r===0,n.appendChild(o);let a=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=y("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=t.skipLabel)!=null?p:hv,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=r===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:gv:(u=t.nextLabel)!=null?u:fv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n},ba=r=>{let e=r.getAttribute(gx);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Cx=(r,e)=>{r.setAttribute(gx,JSON.stringify(e))},Bn=r=>{var t;let e=Number((t=r.getAttribute(jp))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},kv=(r,e)=>{r.setAttribute(jp,String(Math.max(0,Math.floor(e))))},Qa=r=>{var t;let e=Number((t=r.getAttribute(Gp))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},qo=r=>r.getAttribute(Kp)==="true",Ev=(r,e)=>{var o;let t=(o=r.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let n={};return e.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(n[s]=d)}}),n},Lv=(r,e)=>{var n;let t=(n=r.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Bl=(r,e)=>{let{payload:t}=vo(e),n=Js(t),o=ba(r),a={},s=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(a[l]=o[d]))}),a},wx=r=>{let e=ba(r),t=Bn(r),n=e[t],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let a=r.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var f;let l=(f=d.getAttribute("data-option-label"))!=null?f:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=r.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!s.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ax=r=>{if(!qo(r))return;let e=ba(r),t=Bn(r),n=e[t],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=r.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!o);let s=r.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Xp=(r,e,t)=>{let n=Hl(t),o=yv(r),{payload:a,complete:s}=vo(e),i=qo(r),d=Bn(r),l=Qa(r),p=i?Cv(a,d):vv(a),f=!!(p!=null&&p.multiSelect),u=r.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${l}`:"");let m=r.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=r.querySelector('[data-ask-question="true"]');if(v){let E=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=E,v.classList.toggle("persona-ask-question-skeleton",!E&&!s)}let x=r.querySelector('[data-ask-pill-list="true"]');if(x){let E=Sv(p,n,s,o);x.replaceWith(E)}if(o!=="rows"){let E=r.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(vx(n,o))}let S=r.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!S?r.appendChild(Tv(n)):(!f||i)&&S&&S.remove(),r.setAttribute("data-multi-select",f?"true":"false");let M=r.querySelector('[data-ask-nav-row="true"]');if(i){let E=Mv(d,l,n);M?M.replaceWith(E):r.appendChild(E)}else M&&M.remove();wx(r),Ax(r)},Pv=(r,e,t)=>{let n=Hl(e),o=bv(n),a=r.toolCall.id,s=Js(t),i=Math.max(1,s.length),d=i>1,l=Ev(r,s),p=d?Lv(r,i):0,f=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Xa,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",r.id),f.setAttribute(Gp,String(i)),f.setAttribute(jp,String(p)),f.setAttribute(Kp,d?"true":"false"),f.setAttribute(hx,o),Cx(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),bx(f,n);let u=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=y("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let S=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),f.appendChild(S),o!=="rows"&&f.appendChild(vx(n,o)),Xp(f,r,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Rv=(r,e,t)=>{let{payload:n}=vo(e),o=Math.max(1,Js(n).length);o>Qa(r)&&(r.setAttribute(Gp,String(o)),o>1&&!qo(r)&&r.setAttribute(Kp,"true")),Xp(r,e,t)},Sx=(r,e)=>{let t=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${r.id}`,t.setAttribute("data-message-id",r.id),t.setAttribute("data-bubble-type","ask-user-question");let n=Hl(e);bx(t,n);let o=y("span","persona-ask-stub-label"),{complete:a}=vo(r);return o.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},Ja=(r,e,t)=>{if(!t||!yo(r)||Hl(e).enabled===!1)return;let o=r.toolCall.id;t.querySelectorAll(`[${Xa}]`).forEach(l=>{l.getAttribute(Xa)!==o&&l.remove()});let s=t.querySelector(`[${Xa}="${xx(o)}"]`);if(s){Rv(s,r,e);return}let{payload:i}=vo(r),d=Pv(r,e,i);t.appendChild(d)},zo=(r,e)=>{if(!r)return;let t=e?`[${Xa}="${xx(e)}"]`:`[${Xa}]`;r.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(a)?a:180)})},Qp=r=>Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),$o=(r,e)=>{let t=ba(r),n=Bn(r);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[n]:t[n]=e,Cx(r,t),wx(r),Ax(r)},Dl=(r,e,t,n)=>{let o=Qa(r),a=Math.max(0,Math.min(o-1,n));kv(r,a),Xp(r,e,t)};var Fl=new Map,Iv=r=>{let t=(r.startsWith(mo)?r.slice(mo.length):r).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return r;let n=t.join(" ").toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},Tx=r=>(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,Mx=(r,e)=>{var n,o,a;let t=(o=(n=Tx(e))==null?void 0:n.detailsDisplay)!=null?o:"collapsed";return(a=Fl.get(r))!=null?a:t==="expanded"},kx=(r,e,t)=>{var s,i;let n=Tx(t);r.setAttribute("aria-expanded",e?"true":"false");let o=r.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(s=n==null?void 0:n.hideDetailsLabel)!=null?s:"Hide details":(i=n==null?void 0:n.showDetailsLabel)!=null?i:"Show details");let a=r.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let d=Me(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&a.appendChild(d)}},Ex=(r,e,t)=>{let n=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!n||!o)return;let a=Mx(r,t);kx(n,a,t),o.style.display=a?"":"none"};var Nl=(r,e)=>{var T,W,R,I,N,V,ie,xe,Je,we,De,Ae,qe,Ie,J;let t=r.approval,n=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",a=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${r.id}`,a.setAttribute("data-message-id",r.id),a.style.backgroundColor=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(W=n==null?void 0:n.borderColor)!=null?W:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(n==null?void 0:n.shadow)!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return a;let s=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(R=n==null?void 0:n.titleColor)!=null?R:"currentColor",p=Me(d,20,l,2);p&&i.appendChild(p);let f=y("div","persona-flex-1 persona-min-w-0"),u=y("div","persona-flex persona-items-center persona-gap-2"),m=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(I=n==null?void 0:n.title)!=null?I:"Approval Required",u.appendChild(m),!o){let re=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");re.setAttribute("data-approval-status",t.status),t.status==="approved"?(re.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",re.style.color="var(--persona-palette-colors-success-700, #15803d)",re.textContent="Approved"):t.status==="denied"?(re.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",re.style.color="var(--persona-palette-colors-error-700, #b91c1c)",re.textContent="Denied"):t.status==="timeout"&&(re.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",re.style.color="var(--persona-palette-colors-warning-700, #b45309)",re.textContent="Timeout"),u.appendChild(re)}f.appendChild(u);let x=t.toolType==="webmcp"||t.toolName.startsWith(mo)?Sd(t.toolName):void 0,S=(N=n==null?void 0:n.formatDescription)==null?void 0:N.call(n,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),M=!t.toolName,E=S||(M?t.description:`The assistant wants to use \u201C${x!=null?x:Iv(t.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),n!=null&&n.descriptionColor&&(k.style.color=n.descriptionColor),k.textContent=E,f.appendChild(k),t.reason){let re=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");re.setAttribute("data-approval-reason","true"),n!=null&&n.reasonColor?re.style.color=n.reasonColor:n!=null&&n.descriptionColor&&(re.style.color=n.descriptionColor);let Q=y("span","persona-font-medium");Q.textContent=`${(V=n==null?void 0:n.reasonLabel)!=null?V:"Agent's stated reason:"} `,re.appendChild(Q),re.appendChild(document.createTextNode(t.reason)),f.appendChild(re)}let h=(ie=n==null?void 0:n.detailsDisplay)!=null?ie:"collapsed",w=!!t.description&&!M,C=w||!!t.parameters;if(h!=="hidden"&&C){let re=Mx(r.id,e),Q=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");Q.type="button",Q.setAttribute("data-expand-header","true"),Q.setAttribute("data-bubble-type","approval"),n!=null&&n.descriptionColor&&(Q.style.color=n.descriptionColor);let ge=y("span");ge.setAttribute("data-approval-details-label","true");let Z=y("span","persona-inline-flex persona-items-center");Z.setAttribute("data-approval-details-chevron","true"),Q.append(ge,Z),kx(Q,re,e),f.appendChild(Q);let G=y("div");if(G.setAttribute("data-approval-details","true"),G.style.display=re?"":"none",w){let pe=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");n!=null&&n.descriptionColor&&(pe.style.color=n.descriptionColor),pe.textContent=t.description,G.appendChild(pe)}if(t.parameters){let pe=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(pe.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(pe.style.color=n.parameterTextColor),pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",pe.textContent=Na(t.parameters),G.appendChild(pe)}f.appendChild(G)}if(o){let re=y("div","persona-flex persona-gap-2 persona-mt-2");re.setAttribute("data-approval-buttons","true");let Q=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");Q.type="button",Q.style.backgroundColor=(xe=n==null?void 0:n.approveButtonColor)!=null?xe:"var(--persona-approval-approve-bg, #22c55e)",Q.style.color=(Je=n==null?void 0:n.approveButtonTextColor)!=null?Je:"#ffffff",Q.setAttribute("data-approval-action","approve");let ge=Me("shield-check",14,(we=n==null?void 0:n.approveButtonTextColor)!=null?we:"#ffffff",2);ge&&(ge.style.marginRight="4px",Q.appendChild(ge));let Z=document.createTextNode((De=n==null?void 0:n.approveLabel)!=null?De:"Approve");Q.appendChild(Z);let G=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");G.type="button",G.style.backgroundColor=(Ae=n==null?void 0:n.denyButtonColor)!=null?Ae:"transparent",G.style.color=(qe=n==null?void 0:n.denyButtonTextColor)!=null?qe:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let pe=Me("shield-x",14,(Ie=n==null?void 0:n.denyButtonTextColor)!=null?Ie:"var(--persona-feedback-error, #dc2626)",2);pe&&(pe.style.marginRight="4px",G.appendChild(pe));let ke=document.createTextNode((J=n==null?void 0:n.denyLabel)!=null?J:"Deny");G.appendChild(ke),re.append(Q,G),f.appendChild(re)}return s.append(i,f),a.appendChild(s),a};var Lx=r=>{let e=[];return{buttons:e,render:(n,o,a,s,i)=>{if(r.innerHTML="",e.length=0,!n||!n.length||(s!=null?s:o?o.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),f=o?o.isStreaming():!1,u=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=f,i!=null&&i.fontFamily&&(v.style.fontFamily=u(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",o.sendMessage(m))}),p.appendChild(v),e.push(v)}),r.appendChild(p)}}};var Ys=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;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),(t=this.store)==null||t.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 t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let n of t)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,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.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 Zs=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{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=()=>{t(n.error)}}catch(n){t(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,t)=>{if(!this.db){e([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(n){t(n)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{e()},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(n){t(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 Wv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Hv=new Set(["step_start","execution_start"]),Bv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Dv=new Set(["step_complete","agent_turn_complete"]),Fv=new Set(["flow_complete","agent_complete"]),Px=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ix=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),wn=r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,ya=(r,e)=>{let t=r[e];return Ix(t)?t:void 0};function Jp(r){return r>0?Math.max(1,Math.ceil(r/4)):0}function Ol(r,e){if(!(r<=0||e===void 0||e<250))return r/(e/1e3)}function Nv(r,e){return typeof e.type=="string"?e.type:r}function Ov(r){return typeof r.text=="string"?r.text:typeof r.delta=="string"?r.delta:typeof r.content=="string"?r.content:typeof r.chunk=="string"?r.chunk:""}function _v(r,e){return r==="step_delta"||r==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":r!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Rx(r){var n,o,a,s,i;let e=ya(r,"result"),t=[ya(r,"tokens"),ya(r,"totalTokens"),e?ya(e,"tokens"):void 0,ya(r,"usage"),e?ya(e,"usage"):void 0];for(let d of t){if(!d)continue;let l=(o=(n=wn(d.output))!=null?n:wn(d.outputTokens))!=null?o:wn(d.completionTokens);if(l!==void 0)return l}return(i=(a=wn(r.outputTokens))!=null?a:wn(r.completionTokens))!=null?i:e?(s=wn(e.outputTokens))!=null?s:wn(e.completionTokens):void 0}function Uv(r){var t,n,o,a,s;let e=ya(r,"result");return(s=(o=(n=(t=wn(r.executionTime))!=null?t:wn(r.executionTimeMs))!=null?n:wn(r.execution_time))!=null?o:wn(r.duration))!=null?s:e?(a=wn(e.executionTime))!=null?a:wn(e.executionTimeMs):void 0}function qv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ei=class{constructor(e=qv){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 t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Ol(this.metric.outputTokens,t)}}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,t){var a;if(!Ix(t)){Px.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=Nv(e,t),o=this.now();if(Wv.has(n)){this.startRun(o);return}if(Hv.has(n)){this.run||this.startRun(o);return}if(Bv.has(n)){if(!_v(n,t))return;let s=Ov(t);if(!s)return;this.run||this.startRun(o);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=s.length;let d=i.exactOutputTokens+Jp(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ol(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Dv.has(n)){if(!this.run)return;let s=this.run,i=Rx(t);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let d=s.exactOutputTokens>0,l=s.exactOutputTokens+Jp(s.visibleCharCount),p=this.resolveDuration(s,t,o);this.metric={status:"running",tokensPerSecond:Ol(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Fv.has(n)){if(!this.run)return;let s=this.run,i=Rx(t),d=i!=null?i:s.exactOutputTokens+Jp(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,t,o);this.metric={status:"complete",tokensPerSecond:Ol(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Px.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let a=Uv(t);return a!=null?a:n-e.startedAt}};function Ya(r,e){e&&e.split(/\s+/).forEach(t=>t&&r.classList.add(t))}var zv={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)"}},$v={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Vv=["flowName","stepName","reasoningText","text","name","tool","toolName"],jv=100;function Gv(r,e){let t={...zv,...e};if(t[r])return t[r];for(let n of Object.keys(t))if(n.endsWith("_")&&r.startsWith(n))return t[n];return $v}function Kv(r,e){return`+${((r-e)/1e3).toFixed(3)}s`}function Xv(r){let e=new Date(r),t=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),a=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${o}.${a}`}function Qv(r,e){try{let t=JSON.parse(r);if(typeof t!="object"||t===null)return null;for(let n of e){let o=n.split("."),a=t;for(let s of o)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function Jv(r){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(r):new Promise(t=>{let n=document.createElement("textarea");n.value=r,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Yv(r){let e;try{e=JSON.parse(r.payload)}catch{e=r.payload}return JSON.stringify({type:r.type,timestamp:new Date(r.timestamp).toISOString(),payload:e},null,2)}function Zv(r){return r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)?"-- tok/s":`${r.tokensPerSecond.toFixed(1)} tok/s`}function eC(r){let e=[];return r.outputTokens!==void 0&&e.push(`${r.outputTokens.toLocaleString()} tok`),r.durationMs!==void 0&&e.push(`${(r.durationMs/1e3).toFixed(2)}s`),r.source&&e.push(r.source),e.join(" \xB7 ")}function tC(r,e,t){let n,o;try{o=JSON.parse(r.payload),n=JSON.stringify(o,null,2)}catch{o=r.payload,n=r.payload}let a=e.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&t){let i=a.renderEventStreamPayload({event:r,config:t,defaultRenderer:()=>s(),parsedPayload:o});if(i)return i}return s();function s(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function Yp(r,e,t,n,o,a,s,i){var u;let d=o.has(r.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ya(l,(u=n.classNames)==null?void 0:u.eventRow);let p=s.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:r,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>a(r.id)});if(m)return l.appendChild(m),l}return l.appendChild(f()),l;function f(){var V,ie;let m=y("div",""),v=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",r.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=Me(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&x.appendChild(S);let M=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(V=n.timestampFormat)!=null?V:"relative";M.textContent=E==="relative"?Kv(r.timestamp,t):Xv(r.timestamp);let k=null;n.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let h=Gv(r.type,n.badgeColors),w=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=h.bg,w.style.color=h.text,w.style.borderColor=h.text+"50",w.textContent=r.type;let C=(ie=n.descriptionFields)!=null?ie:Vv,T=Qv(r.payload,C),W=null;T&&(W=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=T);let R=y("div","persona-flex-1 persona-min-w-0"),I=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=Me("clipboard","12px","currentColor",1.5);return N&&I.appendChild(N),I.addEventListener("click",async xe=>{xe.stopPropagation(),await Jv(Yv(r)),I.innerHTML="";let Je=Me("check","12px","currentColor",1.5);Je&&I.appendChild(Je),setTimeout(()=>{I.innerHTML="";let we=Me("clipboard","12px","currentColor",1.5);we&&I.appendChild(we)},1500)}),v.appendChild(x),v.appendChild(M),k&&v.appendChild(k),v.appendChild(w),W&&v.appendChild(W),v.appendChild(R),v.appendChild(I),m.appendChild(v),d&&m.appendChild(tC(r,s,i)),m}}function Wx(r){var v,x,S,M,E;let{buffer:e,getFullHistory:t,onClose:n,config:o,plugins:a=[],getThroughput:s}=r,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",f=(E=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?E:{},u=a.find(k=>k.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let k=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=f.classNames,h=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ya(h,k==null?void 0:k.panel);let w=[],C="",T="",W=null,R=[],I={},N=0,V=xl(),ie=0,xe=0,Je=!1,we=null,De=!1,Ae=0,qe=new Set,Ie=new Map,J="",re="",Q=null,ge,Z,G,pe,ke,le=null,ne=null,de=null;function Lt(){let ye=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),se=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ya(se,k==null?void 0:k.headerBar);let st=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(st.textContent="Events",ge=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ge.textContent="0",s){ne=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let ir=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");ir.textContent="Throughput",le=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),le.textContent="-- tok/s",de=y("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"),de.style.display="none",de.style.pointerEvents="none";let fr=ne,Sr=de,cn=()=>{if(!Sr.textContent)return;let _r=fr.getBoundingClientRect(),hr=ye.getBoundingClientRect();Sr.style.left=`${_r.left-hr.left}px`,Sr.style.top=`${_r.bottom-hr.top+4}px`,Sr.style.display="block"},Mt=()=>{Sr.style.display="none"};ne.addEventListener("mouseenter",cn),ne.addEventListener("mouseleave",Mt),ne.appendChild(ir),ne.appendChild(le)}let ur=y("div","persona-flex-1");Z=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ct=y("option","");ct.value="",ct.textContent="All events",Z.appendChild(ct),G=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),G.type="button",G.title="Copy All";let Ir=Me("clipboard-copy","12px","currentColor",1.5);Ir&&G.appendChild(Ir);let pt=y("span","persona-text-xs");pt.textContent="Copy All",G.appendChild(pt),se.appendChild(st),se.appendChild(ge),ne&&se.appendChild(ne),se.appendChild(ur),se.appendChild(Z),se.appendChild(G);let Pt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ya(Pt,k==null?void 0:k.searchBar);let et=Me("search","14px","var(--persona-muted, #9ca3af)",1.5),$t=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");et&&$t.appendChild(et),pe=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ya(pe,k==null?void 0:k.searchInput),pe.type="text",pe.placeholder="Search event payloads...",ke=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ke.type="button",ke.style.display="none";let br=Me("x","12px","currentColor",2);return br&&ke.appendChild(br),Pt.appendChild($t),Pt.appendChild(pe),Pt.appendChild(ke),ye.appendChild(se),ye.appendChild(Pt),de&&ye.appendChild(de),ye}let St,We=a.find(ye=>ye.renderEventStreamToolbar);if(We!=null&&We.renderEventStreamToolbar&&o){let ye=We.renderEventStreamToolbar({config:o,defaultRenderer:()=>Lt(),eventCount:e.getSize(),filteredCount:0,onFilterChange:se=>{C=se,ar(),F()},onSearchChange:se=>{T=se,ar(),F()}});St=ye!=null?ye:Lt()}else St=Lt();let he=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");he.style.display="none";function at(){if(!s||!le||!ne)return;let ye=s();le.textContent=Zv(ye);let se=eC(ye);de&&(de.textContent=se,se||(de.style.display="none")),se?ne.setAttribute("aria-label",se):ne.removeAttribute("aria-label")}let Pe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),j=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");j.style.height="100%";let ue=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ya(ue,k==null?void 0:k.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let nt=Me(l,"14px","currentColor",2);nt&&ue.appendChild(nt);let It=y("span","");It.textContent=p,ue.appendChild(It);let ee=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ee.style.display="none",Pe.appendChild(j),Pe.appendChild(ee),Pe.appendChild(ue),h.setAttribute("tabindex","0"),h.appendChild(St),h.appendChild(he),h.appendChild(Pe);function je(){let ye=e.getAll(),se={};for(let pt of ye)se[pt.type]=(se[pt.type]||0)+1;let st=Object.keys(se).sort(),ur=st.length!==R.length||!st.every((pt,Pt)=>pt===R[Pt]),ct=!ur&&st.some(pt=>se[pt]!==I[pt]),xr=ye.length!==Object.values(I).reduce((pt,Pt)=>pt+Pt,0);if(!ur&&!ct&&!xr||(R=st,I=se,!Z))return;let Ir=Z.value;if(Z.options[0].textContent="All events",ur){for(;Z.options.length>1;)Z.remove(1);for(let pt of st){let Pt=y("option","");Pt.value=pt,Pt.textContent=`${pt} (${se[pt]||0})`,Z.appendChild(Pt)}Ir&&st.includes(Ir)?Z.value=Ir:Ir&&(Z.value="",C="")}else for(let pt=1;pt<Z.options.length;pt++){let Pt=Z.options[pt];Pt.textContent=`${Pt.value} (${se[Pt.value]||0})`}}function Fr(){let ye=e.getAll();if(C&&(ye=ye.filter(se=>se.type===C)),T){let se=T.toLowerCase();ye=ye.filter(st=>st.type.toLowerCase().includes(se)||st.payload.toLowerCase().includes(se))}return ye}function Dt(){return C!==""||T!==""}function ar(){N=0,ie=0,V.resume(),ue.style.display="none"}function gr(ye){qe.has(ye)?qe.delete(ye):qe.add(ye),Q=ye;let se=j.scrollTop,st=V.isFollowing();De=!0,V.pause(),F(),j.scrollTop=se,st&&V.resume(),De=!1}function nn(){return ma(j,50)}function F(){xe=Date.now(),Je=!1,at(),je();let ye=e.getEvictedCount();ye>0?(he.textContent=`${ye.toLocaleString()} older events truncated`,he.style.display=""):he.style.display="none",w=Fr();let se=w.length,st=e.getSize()>0;ge&&(ge.textContent=String(e.getSize())),se===0&&st&&Dt()?(ee.textContent=T?`No events matching '${T}'`:"No events matching filter",ee.style.display="",j.style.display="none"):(ee.style.display="none",j.style.display=""),G&&(G.title=Dt()?`Copy Filtered (${se})`:"Copy All"),d&&!V.isFollowing()&&se>N&&(ie+=se-N,It.textContent=p?`${p}${ie>0?` (${ie})`:""}`:"",ue.style.display=""),N=se;let ur=e.getAll(),ct=ur.length>0?ur[0].timestamp:0,xr=new Set(w.map(Pt=>Pt.id));for(let Pt of qe)xr.has(Pt)||qe.delete(Pt);let Ir=C!==J||T!==re,pt=Ie.size===0&&w.length>0;if(Ir||pt||w.length===0){j.innerHTML="",Ie.clear();let Pt=document.createDocumentFragment();for(let et=0;et<w.length;et++){let $t=Yp(w[et],et,ct,f,qe,gr,a,o);Ie.set(w[et].id,$t),Pt.appendChild($t)}j.appendChild(Pt),J=C,re=T,Q=null}else{if(Q!==null){let et=Ie.get(Q);if(et&&et.parentNode===j){let $t=w.findIndex(br=>br.id===Q);if($t>=0){let br=Yp(w[$t],$t,ct,f,qe,gr,a,o);j.insertBefore(br,et),et.remove(),Ie.set(Q,br)}}Q=null}let Pt=new Set(w.map(et=>et.id));for(let[et,$t]of Ie)Pt.has(et)||($t.remove(),Ie.delete(et));for(let et=0;et<w.length;et++){let $t=w[et];if(!Ie.has($t.id)){let br=Yp($t,et,ct,f,qe,gr,a,o);Ie.set($t.id,br),j.appendChild(br)}}}V.isFollowing()&&(j.scrollTop=j.scrollHeight)}function fe(){if(Date.now()-xe>=jv){we!==null&&(cancelAnimationFrame(we),we=null),F();return}Je||(Je=!0,we=requestAnimationFrame(()=>{we=null,F()}))}let Re=(ye,se)=>{if(!G)return;G.innerHTML="";let st=Me(ye,"12px","currentColor",1.5);st&&G.appendChild(st);let ur=y("span","persona-text-xs");ur.textContent="Copy All",G.appendChild(ur),setTimeout(()=>{G.innerHTML="";let ct=Me("clipboard-copy","12px","currentColor",1.5);ct&&G.appendChild(ct);let xr=y("span","persona-text-xs");xr.textContent="Copy All",G.appendChild(xr),G.disabled=!1},se)},Xe=async()=>{if(G){G.disabled=!0;try{let ye;Dt()?ye=w:t?(ye=await t(),ye.length===0&&(ye=e.getAll())):ye=e.getAll();let se=ye.map(st=>{try{return JSON.parse(st.payload)}catch{return st.payload}});await navigator.clipboard.writeText(JSON.stringify(se,null,2)),Re("check",1500)}catch{Re("x",1500)}}},Fe=()=>{Z&&(C=Z.value,ar(),F())},Oe=()=>{!pe||!ke||(ke.style.display=pe.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{T=pe.value,ar(),F()},150))},Ye=()=>{!pe||!ke||(pe.value="",T="",ke.style.display="none",W&&clearTimeout(W),ar(),F())},Tt=()=>{if(De)return;let ye=j.scrollTop,{action:se,nextLastScrollTop:st}=bl({following:V.isFollowing(),currentScrollTop:ye,lastScrollTop:Ae,nearBottom:nn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ae=st,se==="resume"?(V.resume(),ie=0,ue.style.display="none"):se==="pause"&&(V.pause(),d&&(It.textContent=p,ue.style.display=""))},Qt=ye=>{let se=yl({following:V.isFollowing(),deltaY:ye.deltaY,nearBottom:nn(),resumeWhenNearBottom:!0});se==="pause"?(V.pause(),d&&(It.textContent=p,ue.style.display="")):se==="resume"&&(V.resume(),ie=0,ue.style.display="none")},sr=()=>{d&&(j.scrollTop=j.scrollHeight,V.resume(),ie=0,ue.style.display="none")},K=ye=>{let se=ye.target;if(!se||se.closest("button"))return;let st=se.closest("[data-event-id]");if(!st)return;let ur=st.getAttribute("data-event-id");ur&&gr(ur)},ft=ye=>{if((ye.metaKey||ye.ctrlKey)&&ye.key==="f"){ye.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}ye.key==="Escape"&&(pe&&document.activeElement===pe?(Ye(),pe.blur(),h.focus()):n&&n())};G&&G.addEventListener("click",Xe),Z&&Z.addEventListener("change",Fe),pe&&pe.addEventListener("input",Oe),ke&&ke.addEventListener("click",Ye),j.addEventListener("scroll",Tt),j.addEventListener("wheel",Qt,{passive:!0}),j.addEventListener("click",K),ue.addEventListener("click",sr),h.addEventListener("keydown",ft);function it(){W&&clearTimeout(W),we!==null&&(cancelAnimationFrame(we),we=null),Je=!1,Ie.clear(),G&&G.removeEventListener("click",Xe),Z&&Z.removeEventListener("change",Fe),pe&&pe.removeEventListener("input",Oe),ke&&ke.removeEventListener("click",Ye),j.removeEventListener("scroll",Tt),j.removeEventListener("wheel",Qt),j.removeEventListener("click",K),ue.removeEventListener("click",sr),h.removeEventListener("keydown",ft)}return{element:h,update:fe,destroy:it}}}function Hx(r,e){let t=typeof r.title=="string"&&r.title?r.title:"Untitled artifact",n=typeof r.artifactId=="string"?r.artifactId:"",o=r.status==="streaming"?"streaming":"complete",s=(typeof r.artifactType=="string"?r.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 ${t} 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=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.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",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,f.appendChild(m)}else f.textContent=s;if(l.append(p,f),i.append(d,l),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${t}`,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 Bx=(r,e)=>{var n,o,a;let t=(a=(o=(n=e==null?void 0:e.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:a.renderCard;if(t){let s=typeof r.title=="string"&&r.title?r.title:"Untitled artifact",i=typeof r.artifactId=="string"?r.artifactId:"",d=r.status==="streaming"?"streaming":"complete",l=typeof r.artifactType=="string"?r.artifactType:"markdown",p=t({artifact:{artifactId:i,title:s,artifactType:l,status:d},config:e.config,defaultRenderer:()=>Hx(r,e)});if(p)return p}return Hx(r,e)};var Zp=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}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(([t,n])=>{this.register(t,n)})}},Co=new Zp;Co.register("PersonaArtifactCard",Bx);function rC(r){var o;let e=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=y("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=r.component?`Component: ${r.component}`:"Component";let n=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=r.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(n),e}function Dx(r,e){var Z,G,pe,ke;let t=(G=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:G.layout,o=((pe=t==null?void 0:t.toolbarPreset)!=null?pe:"default")==="document",a=(ke=t==null?void 0:t.panePadding)==null?void 0:ke.trim(),s=r.markdown?sa(r.markdown):null,i=Da(r.sanitize),d=le=>{let ne=s?s(le):ia(le);return i?i(ne):ne},l=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};l&&l.addEventListener("click",()=>{var le;p(),(le=e.onDismiss)==null||le.call(e)});let f=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let u=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=y("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var le;p(),(le=e.onDismiss)==null||le.call(e)});let x="rendered",S=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Dr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Dr({icon:"eye",label:"Rendered view"}),E=o?Dr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Dr({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),h=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,w=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,C=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(w&&C&&C.length>0),W=null,R,I=null,N=null;if(o&&(h||w)&&!T){if(R=h?Qs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let le=Me("chevron-down",14,"currentColor",2);le&&R.appendChild(le)}}else o&&T?(W=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),R=h?Qs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I=Dr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),W.append(R,I)):o?R=Dr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):R=Dr({icon:"copy",label:"Copy"});let V=o?Dr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Dr({icon:"refresh-cw",label:"Refresh"}),ie=o?Dr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Dr({icon:"x",label:"Close"}),xe=()=>{var St,We,he;let le=(St=Ie.find(at=>at.id===J))!=null?St:Ie[Ie.length-1],ne=(We=le==null?void 0:le.id)!=null?We:null,de=(le==null?void 0:le.artifactType)==="markdown"&&(he=le.markdown)!=null?he:"",Lt=le?JSON.stringify({component:le.component,props:le.props},null,2):"";return{markdown:de,jsonPayload:Lt,id:ne}},Je=async()=>{var St;let{markdown:le,jsonPayload:ne}=xe(),de=(St=Ie.find(We=>We.id===J))!=null?St:Ie[Ie.length-1],Lt=(de==null?void 0:de.artifactType)==="markdown"?le:de?ne:"";try{await navigator.clipboard.writeText(Lt)}catch{}};if(R.addEventListener("click",async()=>{let le=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(le&&T){let{markdown:ne,jsonPayload:de,id:Lt}=xe();try{await le({actionId:"primary",artifactId:Lt,markdown:ne,jsonPayload:de})}catch{}return}await Je()}),I&&(C!=null&&C.length)){let le=()=>{var de;return(de=f.closest("[data-persona-root]"))!=null?de:document.body},ne=()=>{N=_o({items:C.map(de=>({id:de.id,label:de.label})),onSelect:async de=>{let{markdown:Lt,jsonPayload:St,id:We}=xe(),he=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{he?await he({actionId:de,artifactId:We,markdown:Lt,jsonPayload:St}):de==="markdown"||de==="md"?await navigator.clipboard.writeText(Lt):de==="json"||de==="source"?await navigator.clipboard.writeText(St):await navigator.clipboard.writeText(Lt||St)}catch{}},anchor:W!=null?W:I,position:"bottom-right",portal:le()})};f.isConnected?ne():requestAnimationFrame(ne),I.addEventListener("click",de=>{de.stopPropagation(),N==null||N.toggle()})}V.addEventListener("click",async()=>{var le;try{await((le=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:le.call(t))}catch{}Q()}),ie.addEventListener("click",()=>{var le;p(),(le=e.onDismiss)==null||le.call(e)});let we=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),E.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",we(),Q()}),E.addEventListener("click",()=>{x="source",we(),Q()});let De=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),S.append(M,E),W?k.append(W,V,ie):k.append(R,V,ie),u.append(S,De,k),we()):(u.appendChild(m),u.appendChild(v)),a&&(u.style.paddingLeft=a,u.style.paddingRight=a);let Ae=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),qe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ae.style.paddingLeft=a,Ae.style.paddingRight=a,qe.style.padding=a),f.appendChild(u),f.appendChild(Ae),f.appendChild(qe);let Ie=[],J=null,re=!1,Q=()=>{var Lt,St,We,he;let le=o&&Ie.length<=1;Ae.classList.toggle("persona-hidden",le),Ae.replaceChildren();for(let at of Ie){let Pe=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Pe.type="button",Pe.textContent=at.title||at.id.slice(0,8),at.id===J&&Pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),Pe.addEventListener("click",()=>e.onSelect(at.id)),Ae.appendChild(Pe)}qe.replaceChildren();let ne=J&&Ie.find(at=>at.id===J)||Ie[Ie.length-1];if(!ne)return;if(o){let at=ne.artifactType==="markdown"?"MD":(Lt=ne.component)!=null?Lt:"Component",j=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";De.textContent=`${j} \xB7 ${at}`}else m.textContent="Artifacts";if(ne.artifactType==="markdown"){if(o&&x==="source"){let Pe=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Pe.textContent=(St=ne.markdown)!=null?St:"",qe.appendChild(Pe);return}let at=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");at.innerHTML=d((We=ne.markdown)!=null?We:""),qe.appendChild(at);return}let de=ne.component?Co.get(ne.component):void 0;if(de){let Pe={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:r,updateProps:()=>{}};try{let j=de((he=ne.props)!=null?he:{},Pe);if(j){qe.appendChild(j);return}}catch{}}qe.appendChild(rC(ne))},ge=()=>{var ne;let le=Ie.length>0;if(f.classList.toggle("persona-hidden",!le),l){let de=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,St=((ne=de==null?void 0:de.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;le&&St&&re?(l.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:l,update(le){var ne,de,Lt;Ie=le.artifacts,J=(Lt=(de=le.selectedId)!=null?de:(ne=le.artifacts[le.artifacts.length-1])==null?void 0:ne.id)!=null?Lt:null,Ie.length>0&&(re=!0),Q(),ge()},setMobileOpen(le){re=le,!le&&l?(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):ge()}}}function Dn(r){var e,t;return((t=(e=r==null?void 0:r.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function Fx(r,e){var a,s,i,d;if(r.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),r.style.removeProperty("--persona-artifact-pane-border"),r.style.removeProperty("--persona-artifact-pane-border-left"),!Dn(e))return;let t=(s=(a=e.features)==null?void 0:a.artifacts)==null?void 0:s.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(r.classList.add("persona-artifact-border-full"),r.style.setProperty("--persona-artifact-pane-border",n)):o&&(r.classList.add("persona-artifact-border-left"),r.style.setProperty("--persona-artifact-pane-border-left",o))}function nC(r){r.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),r.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),r.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function _l(r,e){var d,l,p,f,u,m,v,x,S,M;if(!Dn(e)){r.style.removeProperty("--persona-artifact-split-gap"),r.style.removeProperty("--persona-artifact-pane-width"),r.style.removeProperty("--persona-artifact-pane-max-width"),r.style.removeProperty("--persona-artifact-pane-min-width"),r.style.removeProperty("--persona-artifact-pane-bg"),r.style.removeProperty("--persona-artifact-pane-padding"),nC(r),Fx(r,e);return}let t=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;r.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),r.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),r.style.setProperty("--persona-artifact-pane-max-width",(u=t==null?void 0:t.paneMaxWidth)!=null?u:"28rem"),t!=null&&t.paneMinWidth?r.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):r.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?r.style.setProperty("--persona-artifact-pane-bg",n):r.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?r.style.setProperty("--persona-artifact-pane-padding",o):r.style.removeProperty("--persona-artifact-pane-padding");let a=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();a?r.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):r.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(S=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:S.trim();s?r.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):r.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?r.style.setProperty("--persona-artifact-doc-toggle-active-border",i):r.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Fx(r,e)}var Nx=["panel","seamless"];function Ul(r,e){var i,d,l,p,f,u;for(let m of Nx)r.classList.remove(`persona-artifact-appearance-${m}`);if(r.classList.remove("persona-artifact-unified-split"),r.style.removeProperty("--persona-artifact-pane-radius"),r.style.removeProperty("--persona-artifact-pane-shadow"),r.style.removeProperty("--persona-artifact-unified-outer-radius"),!Dn(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",o=Nx.includes(n)?n:"panel";r.classList.add(`persona-artifact-appearance-${o}`);let a=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();a&&r.style.setProperty("--persona-artifact-pane-radius",a);let s=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(s&&r.style.setProperty("--persona-artifact-pane-shadow",s),(t==null?void 0:t.unifiedSplitChrome)===!0){r.classList.add("persona-artifact-unified-split");let m=((u=t.unifiedSplitOuterRadius)==null?void 0:u.trim())||a;m&&r.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Ox(r,e){var t,n,o;return!e||!Dn(r)?!1:((o=(n=(t=r.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function oC(r,e){if(!(r!=null&&r.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(r.trim());return t?Math.max(0,Number(t[1])):e}function aC(r){if(!(r!=null&&r.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(r.trim());return e?Math.max(0,Number(e[1])):null}function sC(r,e,t){return t<e?e:Math.min(t,Math.max(e,r))}function iC(r,e,t,n){let o=r-n-2*e-t;return Math.max(0,o)}function _x(r,e){var s;let n=(s=(e.getComputedStyle(r).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function Ux(r,e,t,n,o,a){let s=oC(o,200),i=iC(e,t,n,200);i=Math.max(s,i);let d=aC(a);return d!==null&&(i=Math.min(i,d)),sC(r,s,i)}var qx={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},eu=(r,e,t,n)=>{let o=r.querySelectorAll("[data-tv-form]");o.length&&o.forEach(a=>{var v,x,S;if(a.dataset.enhanced==="true")return;let s=(v=a.dataset.tvForm)!=null?v:"init";a.dataset.enhanced="true";let i=(x=qx[s])!=null?x:qx.init;a.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let M=y("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 C,T;let E=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${s}-${M.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=M.label,E.appendChild(k);let h=(C=M.type)!=null?C:"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}-${s}-${M.name}`,w.name=M.name,w.placeholder=(T=M.placeholder)!=null?T:"",M.required&&(w.required=!0),E.appendChild(w),p.appendChild(E)});let f=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(S=i.submitLabel)!=null?S:"Submit",f.appendChild(u),f.appendChild(m),p.appendChild(f),a.replaceChildren(d,p),p.addEventListener("submit",async M=>{var w,C;M.preventDefault();let E=(w=t.formEndpoint)!=null?w:"/form",k=new FormData(p),h={};k.forEach((T,W)=>{h[W]=T}),h.type=s,m.disabled=!0,u.textContent="Submitting\u2026";try{let T=await fetch(E,{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=(C=W.message)!=null?C:"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{m.disabled=!1}})})};var tu=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var n;let t=this.plugins.get(e);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var n,o;return((n=t.priority)!=null?n:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(a=>a.id));return[...t.filter(a=>!n.has(a.id)),...e].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},ti=new tu;var zx=()=>{let r=new Map,e=(o,a)=>(r.has(o)||r.set(o,new Set),r.get(o).add(a),()=>t(o,a)),t=(o,a)=>{var s;(s=r.get(o))==null||s.delete(a)};return{on:e,off:t,emit:(o,a)=>{var s;(s=r.get(o))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var lC=r=>{let e=r.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:r},dC=r=>{let e=r.trim(),t=e.indexOf("{");if(t===-1)return null;let n=0;for(let o=t;o<e.length;o+=1){let a=e[o];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return e.slice(t,o+1)}return null},ri=({text:r})=>{if(!r||!r.includes("{"))return null;try{let e=lC(r),t=dC(e);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},ru=r=>typeof r=="string"?r:r==null?"":String(r),va={message:r=>r.type!=="message"?void 0:{handled:!0,displayText:ru(r.payload.text)},messageAndClick:(r,e)=>{var o;if(r.type!=="message_and_click")return;let t=r.payload,n=ru(t.element);if(n&&((o=e.document)!=null&&o.querySelector)){let a=e.document.querySelector(n);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ru(t.text)}}},$x=r=>Array.isArray(r)?r.map(e=>String(e)):[],ni=r=>{let e=new Set($x(r.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set($x(r.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(e);r.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||e.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?r.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;e.add(a.message.id),n();let d={action:i,message:a.message};r.emit("action:detected",d);for(let l of r.handlers)if(l)try{let p=()=>{r.emit("action:resubmit",d)},f=l(i,{message:a.message,metadata:r.getSessionMetadata(),updateMetadata:r.updateSessionMetadata,document:r.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var cC=r=>{if(!r)return null;try{return JSON.parse(r)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},pC=r=>r.map(e=>({...e,streaming:!1})),uC=r=>r.map(e=>({...e,status:"complete"})),ql=(r="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?cC(t.getItem(r)):null},save:t=>{let n=e();if(n)try{let o={...t,messages:t.messages?pC(t.messages):void 0,artifacts:t.artifacts?uC(t.artifacts):void 0};n.setItem(r,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(r)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Za=Ai(Fi(),1);function fC(r){if(!r||typeof r!="object"||!("component"in r))return!1;let e=r.component;return typeof e=="string"&&e.length>0}function mC(r,e){if(!fC(r))return null;let t=r.props&&typeof r.props=="object"&&r.props!==null?r.props:{};return{component:r.component,props:t,raw:e}}function zl(){let r=null,e=0;return{getExtractedDirective:()=>r,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=e)return r;try{let o=(0,Za.parse)(t,Za.STR|Za.OBJ),a=mC(o,t);a&&(r=a)}catch{}return e=t.length,r},reset:()=>{r=null,e=0}}}function Vx(r){return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"&&"props"in r&&typeof r.props=="object"}function $l(r,e){let{config:t,message:n,onPropsUpdate:o}=e,a=Co.get(r.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${r.component}" not found in registry. Falling back to default rendering.`),null;let s={message:n,config:t,updateProps:i=>{o&&o(i)}};try{return a(r.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${r.component}":`,i),null}}function jx(){let r=zl();return{processChunk:e=>r.processChunk(e),getDirective:()=>r.getExtractedDirective(),reset:()=>{r.reset()}}}function Gx(r){if(typeof r.rawContent=="string"&&r.rawContent.length>0)return r.rawContent;if(typeof r.content=="string"){let e=r.content.trim();if(e.startsWith("{")||e.startsWith("["))return r.content}return null}function Vl(r){let e=Gx(r);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function jl(r){let e=Gx(r);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let n=t;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e}}}catch{}return null}var gC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gl(r){let{onSubmit:e,onDismiss:t,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=gC}=r,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.appendChild(m);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 C=1;C<=5;C++){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",`${C} star${C>1?"s":""}: ${l[C-1]}`),T.title=l[C-1],T.dataset.rating=String(C),T.innerHTML=`
77
74
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
78
75
  <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
76
  </svg>
80
- `,E.addEventListener("click",()=>{u=w,M.forEach((W,P)=>{let R=P<w;W.classList.toggle("selected",R),W.setAttribute("aria-checked",P===w-1?"true":"false")})}),M.push(E),S.appendChild(E)}f.appendChild(S);let k=null;if(d){let w=document.createElement("div");w.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"),w.appendChild(k),f.appendChild(w)}let T=document.createElement("div");T.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 C=document.createElement("button");return C.type="button",C.className="persona-feedback-btn persona-feedback-btn-submit",C.textContent=a,C.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}C.disabled=!0,C.textContent="Submitting...";try{let w=(k==null?void 0:k.value.trim())||void 0;await e(u,w),p.remove()}catch(w){C.disabled=!1,C.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),T.appendChild(h),T.appendChild(C),f.appendChild(T),p.appendChild(f),p}function td(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,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,y.appendChild(x);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,y.appendChild(S),m.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 T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=l;let h=document.createElement("span");h.className="persona-feedback-label-high",h.textContent=p,k.appendChild(T),k.appendChild(h);let C=document.createElement("div");C.className="persona-feedback-numbers";let w=[];for(let N=0;N<=10;N++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${N} out of 10`),j.textContent=String(N),j.dataset.rating=String(N),N<=6?j.classList.add("persona-feedback-detractor"):N<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{f=N,w.forEach((oe,ve)=>{oe.classList.toggle("selected",ve===N),oe.setAttribute("aria-checked",ve===N?"true":"false")})}),w.push(j),C.appendChild(j)}M.appendChild(k),M.appendChild(C),m.appendChild(M);let E=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),N.appendChild(E),m.appendChild(N)}let W=document.createElement("div");W.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(),u.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(f===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let N=(E==null?void 0:E.value.trim())||void 0;await e(f,N),u.remove()}catch(N){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),W.appendChild(P),W.appendChild(R),m.appendChild(W),u.appendChild(m),u}var Za="persona-chat-history",bC=30*1e3,wC={"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 vC(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=wC[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 rd(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 AC(t){try{let e=t==="local"?localStorage:sessionStorage,r="__persist_test__";return e.setItem(r,"1"),e.removeItem(r),e}catch{return null}}var mu=t=>!t||typeof t!="object"?{}:{...t},ly=t=>t.map(e=>({...e,streaming:!1})),dy=(t,e,r)=>{let n=t!=null&&t.markdown?ia(t.markdown):null,o=Wa(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,u;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(e){let f=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&r&&r())}let d;return t!=null&&t.postprocessMessage?d=t.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):n?d=n(a):d=la(a),o?o(d):d}};function cy(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=Be(r,n,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let u=v("span","persona-drop-overlay-label");u.textContent=t.label,e.appendChild(u)}return e}var nd=(t,e,r)=>{var 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,Lf,Pf,If,Rf;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=yl(e),o=ri.getForInstance(n.plugins);n.components&&Co.registerAll(n.components);let s=ny(),i=n.persistState===!1?null:(Nu=n.storageAdapter)!=null?Nu:Xl(),d={},l=null,p=!1,u=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open: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 u(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=u(g);b.metadata&&(d=mu(b.metadata)),(_u=b.messages)!=null&&_u.length&&(n={...n,initialMessages:b.messages}),(Fu=b.artifacts)!=null&&Fu.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:($u=b.selectedArtifactId)!=null?$u:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=u({messages:[],metadata:{}});(Uu=c.messages)!=null&&Uu.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var b;d=(b=c({...d}))!=null?b:{},Ca()},y=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ni],x=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[wa.message,wa.messageAndClick],S=oi({parsers:y,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let M=(zu=(qu=n.launcher)==null?void 0:qu.enabled)!=null?zu:!0,k=(ju=(Vu=n.launcher)==null?void 0:Vu.autoExpand)!=null?ju:!1,T=(Gu=n.autoFocusInput)!=null?Gu:!1,h=k,C=M,w=(Xu=(Ku=n.layout)==null?void 0:Ku.header)==null?void 0:Xu.layout,E=!1,W=()=>_o(n),P=()=>M||W(),R=W()?!1:M?k:!0,N=!1,j=null,oe=()=>{N=!0,j&&clearTimeout(j),j=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},ve=dy(n,S,oe),nt=(Qu=(Ju=n.features)==null?void 0:Ju.showReasoning)!=null?Qu:!0,Te=(Zu=(Yu=n.features)==null?void 0:Yu.showToolCalls)!=null?Zu:!0,$e=(tf=(ef=n.features)==null?void 0:ef.showEventStreamToggle)!=null?tf:!1,Se=(nf=(rf=n.features)==null?void 0:rf.scrollToBottom)!=null?nf:{},He=`${(af=typeof n.persistState=="object"?(of=n.persistState)==null?void 0:of.keyPrefix:void 0)!=null?af:"persona-"}event-stream`,V=$e?new ei(He):null,be=(df=(lf=(sf=n.features)==null?void 0:sf.eventStream)==null?void 0:lf.maxEvents)!=null?df:2e3,G=$e?new Zs(be,V):null,Ae=$e?new ti:null,J=null,ie=!1,Me=null,Ge=0;V==null||V.open().then(()=>G==null?void 0:G.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),U!=null&&U.isClientTokenMode()&&U.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),U!=null&&U.isClientTokenMode()&&U.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)}},re=(cf=n.statusIndicator)!=null?cf:{},le=c=>{var g,b,A,B;return c==="idle"?(g=re.idleText)!=null?g:Gr.idle:c==="connecting"?(b=re.connectingText)!=null?b:Gr.connecting:c==="connected"?(A=re.connectedText)!=null?A:Gr.connected:c==="error"?(B=re.errorText)!=null?B:Gr.error:Gr[c]};function gt(c,g,b,A){if(A==="idle"&&b.idleLink){c.textContent="";let B=document.createElement("a");B.href=b.idleLink,B.target="_blank",B.rel="noopener noreferrer",B.textContent=g,B.style.color="inherit",B.style.textDecoration="none",c.appendChild(B)}else c.textContent=g}let{wrapper:ke,panel:ye,pillRoot:tt}=bx(n),Ue=wx(n,P()),{container:he,body:Q,messagesWrapper:Ve,suggestions:ee,textarea:xe,sendButton:z,sendButtonWrapper:De,composerForm:Le,statusText:ge,introTitle:ue,introSubtitle:Oe,closeButton:Z,iconHolder:O,headerTitle:Ie,headerSubtitle:Ne,header:je,footer:Ke,actionsRow:xt,leftActions:st,rightActions:Pt}=Ue,Zt=Ue.setSendButtonMode,X=Ue.micButton,er=Ue.micButtonWrapper,it=Ue.attachmentButton,Vt=Ue.attachmentButtonWrapper,de=Ue.attachmentInput,we=Ue.attachmentPreviewsContainer;he.classList.add("persona-relative"),Q.classList.add("persona-relative");let Ot=12,lr=()=>{var c;return(c=Se.label)!=null?c:""},It=()=>{var c;return(c=Se.iconName)!=null?c:"arrow-down"},hr=()=>Se.enabled!==!1,Ut=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");Ut.type="button",Ut.style.display="none",Ut.setAttribute("data-persona-scroll-to-bottom","true");let Nt=v("span","persona-flex persona-items-center"),Mt=v("span","");Ut.append(Nt,Mt),he.appendChild(Ut);let Rt=()=>{let g=Ke.style.display==="none"?0:Ke.offsetHeight;Ut.style.bottom=`${g+Ot}px`};Rt();let dr=()=>{let c=!!lr();Ut.setAttribute("aria-label",lr()||"Jump to latest"),Ut.title=lr(),Ut.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Nt.innerHTML="";let g=Be(It(),"14px","currentColor",2);g?(Nt.appendChild(g),Nt.style.display=""):Nt.style.display="none",Mt.textContent=lr(),Mt.style.display=c?"":"none"};dr();let ht=null,ur=null,Cr=o.find(c=>c.renderHeader);if(Cr!=null&&Cr.renderHeader){let c=Cr.renderHeader({config:n,defaultRenderer:()=>{let g=bo({config:n,showClose:P()});return ha(he,g,n),g.header},onClose:()=>Qt(!1,"user")});if(c){let g=he.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),je=c)}}let Br=()=>{var g,b,A,B;if(!G)return;if(ie=!0,!J&&G&&(J=Gx({buffer:G,getFullHistory:()=>G.getAllFromStore(),onClose:()=>Ur(),config:n,plugins:o,getThroughput:()=>{var F;return(F=Ae==null?void 0:Ae.getMetric())!=null?F:{status:"idle"}}})),J&&(Q.style.display="none",(g=Ke.parentNode)==null||g.insertBefore(J.element,Ke),J.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${rn.actionIconColor}`;let F=(B=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:B.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&bt.classList.add($))}let c=()=>{if(!ie)return;let F=Date.now();F-Ge>=200&&(J==null||J.update(),Ge=F),Me=requestAnimationFrame(c)};Ge=0,Me=requestAnimationFrame(c),lo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Ur=()=>{var c,g,b;if(ie){if(ie=!1,J&&J.element.remove(),Q.style.display="",bt){bt.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(B=>B&&bt.classList.remove(B))}Me!==null&&(cancelAnimationFrame(Me),Me=null),lo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if($e){let c=(uf=(pf=n.features)==null?void 0:pf.eventStream)==null?void 0:uf.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");bt=v("button",g),bt.style.width="28px",bt.style.height="28px",bt.style.color=rn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let b=Be("activity","18px","currentColor",1.5);b&&bt.appendChild(b);let A=Ue.clearChatButtonWrapper,B=Ue.closeButtonWrapper,F=A||B;F&&F.parentNode===je?je.insertBefore(bt,F):je.appendChild(bt),bt.addEventListener("click",()=>{ie?Ur():Br()})}let sn=c=>{var A,B,F;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 $=c.querySelector("[data-persona-composer-form]");$!=null&&$.parentNode?$.parentNode.insertBefore(b,$):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let $=v("input");$.type="file",$.accept=((A=g.allowedTypes)!=null?A:yo).join(","),$.multiple=((B=g.maxFiles)!=null?B:4)>1,$.style.display="none",$.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild($)}},gr=o.find(c=>c.renderComposer);if(gr!=null&&gr.renderComposer){let c=n.composer,g=gr.renderComposer({config:n,defaultRenderer:()=>za({config:n}).footer,onSubmit:b=>{var $;if(!U||U.isStreaming())return;let A=b.trim(),B=($=ht==null?void 0:ht.hasAttachments())!=null?$:!1;if(!A&&!B)return;cs();let F;B&&(F=[],F.push(...ht.getContentParts()),A&&F.push(Ds(A))),U.sendMessage(A,{contentParts:F}),B&&ht.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:((ff=n.voiceRecognition)==null?void 0:ff.enabled)===!0?()=>{ur==null||ur()}:void 0});g&&(Ke.replaceWith(g),Ke=g)}let Kn=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),B=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&(Le=g),b&&(xe=b),A&&(z=A),B&&(X=B,er=B.parentElement),F&&(ge=F);let $=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(ee=$);let K=c.querySelector(".persona-attachment-button");K&&(it=K,Vt=K.parentElement),de=c.querySelector('input[type="file"]'),we=c.querySelector(".persona-attachment-previews");let _=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(xt=_)};sn(Ke),Kn(Ke);let Nr=(yf=(mf=n.layout)==null?void 0:mf.contentMaxWidth)!=null?yf:W()?(xf=(hf=(gf=n.launcher)==null?void 0:gf.composerBar)==null?void 0:hf.contentMaxWidth)!=null?xf:"720px":void 0;if(Nr&&(Ve.style.maxWidth=Nr,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),Nr&&Le&&!W()&&(Le.style.maxWidth=Nr,Le.style.marginLeft="auto",Le.style.marginRight="auto"),Nr&&ee&&!W()&&(ee.style.maxWidth=Nr,ee.style.marginLeft="auto",ee.style.marginRight="auto"),Nr&&we&&!W()&&(we.style.maxWidth=Nr,we.style.marginLeft="auto",we.style.marginRight="auto"),(bf=n.attachments)!=null&&bf.enabled&&de&&we){ht=ma.fromConfig(n.attachments),ht.setPreviewsContainer(we),de.addEventListener("change",b=>{let A=b.target;ht==null||ht.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=cy(c);he.appendChild(g)}(()=>{var A,B;let c=(B=(A=n.layout)==null?void 0:A.slots)!=null?B:{},g=F=>{switch(F){case"body-top":return he.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return ee;case"composer":return Le;case"footer-bottom":return ge;default:return null}},b=(F,$)=>{var K;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")je.insertBefore($,je.firstChild);else if(F==="header-right")je.appendChild($);else{let _=je.querySelector(".persona-flex-col");_?(K=_.parentNode)==null||K.insertBefore($,_.nextSibling):je.appendChild($)}break;case"body-top":{let _=Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith($):Q.insertBefore($,Q.firstChild);break}case"body-bottom":Q.appendChild($);break;case"footer-top":ee.replaceWith($);break;case"footer-bottom":ge.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(c))if($)try{let K=$({config:n,defaultContent:()=>g(F)});K&&b(F,K)}catch(K){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,K)}})();let Dn=c=>{var $,K;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let A=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!A)return;let B=A.getAttribute("data-message-id");if(!B)return;let F=b.getAttribute("data-bubble-type");if(F==="reasoning")ja.has(B)?ja.delete(B):ja.add(B),Sx(B,A);else if(F==="tool")Ga.has(B)?Ga.delete(B):Ga.add(B),Tx(B,A,n);else if(F==="approval"){let _=n.approval!==!1?n.approval:void 0,We=(($=_==null?void 0:_.detailsDisplay)!=null?$:"collapsed")==="expanded",Ce=(K=zl.get(B))!=null?K:We;zl.set(B,!Ce),Ux(B,A,n)}Ee.delete(B)};Ve.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dn(c))}),Ve.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dn(c))});let On=new Map;Ve.addEventListener("click",c=>{var $;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 B=A.getAttribute("data-actions-for");if(!B)return;let F=b.getAttribute("data-action");if(F==="copy"){let _=U.getMessages().find(We=>We.id===B);if(_&&ce.onCopy){let We=_.content||"";navigator.clipboard.writeText(We).then(()=>{b.classList.add("persona-message-action-success");let Ce=Be("check",14,"currentColor",2);Ce&&(b.innerHTML="",b.appendChild(Ce)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let se=Be("copy",14,"currentColor",2);se&&(b.innerHTML="",b.appendChild(se))},2e3)}).catch(Ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ce)}),ce.onCopy(_)}}else if(F==="upvote"||F==="downvote"){let _=(($=On.get(B))!=null?$:null)===F,We=F==="upvote"?"thumbs-up":"thumbs-down";if(_){On.delete(B),b.classList.remove("persona-message-action-active");let Ce=Be(We,14,"currentColor",2);Ce&&(b.innerHTML="",b.appendChild(Ce))}else{let Ce=F==="upvote"?"downvote":"upvote",se=A.querySelector(`[data-action="${Ce}"]`);if(se){se.classList.remove("persona-message-action-active");let ot=Be(Ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ot&&(se.innerHTML="",se.appendChild(ot))}On.set(B,F),b.classList.add("persona-message-action-active");let Re=Be(We,14,"currentColor",2);Re&&(Re.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Re)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let et=U.getMessages().find(yt=>yt.id===B);et&&ce.onFeedback&&ce.onFeedback({type:F,messageId:et.id,message:et})}}}),Ve.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 B=A.getAttribute("data-message-id");if(!B)return;let F=b.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",_=U.getMessages().find(Ce=>Ce.id===B);if(!(_!=null&&_.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"}),_.approval.toolType==="webmcp"?U.resolveWebMcpApproval(B,$):U.resolveApproval(_.approval,$)});let fe=null,I=null,te={artifacts:[],selectedId:null},Pe=!1,Ze={current:null};Ve.addEventListener("click",c=>{var se,Re,_e,et,yt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((_e=(Re=(se=n.features)==null?void 0:se.artifacts)==null?void 0:Re.onArtifactAction)==null?void 0:_e.call(Re,{type:"download",artifactId:A}))===!0)return;let F=U.getArtifactById(A),$=F==null?void 0:F.markdown,K=(F==null?void 0:F.title)||"artifact";if(!$){let ot=b.closest("[data-open-artifact]"),kt=ot==null?void 0:ot.closest("[data-message-id]"),St=kt==null?void 0:kt.getAttribute("data-message-id");if(St){let qe=U.getMessages().find(rt=>rt.id===St);if(qe!=null&&qe.rawContent)try{let rt=JSON.parse(qe.rawContent);$=(et=rt==null?void 0:rt.props)==null?void 0:et.markdown,K=((yt=rt==null?void 0:rt.props)==null?void 0:yt.title)||K}catch{}}}if(!$)return;let _=new Blob([$],{type:"text/markdown"}),We=URL.createObjectURL(_),Ce=document.createElement("a");Ce.href=We,Ce.download=`${K}.md`,Ce.click(),URL.revokeObjectURL(We)}),Ve.addEventListener("click",c=>{var F,$,K;let b=c.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||((K=($=(F=n.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:K.call($,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),Pe=!1,U.selectArtifact(A),ln())}),Ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let tr=Ue.composerOverlay,jt=(c,g,b)=>{var K,_,We,Ce;let A=g.trim();if(!A||!Ze.current)return;let B=(K=c.getAttribute("data-tool-call-id"))!=null?K:"",F=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:B,answer:A,answers:b.structured,values:(_=b.values)!=null?_:b.source==="multi"?A.split(", "):[A],isFreeText:F,source:b.source},bubbles:!0,composed:!0})),qo(tr,B);let $=Ze.current.getMessages().find(se=>{var Re;return((Re=se.toolCall)==null?void 0:Re.id)===B});(We=$==null?void 0:$.agentMetadata)!=null&&We.awaitingLocalTool?Ze.current.resolveAskUserQuestion($,(Ce=b.structured)!=null?Ce:A):Ze.current.sendMessage(A)},or=c=>{var B;let g=Ze.current;if(!g)return;let b=(B=c.getAttribute("data-tool-call-id"))!=null?B:"",A=g.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===b});A&&g.persistAskUserQuestionProgress(A,{answers:Ul(c,A),currentIndex:Bn(c)})},Hr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),qr=c=>{var B,F,$;if(((F=(B=n.features)==null?void 0:B.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=Bn(c),b=Xa(c);if(g>=b-1)return;let A=($=Ze.current)==null?void 0:$.getMessages().find(K=>{var _;return((_=K.toolCall)==null?void 0:_.id)===c.getAttribute("data-tool-call-id")});A&&(ql(c,A,n,g+1),or(c))};tr.addEventListener("click",c=>{var F,$,K,_,We,Ce,se,Re,_e,et,yt,ot,kt,St;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 B=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),B==="dismiss"){let ze=(F=A.getAttribute("data-tool-call-id"))!=null?F:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ze},bubbles:!0,composed:!0})),qo(tr,ze);let qe=($=Ze.current)==null?void 0:$.getMessages().find(rt=>{var pt;return((pt=rt.toolCall)==null?void 0:pt.id)===ze});(K=qe==null?void 0:qe.agentMetadata)!=null&&K.awaitingLocalTool&&((_=Ze.current)==null||_.markAskUserQuestionResolved(qe),(We=Ze.current)==null||We.resolveAskUserQuestion(qe,"(dismissed)"));return}if(B==="pick"){let ze=b.getAttribute("data-option-label");if(!ze)return;let qe=A.getAttribute("data-multi-select")==="true",rt=Uo(A);if(rt&&qe){let pt=ya(A)[Bn(A)],Ht=new Set(Array.isArray(pt)?pt:[]);Ht.has(ze)?Ht.delete(ze):Ht.add(ze),zo(A,Array.from(Ht)),or(A);return}if(rt){zo(A,ze),or(A),qr(A);return}if(qe){let pt=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",pt?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!pt);let Ht=A.querySelector('[data-ask-user-action="submit-multi"]');Ht&&(Ht.disabled=iu(A).length===0);return}jt(A,ze,{source:"pick",values:[ze]});return}if(B==="submit-multi"){let ze=iu(A);if(ze.length===0)return;jt(A,ze.join(", "),{source:"multi",values:ze});return}if(B==="open-free-text"){let ze=A.querySelector('[data-ask-free-text-row="true"]');if(ze){ze.classList.remove("persona-hidden");let qe=ze.querySelector('[data-ask-free-text-input="true"]');qe==null||qe.focus()}return}if(B==="focus-free-text"){let ze=A.querySelector('[data-ask-free-text-input="true"]');ze==null||ze.focus();return}if(B==="submit-free-text"){let ze=A.querySelector('[data-ask-free-text-input="true"]'),qe=(Ce=ze==null?void 0:ze.value)!=null?Ce:"";if(!qe.trim())return;if(Uo(A)){zo(A,qe.trim()),or(A),qr(A);return}jt(A,qe,{source:"free-text"});return}if(B==="next"||B==="back"){if(!Ze.current)return;let ze=(se=A.getAttribute("data-tool-call-id"))!=null?se:"",qe=Ze.current.getMessages().find(Je=>{var pe;return((pe=Je.toolCall)==null?void 0:pe.id)===ze});if(!qe)return;let rt=A.querySelector('[data-ask-free-text-input="true"]'),pt=(_e=(Re=rt==null?void 0:rt.value)==null?void 0:Re.trim())!=null?_e:"";if(pt){let Je=ya(A)[Bn(A)];(typeof Je!="string"||Je!==pt)&&zo(A,pt)}let Ht=B==="next"?1:-1,D=Bn(A)+Ht;ql(A,qe,n,D),or(A);return}if(B==="submit-all"){if(!Ze.current)return;let ze=(et=A.getAttribute("data-tool-call-id"))!=null?et:"",qe=Ze.current.getMessages().find(Je=>{var pe;return((pe=Je.toolCall)==null?void 0:pe.id)===ze});if(!qe)return;let rt=A.querySelector('[data-ask-free-text-input="true"]'),pt=(ot=(yt=rt==null?void 0:rt.value)==null?void 0:yt.trim())!=null?ot:"";pt&&zo(A,pt);let Ht=Ul(A,qe);Ze.current.persistAskUserQuestionProgress(qe,{answers:Ht,currentIndex:Bn(A)});let D=Hr(Ht);jt(A,D||"(submitted)",{source:"submit-all",structured:Ht});return}if(B==="skip"){if(!Ze.current)return;let ze=(kt=A.getAttribute("data-tool-call-id"))!=null?kt:"",qe=Ze.current.getMessages().find(pe=>{var ft;return((ft=pe.toolCall)==null?void 0:ft.id)===ze});if(!qe)return;let rt=Uo(A),pt=Bn(A),Ht=Xa(A),D=pt>=Ht-1;if(!rt){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ze},bubbles:!0,composed:!0})),qo(tr,ze),(St=qe.agentMetadata)!=null&&St.awaitingLocalTool&&(Ze.current.markAskUserQuestionResolved(qe),Ze.current.resolveAskUserQuestion(qe,"(dismissed)"));return}zo(A,"");let Je=A.querySelector('[data-ask-free-text-input="true"]');if(Je&&(Je.value=""),D){let pe=Ul(A,qe),ft=Hr(pe);jt(A,ft||"(skipped)",{source:"submit-all",structured:pe});return}ql(A,qe,n,pt+1),or(A);return}}),tr.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let b=c.target;if(!((F=b.matches)!=null&&F.call(b,'[data-ask-free-text-input="true"]')))return;let A=b.closest("[data-persona-ask-sheet-for]");if(!A)return;c.preventDefault();let B=b.value;if(B.trim()){if(Uo(A)){zo(A,B.trim()),or(A),qr(A);return}jt(A,B,{source:"free-text"})}});let Cn=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=tr.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),F=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[A-1];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",Cn);let Jt=null,Gt=null,Dr=null,An=null,Ao=()=>{};function ao(){An==null||An(),An=null}let So=()=>{var $;if(!Jt||!Gt)return;let c=t.classList.contains("persona-artifact-appearance-seamless"),b=(($=t.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!c||t.classList.contains("persona-artifact-narrow-host")||b){Gt.style.removeProperty("position"),Gt.style.removeProperty("left"),Gt.style.removeProperty("top"),Gt.style.removeProperty("bottom"),Gt.style.removeProperty("width"),Gt.style.removeProperty("z-index");return}let A=Jt.firstElementChild;if(!A||A===Gt)return;let B=10;Gt.style.position="absolute",Gt.style.top="0",Gt.style.bottom="0",Gt.style.width=`${B}px`,Gt.style.zIndex="5";let F=A.offsetWidth-B/2;Gt.style.left=`${Math.max(0,F)}px`},Xn=()=>{},ln=()=>{var b,A,B,F,$;if(!fe||!Hn(n))return;Gl(t,n),Kl(t,n),Xn();let c=(F=(B=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:B.narrowHostMaxWidth)!=null?F:520,g=ye.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),fe.update(te),Pe?(fe.setMobileOpen(!1),fe.element.classList.add("persona-hidden"),($=fe.backdrop)==null||$.classList.add("persona-hidden")):te.artifacts.length>0&&(fe.element.classList.remove("persona-hidden"),fe.setMobileOpen(!0)),Ao()};if(Hn(n)){ye.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(he),fe=Jx(n,{onSelect:b=>{var A;return(A=Ze.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{Pe=!0,ln()}}),fe.element.classList.add("persona-hidden"),Jt=g,g.appendChild(c),g.appendChild(fe.element),fe.backdrop&&ye.appendChild(fe.backdrop),ye.appendChild(g),Ao=()=>{var A,B,F,$;if(!Jt||!fe)return;if(!(((F=(B=(A=n.features)==null?void 0:A.artifacts)==null?void 0:B.layout)==null?void 0:F.resizable)===!0)){Dr==null||Dr(),Dr=null,ao(),Gt&&(Gt.remove(),Gt=null),fe.element.style.removeProperty("width"),fe.element.style.removeProperty("maxWidth");return}if(!Gt){let K=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");K.setAttribute("role","separator"),K.setAttribute("aria-orientation","vertical"),K.setAttribute("aria-label","Resize artifacts panel"),K.tabIndex=0;let _=t.ownerDocument,We=($=_.defaultView)!=null?$:window,Ce=se=>{var kt,St;if(!fe||se.button!==0||t.classList.contains("persona-artifact-narrow-host")||We.innerWidth<=640)return;se.preventDefault(),ao();let Re=se.clientX,_e=fe.element.getBoundingClientRect().width,et=(St=(kt=n.features)==null?void 0:kt.artifacts)==null?void 0:St.layout,yt=ze=>{let qe=Jt.getBoundingClientRect().width,rt=t.classList.contains("persona-artifact-appearance-seamless"),pt=rt?0:ey(Jt,We),Ht=rt?0:K.getBoundingClientRect().width||6,D=_e-(ze.clientX-Re),Je=ty(D,qe,pt,Ht,et==null?void 0:et.resizableMinWidth,et==null?void 0:et.resizableMaxWidth);fe.element.style.width=`${Je}px`,fe.element.style.maxWidth="none",So()},ot=()=>{_.removeEventListener("pointermove",yt),_.removeEventListener("pointerup",ot),_.removeEventListener("pointercancel",ot),An=null;try{K.releasePointerCapture(se.pointerId)}catch{}};An=ot,_.addEventListener("pointermove",yt),_.addEventListener("pointerup",ot),_.addEventListener("pointercancel",ot);try{K.setPointerCapture(se.pointerId)}catch{}};K.addEventListener("pointerdown",Ce),Gt=K,Jt.insertBefore(K,fe.element),Dr=()=>{K.removeEventListener("pointerdown",Ce)}}if(Gt){let K=te.artifacts.length>0&&!Pe;Gt.classList.toggle("persona-hidden",!K),So()}},Xn=()=>{var We,Ce,se,Re,_e,et,yt,ot,kt,St,ze,qe,rt,pt;if(!M||!fe||((Ce=(We=n.launcher)==null?void 0:We.sidebarMode)!=null?Ce:!1)||kr(n)&&Wn(n).reveal==="emerge")return;let A=(se=t.ownerDocument.defaultView)!=null?se:window,B=(_e=(Re=n.launcher)==null?void 0:Re.mobileFullscreen)!=null?_e:!0,F=(yt=(et=n.launcher)==null?void 0:et.mobileBreakpoint)!=null?yt:640;if(B&&A.innerWidth<=F||!Zx(n,M))return;let $=(St=(kt=(ot=n.launcher)==null?void 0:ot.width)!=null?kt:n.launcherWidth)!=null?St:wn,K=(pt=(rt=(qe=(ze=n.features)==null?void 0:ze.artifacts)==null?void 0:qe.layout)==null?void 0:rt.expandedPanelWidth)!=null?pt:"min(720px, calc(100vw - 24px))";te.artifacts.length>0&&!Pe?(ye.style.width=K,ye.style.maxWidth=K):(ye.style.width=$,ye.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(I=new ResizeObserver(()=>{ln()}),I.observe(ye))}else ye.appendChild(he),W()&&tt&&(Ue.peekBanner&&tt.appendChild(Ue.peekBanner),tt.appendChild(Ke));t.appendChild(ke),tt&&t.appendChild(tt);let Nn=()=>{var Je,pe,ft,rr,Yt,cr,wt,Lr,fn,at,_t,mn,Tr,Pn,gn,Jo,La,Pa,fr,Qo,Wo,Bo,uo,Yo,mt,Vr,Or,Pr;if(W()){ye.style.width="100%",ye.style.maxWidth="100%";let Et=(pe=(Je=n.launcher)==null?void 0:Je.composerBar)!=null?pe:{},vt=ke.dataset.state==="expanded",qt=(ft=Et.expandedSize)!=null?ft:"anchored";if(!(vt&&qt!=="fullscreen")){he.style.background="",he.style.border="",he.style.borderRadius="",he.style.overflow="",he.style.boxShadow="";return}let vr=(Yt=(rr=n.theme)==null?void 0:rr.components)==null?void 0:Yt.panel,Qn=Ua(n),Mr=(ea,Ai)=>{var ys;return ea==null||ea===""?Ai:(ys=Fa(Qn,ea))!=null?ys:ea},Jr="1px solid var(--persona-border)",In="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Zo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";he.style.background="var(--persona-surface, #ffffff)",he.style.border=Mr(vr==null?void 0:vr.border,Jr),he.style.borderRadius=Mr(vr==null?void 0:vr.borderRadius,Zo),he.style.boxShadow=Mr(vr==null?void 0:vr.shadow,In),he.style.overflow="hidden";return}let c=kr(n),g=(wt=(cr=n.launcher)==null?void 0:cr.sidebarMode)!=null?wt:!1,b=c||g||((fn=(Lr=n.launcher)==null?void 0:Lr.fullHeight)!=null?fn:!1),A=((at=n.launcher)==null?void 0:at.enabled)===!1,B=(mn=(_t=n.theme)==null?void 0:_t.components)==null?void 0:mn.panel,F=Ua(n),$=(Et,vt)=>{var qt;return Et==null||Et===""?vt:(qt=Fa(F,Et))!=null?qt:Et},K=(Tr=t.ownerDocument.defaultView)!=null?Tr:window,_=(gn=(Pn=n.launcher)==null?void 0:Pn.mobileFullscreen)!=null?gn:!0,We=(La=(Jo=n.launcher)==null?void 0:Jo.mobileBreakpoint)!=null?La:640,Ce=K.innerWidth<=We,se=_&&Ce&&M,Re=(fr=(Pa=n.launcher)==null?void 0:Pa.position)!=null?fr:"bottom-left",_e=Re==="bottom-left"||Re==="top-left",et=(Wo=(Qo=n.launcher)==null?void 0:Qo.zIndex)!=null?Wo:Kr,yt=g||se?"none":"1px solid var(--persona-border)",ot=se?"none":g?_e?"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&&(ot="none",yt="none");let kt=g||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",St=$(B==null?void 0:B.border,yt),ze=$(B==null?void 0:B.shadow,ot),qe=$(B==null?void 0:B.borderRadius,kt),rt=Q.scrollTop;t.style.cssText="",ke.style.cssText="",ye.style.cssText="",he.style.cssText="",Q.style.cssText="",Ke.style.cssText="";let pt=()=>{var vt;if(rt<=0)return;((vt=Q.ownerDocument.defaultView)!=null?vt:window).requestAnimationFrame(()=>{if(Q.scrollTop===rt)return;let qt=Q.scrollHeight-Q.clientHeight;qt<=0||(Q.scrollTop=Math.min(rt,qt))})};if(se){ke.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"),ke.style.cssText=`
77
+ `,T.addEventListener("click",()=>{f=C,M.forEach((W,R)=>{let I=R<C;W.classList.toggle("selected",I),W.setAttribute("aria-checked",R===C-1?"true":"false")})}),M.push(T),S.appendChild(T)}u.appendChild(S);let E=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=a,E.rows=3,E.setAttribute("aria-label","Additional comments"),C.appendChild(E),u.appendChild(C)}let k=document.createElement("div");k.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",()=>{t==null||t(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(f===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let C=(E==null?void 0:E.value.trim())||void 0;await e(f,C),p.remove()}catch(C){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",C)}}),k.appendChild(h),k.appendChild(w),u.appendChild(k),p.appendChild(u),p}function Kl(r){let{onSubmit:e,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=r,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,v.appendChild(x);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,v.appendChild(S),m.appendChild(v);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 E=document.createElement("div");E.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let h=document.createElement("span");h.className="persona-feedback-label-high",h.textContent=p,E.appendChild(k),E.appendChild(h);let w=document.createElement("div");w.className="persona-feedback-numbers";let C=[];for(let N=0;N<=10;N++){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 ${N} out of 10`),V.textContent=String(N),V.dataset.rating=String(N),N<=6?V.classList.add("persona-feedback-detractor"):N<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{u=N,C.forEach((ie,xe)=>{ie.classList.toggle("selected",xe===N),ie.setAttribute("aria-checked",xe===N?"true":"false")})}),C.push(V),w.appendChild(V)}M.appendChild(E),M.appendChild(w),m.appendChild(M);let T=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=a,T.rows=3,T.setAttribute("aria-label","Additional comments"),N.appendChild(T),m.appendChild(N)}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",()=>{t==null||t(),f.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=s,I.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let N=(T==null?void 0:T.value.trim())||void 0;await e(u,N),f.remove()}catch(N){I.disabled=!1,I.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),W.appendChild(R),W.appendChild(I),m.appendChild(W),f.appendChild(m),f}var es="persona-chat-history",hC=30*1e3,xC={"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 bC(r){var n,o,a;if(!r)return[];let e=[],t=Array.from((n=r.items)!=null?n:[]);for(let s of t){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=xC[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 s of Array.from((a=r.files)!=null?a:[]))s.type.startsWith("image/")&&e.push(s);return e}function Xl(r){if(!r)return!1;let e=r.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function yC(r){var e,t,n,o,a,s,i,d,l;return r?r===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=r.storage)!=null?e:"session",keyPrefix:(t=r.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(n=r.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(s=(a=r.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=r.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=r.clearOnChatClear)!=null?l:!0}:null}function vC(r){try{let e=r==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var nu=r=>!r||typeof r!="object"?{}:{...r},Kx=r=>r.map(e=>({...e,streaming:!1})),Xx=(r,e,t)=>{let n=r!=null&&r.markdown?sa(r.markdown):null,o=Da(r==null?void 0:r.sanitize);return r!=null&&r.postprocessMessage&&o&&(r==null?void 0:r.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var l,p,f;let s=(l=a.text)!=null?l:"",i=(p=a.message.rawContent)!=null?p:null;if(e){let u=e.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});u!==null&&(s=u.text,u.persist||(a.message.__skipPersist=!0),u.resubmit&&!a.streaming&&t&&t())}let d;return r!=null&&r.postprocessMessage?d=r.postprocessMessage({...a,text:s,raw:(f=i!=null?i:a.text)!=null?f:""}):n?d=n(s):d=ia(s),o?o(d):d}};function Qx(r){var i,d,l,p;let e=y("div","persona-attachment-drop-overlay");r!=null&&r.background&&e.style.setProperty("--persona-drop-overlay-bg",r.background),(r==null?void 0:r.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",r.backdropBlur),r!=null&&r.border&&e.style.setProperty("--persona-drop-overlay-border",r.border),r!=null&&r.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",r.borderRadius),r!=null&&r.inset&&e.style.setProperty("--persona-drop-overlay-inset",r.inset),r!=null&&r.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",r.labelSize),r!=null&&r.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",r.labelColor);let t=(i=r==null?void 0:r.iconName)!=null?i:"upload",n=(d=r==null?void 0:r.iconSize)!=null?d:"48px",o=(l=r==null?void 0:r.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(p=r==null?void 0:r.iconStrokeWidth)!=null?p:.5,s=Me(t,n,o,a);if(s&&e.appendChild(s),r!=null&&r.label){let f=y("span","persona-drop-overlay-label");f.textContent=r.label,e.appendChild(f)}return e}var Ql=(r,e,t)=>{var Bu,Du,Fu,Nu,Ou,_u,Uu,qu,zu,$u,Vu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,bf,yf,vf,Cf,wf,Af,Sf,Tf,Mf,kf,Ef,Lf,Pf,Rf;if(r==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');r.id&&!r.getAttribute("data-persona-instance")&&r.setAttribute("data-persona-instance",r.id),r.hasAttribute("data-persona-root")||r.setAttribute("data-persona-root","true");let n=pl(e),o=ti.getForInstance(n.plugins);n.components&&Co.registerAll(n.components);let a=zx(),i=n.persistState===!1?null:(Bu=n.storageAdapter)!=null?Bu:ql(),d={},l=null,p=!1,f=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 f(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=f(g);b.metadata&&(d=nu(b.metadata)),(Du=b.messages)!=null&&Du.length&&(n={...n,initialMessages:b.messages}),(Fu=b.artifacts)!=null&&Fu.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Nu=b.selectedArtifactId)!=null?Nu:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=f({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,m=c=>{var b;d=(b=c({...d}))!=null?b:{},Ma()},v=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ri],x=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[va.message,va.messageAndClick],S=ni({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let M=(Uu=(_u=n.launcher)==null?void 0:_u.enabled)!=null?Uu:!0,E=(zu=(qu=n.launcher)==null?void 0:qu.autoExpand)!=null?zu:!1,k=($u=n.autoFocusInput)!=null?$u:!1,h=E,w=M,C=(ju=(Vu=n.layout)==null?void 0:Vu.header)==null?void 0:ju.layout,T=!1,W=()=>Oo(n),R=()=>M||W(),I=W()?!1:M?E:!0,N=!1,V=null,ie=()=>{N=!0,V&&clearTimeout(V),V=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},xe=Xx(n,S,ie),Je=(Ku=(Gu=n.features)==null?void 0:Gu.showReasoning)!=null?Ku:!0,we=(Qu=(Xu=n.features)==null?void 0:Xu.showToolCalls)!=null?Qu:!0,De=(Yu=(Ju=n.features)==null?void 0:Ju.showEventStreamToggle)!=null?Yu:!1,Ae=(ef=(Zu=n.features)==null?void 0:Zu.scrollToBottom)!=null?ef:{},qe=(rf=(tf=n.features)==null?void 0:tf.scrollBehavior)!=null?rf:{},J=`${(of=typeof n.persistState=="object"?(nf=n.persistState)==null?void 0:nf.keyPrefix:void 0)!=null?of:"persona-"}event-stream`,re=De?new Zs(J):null,Q=(lf=(sf=(af=n.features)==null?void 0:af.eventStream)==null?void 0:sf.maxEvents)!=null?lf:2e3,ge=De?new Ys(Q,re):null,Z=De?new ei:null,G=null,pe=!1,ke=null,le=0;re==null||re.open().then(()=>ge==null?void 0:ge.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ne={onCopy:c=>{var g,b;a.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.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;a.emit("message:feedback",c),q!=null&&q.isClientTokenMode()&&q.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)}},de=(df=n.statusIndicator)!=null?df:{},Lt=c=>{var g,b,A,H;return c==="idle"?(g=de.idleText)!=null?g:jr.idle:c==="connecting"?(b=de.connectingText)!=null?b:jr.connecting:c==="connected"?(A=de.connectedText)!=null?A:jr.connected:c==="error"?(H=de.errorText)!=null?H:jr.error:jr[c]};function St(c,g,b,A){if(A==="idle"&&b.idleLink){c.textContent="";let H=document.createElement("a");H.href=b.idleLink,H.target="_blank",H.rel="noopener noreferrer",H.textContent=g,H.style.color="inherit",H.style.textDecoration="none",c.appendChild(H)}else c.textContent=g}let{wrapper:We,panel:he,pillRoot:at}=ax(n),Pe=sx(n,R()),{container:j,body:ue,messagesWrapper:nt,suggestions:It,textarea:ee,sendButton:je,sendButtonWrapper:Fr,composerForm:Dt,statusText:ar,introTitle:gr,introSubtitle:nn,closeButton:F,iconHolder:fe,headerTitle:Re,headerSubtitle:Xe,header:Fe,footer:Oe,actionsRow:Ye,leftActions:Tt,rightActions:Qt}=Pe,sr=Pe.setSendButtonMode,K=Pe.micButton,ft=Pe.micButtonWrapper,it=Pe.attachmentButton,ye=Pe.attachmentButtonWrapper,se=Pe.attachmentInput,st=Pe.attachmentPreviewsContainer;j.classList.add("persona-relative"),ue.classList.add("persona-relative");let ur=12,ct=()=>{var c;return(c=Ae.label)!=null?c:""},xr=()=>{var c;return(c=Ae.iconName)!=null?c:"arrow-down"},Ir=()=>Ae.enabled!==!1,pt=()=>{var c;return(c=qe.mode)!=null?c:"follow"},Pt=()=>{var c;return(c=qe.anchorTopOffset)!=null?c:16},et=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");et.type="button",et.style.display="none",et.setAttribute("data-persona-scroll-to-bottom","true");let $t=y("span","persona-flex persona-items-center"),br=y("span",""),ir=y("span","");ir.setAttribute("data-persona-scroll-to-bottom-count",""),ir.style.display="none",et.append($t,br,ir),j.appendChild(et);let fr=y("div","persona-stream-anchor-spacer");fr.setAttribute("aria-hidden","true"),fr.setAttribute("data-persona-anchor-spacer",""),fr.style.flexShrink="0",fr.style.pointerEvents="none",fr.style.height="0px",ue.appendChild(fr);let Sr=()=>{let g=Oe.style.display==="none"?0:Oe.offsetHeight;et.style.bottom=`${g+ur}px`};Sr();let cn=()=>{let c=!!ct();et.setAttribute("aria-label",ct()||"Jump to latest"),et.title=ct(),et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),$t.innerHTML="";let g=Me(xr(),"14px","currentColor",2);g?($t.appendChild(g),$t.style.display=""):$t.style.display="none",br.textContent=ct(),br.style.display=c?"":"none"};cn();let Mt=null,_r=null,hr=o.find(c=>c.renderHeader);if(hr!=null&&hr.renderHeader){let c=hr.renderHeader({config:n,defaultRenderer:()=>{let g=bo({config:n,showClose:R()});return ha(j,g,n),g.header},onClose:()=>Gt(!1,"user")});if(c){let g=j.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Fe=c)}}let An=()=>{var g,b,A,H;if(!ge)return;if(pe=!0,!G&&ge&&(G=Wx({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>on(),config:n,plugins:o,getThroughput:()=>{var _;return(_=Z==null?void 0:Z.getMetric())!=null?_:{status:"idle"}}})),G&&(ue.style.display="none",(g=Oe.parentNode)==null||g.insertBefore(G.element,Oe),G.update()),Ct){Ct.style.boxShadow=`inset 0 0 0 1.5px ${rn.actionIconColor}`;let _=(H=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:H.toggleButtonActive;_&&_.split(/\s+/).forEach(U=>U&&Ct.classList.add(U))}let c=()=>{if(!pe)return;let _=Date.now();_-le>=200&&(G==null||G.update(),le=_),ke=requestAnimationFrame(c)};le=0,ke=requestAnimationFrame(c),sn(),a.emit("eventStream:opened",{timestamp:Date.now()})},on=()=>{var c,g,b;if(pe){if(pe=!1,G&&G.element.remove(),ue.style.display="",Ct){Ct.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(H=>H&&Ct.classList.remove(H))}ke!==null&&(cancelAnimationFrame(ke),ke=null),sn(),a.emit("eventStream:closed",{timestamp:Date.now()})}},Ct=null;if(De){let c=(pf=(cf=n.features)==null?void 0:cf.eventStream)==null?void 0:pf.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:"");Ct=y("button",g),Ct.style.width="28px",Ct.style.height="28px",Ct.style.color=rn.actionIconColor,Ct.type="button",Ct.setAttribute("aria-label","Event Stream"),Ct.title="Event Stream";let b=Me("activity","18px","currentColor",1.5);b&&Ct.appendChild(b);let A=Pe.clearChatButtonWrapper,H=Pe.closeButtonWrapper,_=A||H;_&&_.parentNode===Fe?Fe.insertBefore(Ct,_):Fe.appendChild(Ct),Ct.addEventListener("click",()=>{pe?on():An()})}let jn=c=>{var A,H,_;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let 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=y("input");U.type="file",U.accept=((A=g.allowedTypes)!=null?A:ho).join(","),U.multiple=((H=g.maxFiles)!=null?H:4)>1,U.style.display="none",U.setAttribute("aria-label",(_=g.buttonTooltipText)!=null?_:"Attach files"),c.appendChild(U)}},Sn=o.find(c=>c.renderComposer);if(Sn!=null&&Sn.renderComposer){let c=n.composer,g=Sn.renderComposer({config:n,defaultRenderer:()=>Va({config:n}).footer,onSubmit:b=>{var U;if(!q||q.isStreaming())return;let A=b.trim(),H=(U=Mt==null?void 0:Mt.hasAttachments())!=null?U:!1;if(!A&&!H)return;L();let _;H&&(_=[],_.push(...Mt.getContentParts()),A&&_.push(Fs(A))),q.sendMessage(A,{contentParts:_}),H&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{se==null||se.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:((uf=n.voiceRecognition)==null?void 0:uf.enabled)===!0?()=>{_r==null||_r()}:void 0});g&&(Oe.replaceWith(g),Oe=g)}let _e=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),H=c.querySelector("[data-persona-composer-mic]"),_=c.querySelector("[data-persona-composer-status]");g&&(Dt=g),b&&(ee=b),A&&(je=A),H&&(K=H,ft=H.parentElement),_&&(ar=_);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(It=U);let $=c.querySelector(".persona-attachment-button");$&&(it=$,ye=$.parentElement),se=c.querySelector('input[type="file"]'),st=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(Ye=O)};jn(Oe),_e(Oe);let P=(xf=(ff=n.layout)==null?void 0:ff.contentMaxWidth)!=null?xf:W()?(hf=(gf=(mf=n.launcher)==null?void 0:mf.composerBar)==null?void 0:gf.contentMaxWidth)!=null?hf:"720px":void 0;if(P&&(nt.style.maxWidth=P,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),P&&Dt&&!W()&&(Dt.style.maxWidth=P,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),P&&It&&!W()&&(It.style.maxWidth=P,It.style.marginLeft="auto",It.style.marginRight="auto"),P&&st&&!W()&&(st.style.maxWidth=P,st.style.marginLeft="auto",st.style.marginRight="auto"),(bf=n.attachments)!=null&&bf.enabled&&se&&st){Mt=fa.fromConfig(n.attachments),Mt.setPreviewsContainer(st),se.addEventListener("change",b=>{let A=b.target;Mt==null||Mt.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=Qx(c);j.appendChild(g)}(()=>{var A,H;let c=(H=(A=n.layout)==null?void 0:A.slots)!=null?H:{},g=_=>{switch(_){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return It;case"composer":return Dt;case"footer-bottom":return ar;default:return null}},b=(_,U)=>{var $;switch(_){case"header-left":case"header-center":case"header-right":if(_==="header-left")Fe.insertBefore(U,Fe.firstChild);else if(_==="header-right")Fe.appendChild(U);else{let O=Fe.querySelector(".persona-flex-col");O?($=O.parentNode)==null||$.insertBefore(U,O.nextSibling):Fe.appendChild(U)}break;case"body-top":{let O=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(U):ue.insertBefore(U,ue.firstChild);break}case"body-bottom":ue.appendChild(U);break;case"footer-top":It.replaceWith(U);break;case"footer-bottom":ar.replaceWith(U);break;default:break}};for(let[_,U]of Object.entries(c))if(U)try{let $=U({config:n,defaultContent:()=>g(_)});$&&b(_,$)}catch($){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${_}":`,$)}})();let Ee=c=>{var U,$;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let A=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let _=b.getAttribute("data-bubble-type");if(_==="reasoning")Ga.has(H)?Ga.delete(H):Ga.add(H),cx(H,A);else if(_==="tool")Ka.has(H)?Ka.delete(H):Ka.add(H),px(H,A,n);else if(_==="approval"){let O=n.approval!==!1?n.approval:void 0,Ce=((U=O==null?void 0:O.detailsDisplay)!=null?U:"collapsed")==="expanded",me=($=Fl.get(H))!=null?$:Ce;Fl.set(H,!me),Ex(H,A,n)}ao.delete(H)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Ee(c))}),nt.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Ee(c))});let Ot=new Map;nt.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 H=A.getAttribute("data-actions-for");if(!H)return;let _=b.getAttribute("data-action");if(_==="copy"){let O=q.getMessages().find(Ce=>Ce.id===H);if(O&&ne.onCopy){let Ce=O.content||"";navigator.clipboard.writeText(Ce).then(()=>{b.classList.add("persona-message-action-success");let me=Me("check",14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let oe=Me("copy",14,"currentColor",2);oe&&(b.innerHTML="",b.appendChild(oe))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ne.onCopy(O)}}else if(_==="upvote"||_==="downvote"){let O=((U=Ot.get(H))!=null?U:null)===_,Ce=_==="upvote"?"thumbs-up":"thumbs-down";if(O){Ot.delete(H),b.classList.remove("persona-message-action-active");let me=Me(Ce,14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me))}else{let me=_==="upvote"?"downvote":"upvote",oe=A.querySelector(`[data-action="${me}"]`);if(oe){oe.classList.remove("persona-message-action-active");let Qe=Me(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(oe.innerHTML="",oe.appendChild(Qe))}Ot.set(H,_),b.classList.add("persona-message-action-active");let Te=Me(Ce,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Te)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Se=q.getMessages().find(dt=>dt.id===H);Se&&ne.onFeedback&&ne.onFeedback({type:_,messageId:Se.id,message:Se})}}}),nt.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 H=A.getAttribute("data-message-id");if(!H)return;let _=b.getAttribute("data-approval-action");if(!_)return;let U=_==="approve"?"approved":"denied",O=q.getMessages().find(me=>me.id===H);if(!(O!=null&&O.approval))return;let Ce=A.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?q.resolveWebMcpApproval(H,U):q.resolveApproval(O.approval,U)});let Ze=null,_t=null,Zt={artifacts:[],selectedId:null},dr=!1,wt={current:null};nt.addEventListener("click",c=>{var oe,Te,Ve,Se,dt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((Ve=(Te=(oe=n.features)==null?void 0:oe.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:Ve.call(Te,{type:"download",artifactId:A}))===!0)return;let _=q.getArtifactById(A),U=_==null?void 0:_.markdown,$=(_==null?void 0:_.title)||"artifact";if(!U){let Qe=b.closest("[data-open-artifact]"),ht=Qe==null?void 0:Qe.closest("[data-message-id]"),xt=ht==null?void 0:ht.getAttribute("data-message-id");if(xt){let Le=q.getMessages().find(Ke=>Ke.id===xt);if(Le!=null&&Le.rawContent)try{let Ke=JSON.parse(Le.rawContent);U=(Se=Ke==null?void 0:Ke.props)==null?void 0:Se.markdown,$=((dt=Ke==null?void 0:Ke.props)==null?void 0:dt.title)||$}catch{}}}if(!U)return;let O=new Blob([U],{type:"text/markdown"}),Ce=URL.createObjectURL(O),me=document.createElement("a");me.href=Ce,me.download=`${$}.md`,me.click(),URL.revokeObjectURL(Ce)}),nt.addEventListener("click",c=>{var _,U,$;let b=c.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||(($=(U=(_=n.features)==null?void 0:_.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:$.call(U,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),dr=!1,q.selectArtifact(A),un())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Ur=Pe.composerOverlay,Vt=(c,g,b)=>{var $,O,Ce,me;let A=g.trim();if(!A||!wt.current)return;let H=($=c.getAttribute("data-tool-call-id"))!=null?$:"",_=b.source==="free-text";r.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:H,answer:A,answers:b.structured,values:(O=b.values)!=null?O:b.source==="multi"?A.split(", "):[A],isFreeText:_,source:b.source},bubbles:!0,composed:!0})),zo(Ur,H);let U=wt.current.getMessages().find(oe=>{var Te;return((Te=oe.toolCall)==null?void 0:Te.id)===H});(Ce=U==null?void 0:U.agentMetadata)!=null&&Ce.awaitingLocalTool?wt.current.resolveAskUserQuestion(U,(me=b.structured)!=null?me:A):wt.current.sendMessage(A)},qr=c=>{var H;let g=wt.current;if(!g)return;let b=(H=c.getAttribute("data-tool-call-id"))!=null?H:"",A=g.getMessages().find(_=>{var U;return((U=_.toolCall)==null?void 0:U.id)===b});A&&g.persistAskUserQuestionProgress(A,{answers:Bl(c,A),currentIndex:Bn(c)})},Fn=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),no=c=>{var H,_,U;if(((_=(H=n.features)==null?void 0:H.askUserQuestion)==null?void 0:_.groupedAutoAdvance)===!1)return;let g=Bn(c),b=Qa(c);if(g>=b-1)return;let A=(U=wt.current)==null?void 0:U.getMessages().find($=>{var O;return((O=$.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});A&&(Dl(c,A,n,g+1),qr(c))};Ur.addEventListener("click",c=>{var _,U,$,O,Ce,me,oe,Te,Ve,Se,dt,Qe,ht,xt;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 H=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),H==="dismiss"){let Be=(_=A.getAttribute("data-tool-call-id"))!=null?_:"";r.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),zo(Ur,Be);let Le=(U=wt.current)==null?void 0:U.getMessages().find(Ke=>{var rt;return((rt=Ke.toolCall)==null?void 0:rt.id)===Be});($=Le==null?void 0:Le.agentMetadata)!=null&&$.awaitingLocalTool&&((O=wt.current)==null||O.markAskUserQuestionResolved(Le),(Ce=wt.current)==null||Ce.resolveAskUserQuestion(Le,"(dismissed)"));return}if(H==="pick"){let Be=b.getAttribute("data-option-label");if(!Be)return;let Le=A.getAttribute("data-multi-select")==="true",Ke=qo(A);if(Ke&&Le){let rt=ba(A)[Bn(A)],Wt=new Set(Array.isArray(rt)?rt:[]);Wt.has(Be)?Wt.delete(Be):Wt.add(Be),$o(A,Array.from(Wt)),qr(A);return}if(Ke){$o(A,Be),qr(A),no(A);return}if(Le){let rt=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",rt?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!rt);let Wt=A.querySelector('[data-ask-user-action="submit-multi"]');Wt&&(Wt.disabled=Qp(A).length===0);return}Vt(A,Be,{source:"pick",values:[Be]});return}if(H==="submit-multi"){let Be=Qp(A);if(Be.length===0)return;Vt(A,Be.join(", "),{source:"multi",values:Be});return}if(H==="open-free-text"){let Be=A.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Le=Be.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(H==="focus-free-text"){let Be=A.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(H==="submit-free-text"){let Be=A.querySelector('[data-ask-free-text-input="true"]'),Le=(me=Be==null?void 0:Be.value)!=null?me:"";if(!Le.trim())return;if(qo(A)){$o(A,Le.trim()),qr(A),no(A);return}Vt(A,Le,{source:"free-text"});return}if(H==="next"||H==="back"){if(!wt.current)return;let Be=(oe=A.getAttribute("data-tool-call-id"))!=null?oe:"",Le=wt.current.getMessages().find(Ne=>{var Ue;return((Ue=Ne.toolCall)==null?void 0:Ue.id)===Be});if(!Le)return;let Ke=A.querySelector('[data-ask-free-text-input="true"]'),rt=(Ve=(Te=Ke==null?void 0:Ke.value)==null?void 0:Te.trim())!=null?Ve:"";if(rt){let Ne=ba(A)[Bn(A)];(typeof Ne!="string"||Ne!==rt)&&$o(A,rt)}let Wt=H==="next"?1:-1,D=Bn(A)+Wt;Dl(A,Le,n,D),qr(A);return}if(H==="submit-all"){if(!wt.current)return;let Be=(Se=A.getAttribute("data-tool-call-id"))!=null?Se:"",Le=wt.current.getMessages().find(Ne=>{var Ue;return((Ue=Ne.toolCall)==null?void 0:Ue.id)===Be});if(!Le)return;let Ke=A.querySelector('[data-ask-free-text-input="true"]'),rt=(Qe=(dt=Ke==null?void 0:Ke.value)==null?void 0:dt.trim())!=null?Qe:"";rt&&$o(A,rt);let Wt=Bl(A,Le);wt.current.persistAskUserQuestionProgress(Le,{answers:Wt,currentIndex:Bn(A)});let D=Fn(Wt);Vt(A,D||"(submitted)",{source:"submit-all",structured:Wt});return}if(H==="skip"){if(!wt.current)return;let Be=(ht=A.getAttribute("data-tool-call-id"))!=null?ht:"",Le=wt.current.getMessages().find(Ue=>{var be;return((be=Ue.toolCall)==null?void 0:be.id)===Be});if(!Le)return;let Ke=qo(A),rt=Bn(A),Wt=Qa(A),D=rt>=Wt-1;if(!Ke){r.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),zo(Ur,Be),(xt=Le.agentMetadata)!=null&&xt.awaitingLocalTool&&(wt.current.markAskUserQuestionResolved(Le),wt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}$o(A,"");let Ne=A.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),D){let Ue=Bl(A,Le),be=Fn(Ue);Vt(A,be||"(skipped)",{source:"submit-all",structured:Ue});return}Dl(A,Le,n,rt+1),qr(A);return}}),Ur.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 H=b.value;if(H.trim()){if(qo(A)){$o(A,H.trim()),qr(A),no(A);return}Vt(A,H,{source:"free-text"})}});let wo=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=Ur.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",wo);let pn=null,jt=null,Kr=null,Tn=null,Ao=()=>{};function oo(){Tn==null||Tn(),Tn=null}let So=()=>{var U;if(!pn||!jt)return;let c=r.classList.contains("persona-artifact-appearance-seamless"),b=((U=r.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||r.classList.contains("persona-artifact-narrow-host")||b){jt.style.removeProperty("position"),jt.style.removeProperty("left"),jt.style.removeProperty("top"),jt.style.removeProperty("bottom"),jt.style.removeProperty("width"),jt.style.removeProperty("z-index");return}let A=pn.firstElementChild;if(!A||A===jt)return;let H=10;jt.style.position="absolute",jt.style.top="0",jt.style.bottom="0",jt.style.width=`${H}px`,jt.style.zIndex="5";let _=A.offsetWidth-H/2;jt.style.left=`${Math.max(0,_)}px`},Gn=()=>{},un=()=>{var b,A,H,_,U;if(!Ze||!Dn(n))return;_l(r,n),Ul(r,n),Gn();let c=(_=(H=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:H.narrowHostMaxWidth)!=null?_:520,g=he.getBoundingClientRect().width||0;r.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),Ze.update(Zt),dr?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),(U=Ze.backdrop)==null||U.classList.add("persona-hidden")):Zt.artifacts.length>0&&(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)),Ao()};if(Dn(n)){he.style.position="relative";let c=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(j),Ze=Dx(n,{onSelect:b=>{var A;return(A=wt.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{dr=!0,un()}}),Ze.element.classList.add("persona-hidden"),pn=g,g.appendChild(c),g.appendChild(Ze.element),Ze.backdrop&&he.appendChild(Ze.backdrop),he.appendChild(g),Ao=()=>{var A,H,_,U;if(!pn||!Ze)return;if(!(((_=(H=(A=n.features)==null?void 0:A.artifacts)==null?void 0:H.layout)==null?void 0:_.resizable)===!0)){Kr==null||Kr(),Kr=null,oo(),jt&&(jt.remove(),jt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!jt){let $=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");$.setAttribute("role","separator"),$.setAttribute("aria-orientation","vertical"),$.setAttribute("aria-label","Resize artifacts panel"),$.tabIndex=0;let O=r.ownerDocument,Ce=(U=O.defaultView)!=null?U:window,me=oe=>{var ht,xt;if(!Ze||oe.button!==0||r.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;oe.preventDefault(),oo();let Te=oe.clientX,Ve=Ze.element.getBoundingClientRect().width,Se=(xt=(ht=n.features)==null?void 0:ht.artifacts)==null?void 0:xt.layout,dt=Be=>{let Le=pn.getBoundingClientRect().width,Ke=r.classList.contains("persona-artifact-appearance-seamless"),rt=Ke?0:_x(pn,Ce),Wt=Ke?0:$.getBoundingClientRect().width||6,D=Ve-(Be.clientX-Te),Ne=Ux(D,Le,rt,Wt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ze.element.style.width=`${Ne}px`,Ze.element.style.maxWidth="none",So()},Qe=()=>{O.removeEventListener("pointermove",dt),O.removeEventListener("pointerup",Qe),O.removeEventListener("pointercancel",Qe),Tn=null;try{$.releasePointerCapture(oe.pointerId)}catch{}};Tn=Qe,O.addEventListener("pointermove",dt),O.addEventListener("pointerup",Qe),O.addEventListener("pointercancel",Qe);try{$.setPointerCapture(oe.pointerId)}catch{}};$.addEventListener("pointerdown",me),jt=$,pn.insertBefore($,Ze.element),Kr=()=>{$.removeEventListener("pointerdown",me)}}if(jt){let $=Zt.artifacts.length>0&&!dr;jt.classList.toggle("persona-hidden",!$),So()}},Gn=()=>{var Ce,me,oe,Te,Ve,Se,dt,Qe,ht,xt,Be,Le,Ke,rt;if(!M||!Ze||((me=(Ce=n.launcher)==null?void 0:Ce.sidebarMode)!=null?me:!1)||Rr(n)&&Hn(n).reveal==="emerge")return;let A=(oe=r.ownerDocument.defaultView)!=null?oe:window,H=(Ve=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?Ve:!0,_=(dt=(Se=n.launcher)==null?void 0:Se.mobileBreakpoint)!=null?dt:640;if(H&&A.innerWidth<=_||!Ox(n,M))return;let U=(xt=(ht=(Qe=n.launcher)==null?void 0:Qe.width)!=null?ht:n.launcherWidth)!=null?xt:Cn,$=(rt=(Ke=(Le=(Be=n.features)==null?void 0:Be.artifacts)==null?void 0:Le.layout)==null?void 0:Ke.expandedPanelWidth)!=null?rt:"min(720px, calc(100vw - 24px))";Zt.artifacts.length>0&&!dr?(he.style.width=$,he.style.maxWidth=$):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(_t=new ResizeObserver(()=>{un()}),_t.observe(he))}else he.appendChild(j),W()&&at&&(Pe.peekBanner&&at.appendChild(Pe.peekBanner),at.appendChild(Oe));r.appendChild(We),at&&r.appendChild(at);let Nn=()=>{var Ne,Ue,be,Yt,Kt,cr,Bt,lr,hn,Tr,ot,Ut,Er,Rn,xn,Xo,Qo,Ia,Wa,mr,Jo,Wo,Ho,po,ut,Nr,Xr,Mr;if(W()){he.style.width="100%",he.style.maxWidth="100%";let bt=(Ue=(Ne=n.launcher)==null?void 0:Ne.composerBar)!=null?Ue:{},Et=We.dataset.state==="expanded",yt=(be=bt.expandedSize)!=null?be:"anchored";if(!(Et&&yt!=="fullscreen")){j.style.background="",j.style.border="",j.style.borderRadius="",j.style.overflow="",j.style.boxShadow="";return}let Lr=(Kt=(Yt=n.theme)==null?void 0:Yt.components)==null?void 0:Kt.panel,Zn=za(n),Pr=(Zo,wi)=>{var ys;return Zo==null||Zo===""?wi:(ys=Ua(Zn,Zo))!=null?ys:Zo},Qr="1px solid var(--persona-border)",In="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Yo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";j.style.background="var(--persona-surface, #ffffff)",j.style.border=Pr(Lr==null?void 0:Lr.border,Qr),j.style.borderRadius=Pr(Lr==null?void 0:Lr.borderRadius,Yo),j.style.boxShadow=Pr(Lr==null?void 0:Lr.shadow,In),j.style.overflow="hidden";return}let c=Rr(n),g=(Bt=(cr=n.launcher)==null?void 0:cr.sidebarMode)!=null?Bt:!1,b=c||g||((hn=(lr=n.launcher)==null?void 0:lr.fullHeight)!=null?hn:!1),A=((Tr=n.launcher)==null?void 0:Tr.enabled)===!1,H=(Ut=(ot=n.theme)==null?void 0:ot.components)==null?void 0:Ut.panel,_=za(n),U=(bt,Et)=>{var yt;return bt==null||bt===""?Et:(yt=Ua(_,bt))!=null?yt:bt},$=(Er=r.ownerDocument.defaultView)!=null?Er:window,O=(xn=(Rn=n.launcher)==null?void 0:Rn.mobileFullscreen)!=null?xn:!0,Ce=(Qo=(Xo=n.launcher)==null?void 0:Xo.mobileBreakpoint)!=null?Qo:640,me=$.innerWidth<=Ce,oe=O&&me&&M,Te=(Wa=(Ia=n.launcher)==null?void 0:Ia.position)!=null?Wa:"bottom-left",Ve=Te==="bottom-left"||Te==="top-left",Se=(Jo=(mr=n.launcher)==null?void 0:mr.zIndex)!=null?Jo:Gr,dt=g||oe?"none":"1px solid var(--persona-border)",Qe=oe?"none":g?Ve?"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&&!oe&&(Qe="none",dt="none");let ht=g||oe?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",xt=U(H==null?void 0:H.border,dt),Be=U(H==null?void 0:H.shadow,Qe),Le=U(H==null?void 0:H.borderRadius,ht),Ke=ue.scrollTop;r.style.cssText="",We.style.cssText="",he.style.cssText="",j.style.cssText="",ue.style.cssText="",Oe.style.cssText="";let rt=()=>{var Et;if(Ke<=0)return;((Et=ue.ownerDocument.defaultView)!=null?Et:window).requestAnimationFrame(()=>{if(ue.scrollTop===Ke)return;let yt=ue.scrollHeight-ue.clientHeight;yt<=0||(ue.scrollTop=Math.min(Ke,yt))})};if(oe){We.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"),We.style.cssText=`
81
78
  position: fixed !important;
82
79
  inset: 0 !important;
83
80
  width: 100% !important;
@@ -87,9 +84,9 @@ _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
87
84
  padding: 0 !important;
88
85
  display: flex !important;
89
86
  flex-direction: column !important;
90
- z-index: ${et} !important;
87
+ z-index: ${Se} !important;
91
88
  background-color: var(--persona-surface, #ffffff) !important;
92
- `,ye.style.cssText=`
89
+ `,he.style.cssText=`
93
90
  position: relative !important;
94
91
  display: flex !important;
95
92
  flex-direction: column !important;
@@ -102,7 +99,7 @@ _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
102
99
  padding: 0 !important;
103
100
  box-shadow: none !important;
104
101
  border-radius: 0 !important;
105
- `,he.style.cssText=`
102
+ `,j.style.cssText=`
106
103
  display: flex !important;
107
104
  flex-direction: column !important;
108
105
  flex: 1 1 0% !important;
@@ -113,20 +110,20 @@ _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
113
110
  overflow: hidden !important;
114
111
  border-radius: 0 !important;
115
112
  border: none !important;
116
- `,Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",Ke.style.flexShrink="0",E=!0,pt();return}let Ht=(uo=(Bo=n==null?void 0:n.launcher)==null?void 0:Bo.width)!=null?uo:n==null?void 0:n.launcherWidth,D=Ht!=null?Ht:wn;if(!g&&!c)A&&b?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=D,ye.style.maxWidth=D);else if(c)if(Wn(n).reveal==="emerge"){let vt=Wn(n).width;ye.style.width=vt,ye.style.maxWidth=vt}else ye.style.width="100%",ye.style.maxWidth="100%";if(Xn(),ye.style.boxShadow=ze,ye.style.borderRadius=qe,he.style.border=St,he.style.borderRadius=qe,c&&!se&&(B==null?void 0:B.border)===void 0&&(he.style.border="none",Wn(n).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.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%"),ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.maxHeight="100%",ke.style.height="100%",A&&(ke.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",ye.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.overflow="hidden",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",Ke.style.flexShrink="0"),ke.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&&((Yo=Gn[Re])!=null?Yo:Gn["bottom-right"]).split(" ").forEach(vt=>ke.classList.add(vt)),g){let Et=(Vr=(mt=n.launcher)==null?void 0:mt.sidebarWidth)!=null?Vr:"420px";ke.style.cssText=`
113
+ `,ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Oe.style.flexShrink="0",T=!0,rt();return}let Wt=(Ho=(Wo=n==null?void 0:n.launcher)==null?void 0:Wo.width)!=null?Ho:n==null?void 0:n.launcherWidth,D=Wt!=null?Wt:Cn;if(!g&&!c)A&&b?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=D,he.style.maxWidth=D);else if(c)if(Hn(n).reveal==="emerge"){let Et=Hn(n).width;he.style.width=Et,he.style.maxWidth=Et}else he.style.width="100%",he.style.maxWidth="100%";if(Gn(),he.style.boxShadow=Be,he.style.borderRadius=Le,j.style.border=xt,j.style.borderRadius=Le,c&&!oe&&(H==null?void 0:H.border)===void 0&&(j.style.border="none",Hn(n).side==="right"?j.style.borderLeft="1px solid var(--persona-border)":j.style.borderRight="1px solid var(--persona-border)"),b&&(r.style.display="flex",r.style.flexDirection="column",r.style.height="100%",r.style.minHeight="0",A&&(r.style.width="100%"),We.style.display="flex",We.style.flexDirection="column",We.style.flex="1 1 0%",We.style.minHeight="0",We.style.maxHeight="100%",We.style.height="100%",A&&(We.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",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Oe.style.flexShrink="0"),We.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&&((po=Vn[Te])!=null?po:Vn["bottom-right"]).split(" ").forEach(Et=>We.classList.add(Et)),g){let bt=(Nr=(ut=n.launcher)==null?void 0:ut.sidebarWidth)!=null?Nr:"420px";We.style.cssText=`
117
114
  position: fixed !important;
118
115
  top: 0 !important;
119
116
  bottom: 0 !important;
120
- width: ${Et} !important;
117
+ width: ${bt} !important;
121
118
  height: 100vh !important;
122
119
  max-height: 100vh !important;
123
120
  margin: 0 !important;
124
121
  padding: 0 !important;
125
122
  display: flex !important;
126
123
  flex-direction: column !important;
127
- z-index: ${et} !important;
128
- ${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
129
- `,ye.style.cssText=`
124
+ z-index: ${Se} !important;
125
+ ${Ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
126
+ `,he.style.cssText=`
130
127
  position: relative !important;
131
128
  display: flex !important;
132
129
  flex-direction: column !important;
@@ -137,9 +134,9 @@ _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
137
134
  min-height: 0 !important;
138
135
  margin: 0 !important;
139
136
  padding: 0 !important;
140
- box-shadow: ${ze} !important;
141
- border-radius: ${qe} !important;
142
- `,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),he.style.cssText=`
137
+ box-shadow: ${Be} !important;
138
+ border-radius: ${Le} !important;
139
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),j.style.cssText=`
143
140
  display: flex !important;
144
141
  flex-direction: column !important;
145
142
  flex: 1 1 0% !important;
@@ -148,29 +145,29 @@ _Details: ${r.message}_`:n}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
148
145
  min-height: 0 !important;
149
146
  max-height: 100% !important;
150
147
  overflow: hidden !important;
151
- border-radius: ${qe} !important;
152
- border: ${St} !important;
153
- `,Ke.style.cssText=`
148
+ border-radius: ${Le} !important;
149
+ border: ${xt} !important;
150
+ `,Oe.style.cssText=`
154
151
  flex-shrink: 0 !important;
155
152
  border-top: none !important;
156
153
  padding: 8px 16px 12px 16px !important;
157
- `}if(!A&&!c){let Et="max-height: -moz-available !important; max-height: stretch !important;",vt=g?"":"padding-top: 1.25em !important;",qt=g?"":`z-index: ${(Pr=(Or=n.launcher)==null?void 0:Or.zIndex)!=null?Pr:Kr} !important;`;ke.style.cssText+=Et+vt+qt}pt()};Nn(),Do(t,n),Gl(t,n),Kl(t,n);let Bt=[];Bt.push(()=>{document.removeEventListener("keydown",Cn)});let xr=null,yr=null;Bt.push(()=>{xr==null||xr(),xr=null,yr==null||yr(),yr=null}),I&&Bt.push(()=>{I==null||I.disconnect(),I=null}),Bt.push(()=>{Dr==null||Dr(),Dr=null,ao(),Gt&&(Gt.remove(),Gt=null),fe==null||fe.element.style.removeProperty("width"),fe==null||fe.element.style.removeProperty("maxWidth")}),$e&&Bt.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),J==null||J.destroy(),J=null,G==null||G.destroy(),G=null,V=null});let dn=null,To=()=>{dn&&(dn(),dn=null),n.colorScheme==="auto"&&(dn=vl(()=>{Do(t,n)}))};To(),Bt.push(()=>{dn&&(dn(),dn=null)});let Sn=(wf=n.features)==null?void 0:wf.streamAnimation;if(Sn!=null&&Sn.type&&Sn.type!=="none"){let c=js(Sn.type,Sn.plugins);c&&(qp(c,t),Bt.push(()=>gx(t)))}let _n=qx(ee),cn=null,U,Tn=!1,Ee=dx(),pn=new Map,Mn=new Map,Fn=new Map,ts=0,$n=Sl(),Un=0,qn=null,so=!1,Vo=!1,ii=4,rs=24,li=80,va=new Map,Wt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ns=(Cf=(vf=n.voiceRecognition)==null?void 0:vf.autoResume)!=null?Cf:!1,kn=c=>{s.emit("voice:state",{active:Wt.active,source:c,timestamp:Date.now()})},nn=()=>{m(c=>({...c,voiceState:{active:Wt.active,timestamp:Date.now(),manuallyDeactivated:Wt.manuallyDeactivated}}))},di=()=>{var A,B;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=mu(d.voiceState),g=!!c.active,b=Number((B=c.timestamp)!=null?B:0);Wt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<bC&&setTimeout(()=>{var F,$;Wt.active||(Wt.manuallyDeactivated=!1,(($=(F=n.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?U.toggleVoice().then(()=>{Wt.active=U.isVoiceActive(),kn("restore"),U.isVoiceActive()&&H()}):Xo("restore"))},1e3)},ci=()=>U?ly(U.getMessages()).filter(c=>!c.__skipPersist):[];function Ca(c){if(!(i!=null&&i.save))return;let b={messages:c?ly(c):U?ci():[],metadata:d,artifacts:te.artifacts,selectedArtifactId:te.selectedId};try{let A=i.save(b);A instanceof Promise&&A.catch(B=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",B)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let io=null,pi=()=>ke.querySelector("#persona-scroll-container")||Q,jo=()=>{io!==null&&(cancelAnimationFrame(io),io=null),so=!1},os=()=>{qn!==null&&(cancelAnimationFrame(qn),qn=null),Vo=!1,jo()},lo=()=>{if(!hr()||ie){Ut.parentNode&&Ut.remove(),Ut.style.display="none";return}Ut.parentNode!==he&&he.appendChild(Ut),Rt();let c=Us(Q)>0;Ut.style.display=$n.isFollowing()||!c?"none":""},as=()=>{$n.pause()&&(os(),lo())},Mo=()=>{$n.resume(),lo()},ko=(c=!1)=>{$n.isFollowing()&&(!c&&!Tn||(qn!==null&&(cancelAnimationFrame(qn),qn=null),Vo=!0,qn=requestAnimationFrame(()=>{qn=null,Vo=!1,$n.isFollowing()&&ui(pi(),c?220:140)})))},ui=(c,g=500)=>{let b=c.scrollTop,A=Us(c),B=A-b;if(Math.abs(B)<1){Un=c.scrollTop;return}if(Math.abs(B)>=li){jo(),so=!0,c.scrollTop=A,Un=c.scrollTop,so=!1;return}jo();let F=performance.now();so=!0;let $=_=>1-Math.pow(1-_,3),K=_=>{if(!$n.isFollowing()){jo();return}let We=Us(c);We!==A&&(A=We,B=A-b);let Ce=_-F,se=Math.min(Ce/g,1),Re=$(se),_e=b+B*Re;c.scrollTop=_e,Un=c.scrollTop,se<1?io=requestAnimationFrame(K):(c.scrollTop=A,Un=c.scrollTop,io=null,so=!1)};io=requestAnimationFrame(K)},fi=c=>{let g=new Map;c.forEach(b=>{let A=va.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}))}),va.clear(),g.forEach((b,A)=>{va.set(A,b)})},Go=(c,g,b)=>{var St,ze,qe,rt,pt,Ht;let A=document.createElement("div"),F=(()=>{var Je;let D=o.find(pe=>pe.renderLoadingIndicator);if(D!=null&&D.renderLoadingIndicator)return D.renderLoadingIndicator;if((Je=n.loadingIndicator)!=null&&Je.render)return n.loadingIndicator.render})(),$=(D,Je)=>Je==null?!1:typeof Je=="string"?(D.textContent=Je,!0):(D.appendChild(Je),!0),K=new Set,_=new Set,We=o.some(D=>D.renderAskUserQuestion),Ce=[],se=[],Re=n.enableComponentStreaming!==!1,_e=o.some(D=>D.renderApproval)&&n.approval!==!1,et=[];if(g.forEach(D=>{var _t,mn,Tr,Pn,gn,Jo,La,Pa,fr,Qo,Wo,Bo,uo,Yo;K.add(D.id);let Je=We&&wo(D),pe=_e&&D.variant==="approval"&&!!D.approval,ft=!Je&&D.role==="assistant"&&!D.variant&&Re&&Yl(D);if(!pe&&Fn.has(D.id)){let mt=c.querySelector(`#wrapper-${D.id}`);mt==null||mt.removeAttribute("data-preserve-runtime"),Fn.delete(D.id)}if(!ft&&Mn.has(D.id)){let mt=c.querySelector(`#wrapper-${D.id}`);mt==null||mt.removeAttribute("data-preserve-runtime"),Mn.delete(D.id)}let rr=wo(D)?`:${(_t=D.agentMetadata)!=null&&_t.askUserQuestionAnswered?"a":"u"}:${(mn=D.agentMetadata)!=null&&mn.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Yt=lx(D,ts)+rr,cr=Je||pe||ft?null:cx(Ee,D.id,Yt);if(cr){A.appendChild(cr.cloneNode(!0)),wo(D)&&((Tr=D.toolCall)!=null&&Tr.id)&&((Pn=D.agentMetadata)==null?void 0:Pn.awaitingLocalTool)===!0&&!((gn=D.agentMetadata)!=null&&gn.askUserQuestionAnswered)&&(_.add(D.toolCall.id),Ja(D,n,Ue.composerOverlay));return}let wt=null,Lr=o.find(mt=>!!(D.variant==="reasoning"&&mt.renderReasoning||D.variant==="tool"&&mt.renderToolCall||!D.variant&&mt.renderMessage)),fn=(Jo=n.layout)==null?void 0:Jo.messages;if(wo(D)&&((La=D.agentMetadata)==null?void 0:La.askUserQuestionAnswered)===!0){pn.delete(D.id);let mt=c.querySelector(`#wrapper-${D.id}`);mt==null||mt.removeAttribute("data-preserve-runtime");return}if(wo(D)&&((fr=(Pa=n.features)==null?void 0:Pa.askUserQuestion)==null?void 0:fr.enabled)!==!1){let mt=o.find(Vr=>typeof Vr.renderAskUserQuestion=="function");if(mt&&Ze.current){let Vr=pn.get(D.id),Or=Vr!==Yt,Pr=null;if(Or){let{payload:qt,complete:on}=vo(D),vr=D.id,Qn=()=>{var Mr;return(Mr=Ze.current)==null?void 0:Mr.getMessages().find(Jr=>Jr.id===vr)};Pr=mt.renderAskUserQuestion({message:D,payload:qt,complete:on,resolve:Mr=>{var In;let Jr=Qn();Jr&&((In=Ze.current)==null||In.resolveAskUserQuestion(Jr,Mr))},dismiss:()=>{var Jr,In,Zo;let Mr=Qn();(Jr=Mr==null?void 0:Mr.agentMetadata)!=null&&Jr.awaitingLocalTool&&((In=Ze.current)==null||In.markAskUserQuestionResolved(Mr),(Zo=Ze.current)==null||Zo.resolveAskUserQuestion(Mr,"(dismissed)"))},config:n})}let Et=Vr!=null;if(Or&&Pr===null&&!Et){((Qo=D.agentMetadata)==null?void 0:Qo.awaitingLocalTool)===!0&&!((Wo=D.agentMetadata)!=null&&Wo.askUserQuestionAnswered)&&(_.add(D.toolCall.id),Ja(D,n,Ue.composerOverlay));return}let vt=document.createElement("div");vt.className="persona-flex",vt.id=`wrapper-${D.id}`,vt.setAttribute("data-wrapper-id",D.id),vt.setAttribute("data-ask-plugin-stub","true"),vt.setAttribute("data-preserve-runtime","true"),A.appendChild(vt),Ce.push({messageId:D.id,fingerprint:Yt,bubble:Pr});return}else{((Bo=D.agentMetadata)==null?void 0:Bo.awaitingLocalTool)===!0&&!((uo=D.agentMetadata)!=null&&uo.askUserQuestionAnswered)&&(_.add(D.toolCall.id),Ja(D,n,Ue.composerOverlay));return}}else if(pe){let mt=o.find(Et=>typeof Et.renderApproval=="function"),Or=Fn.get(D.id)!==Yt,Pr=null;if(Or&&(mt!=null&&mt.renderApproval)){let Et=D.id,vt=(qt,on)=>{var Qn,Mr,Jr;let vr=(Qn=Ze.current)==null?void 0:Qn.getMessages().find(In=>In.id===Et);vr!=null&&vr.approval&&(vr.approval.toolType==="webmcp"?(Mr=Ze.current)==null||Mr.resolveWebMcpApproval(vr.id,qt):(Jr=Ze.current)==null||Jr.resolveApproval(vr.approval,qt,on))};Pr=mt.renderApproval({message:D,defaultRenderer:()=>Vl(D,n),config:n,approve:qt=>vt("approved",qt),deny:qt=>vt("denied",qt)})}if(Or&&Pr===null){let Et=c.querySelector(`#wrapper-${D.id}`);Et==null||Et.removeAttribute("data-preserve-runtime"),Fn.delete(D.id),wt=Vl(D,n)}else{let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${D.id}`,Et.setAttribute("data-wrapper-id",D.id),Et.setAttribute("data-approval-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),A.appendChild(Et),et.push({messageId:D.id,fingerprint:Yt,bubble:Pr});return}}else if(Lr)if(D.variant==="reasoning"&&D.reasoning&&Lr.renderReasoning){if(!nt)return;wt=Lr.renderReasoning({message:D,defaultRenderer:()=>Zp(D,n),config:n})}else if(D.variant==="tool"&&D.toolCall&&Lr.renderToolCall){if(!Te)return;wt=Lr.renderToolCall({message:D,defaultRenderer:()=>eu(D,n),config:n})}else Lr.renderMessage&&(wt=Lr.renderMessage({message:D,defaultRenderer:()=>{let mt=Va(D,b,fn,n.messageActions,ce,{loadingIndicatorRenderer:F,widgetConfig:n});return D.role!=="user"&&pu(mt,D,n,U),mt},config:n}));if(!wt&&ft){let mt=Zl(D);if(mt){let Vr=Mn.get(D.id),Or=Vr!==Yt,Pr=n.wrapComponentDirectiveInBubble!==!1,Et=null;if(Or){let vt=Ql(mt,{config:n,message:D,transform:b});if(vt)if(Pr){let qt=document.createElement("div");if(qt.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(" "),qt.id=`bubble-${D.id}`,qt.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let on=document.createElement("div");on.className="persona-mb-3 persona-text-sm persona-leading-relaxed",on.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),qt.appendChild(on)}qt.appendChild(vt),Et=qt}else{let qt=document.createElement("div");if(qt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",qt.id=`bubble-${D.id}`,qt.setAttribute("data-message-id",D.id),qt.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let on=document.createElement("div");on.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",on.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),qt.appendChild(on)}qt.appendChild(vt),Et=qt}}if(Et||Vr!=null){let vt=document.createElement("div");vt.className="persona-flex",vt.id=`wrapper-${D.id}`,vt.setAttribute("data-wrapper-id",D.id),vt.setAttribute("data-component-directive-stub","true"),vt.setAttribute("data-preserve-runtime","true"),Pr||vt.classList.add("persona-w-full"),A.appendChild(vt),se.push({messageId:D.id,fingerprint:Yt,bubble:Et});return}}}if(!wt)if(D.variant==="reasoning"&&D.reasoning){if(!nt)return;wt=Zp(D,n)}else if(D.variant==="tool"&&D.toolCall){if(!Te)return;wt=eu(D,n)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;wt=Vl(D,n)}else{let mt=(Yo=n.layout)==null?void 0:Yo.messages;mt!=null&&mt.renderUserMessage&&D.role==="user"?wt=mt.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):mt!=null&&mt.renderAssistantMessage&&D.role==="assistant"?wt=mt.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):wt=Va(D,b,mt,n.messageActions,ce,{loadingIndicatorRenderer:F,widgetConfig:n}),D.role!=="user"&&wt&&pu(wt,D,n,U)}let at=document.createElement("div");at.className="persona-flex",at.id=`wrapper-${D.id}`,at.setAttribute("data-wrapper-id",D.id),D.role==="user"&&at.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&at.classList.add("persona-w-full"),at.appendChild(wt),px(Ee,D.id,Yt,at),A.appendChild(at)}),Ue.composerOverlay&&Ue.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Je=>{let pe=Je.getAttribute("data-persona-ask-sheet-for");pe&&!_.has(pe)&&qo(Ue.composerOverlay,pe)}),(ze=(St=n.features)==null?void 0:St.toolCallDisplay)!=null&&ze.grouped){let D=[],Je=[];g.forEach(pe=>{if(pe.variant==="tool"&&pe.toolCall&&Te){Je.push(pe);return}Je.length>1&&D.push(Je),Je=[]}),Je.length>1&&D.push(Je),D.forEach((pe,ft)=>{var _t,mn;let rr=pe.map(Tr=>Array.from(A.children).find(Pn=>Pn instanceof HTMLElement&&Pn.getAttribute("data-wrapper-id")===Tr.id)).filter(Tr=>!!Tr);if(rr.length<2)return;let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-tool-group-${ft}-${pe[0].id}`,Yt.setAttribute("data-wrapper-id",`tool-group-${ft}-${pe[0].id}`);let cr=document.createElement("div");cr.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",cr.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Lr=`Called ${pe.length} tools`,fn=(mn=(_t=n.toolCall)==null?void 0:_t.renderGroupedSummary)==null?void 0:mn.call(_t,{messages:pe,toolCalls:pe.map(Tr=>Tr.toolCall).filter(Tr=>!!Tr),defaultSummary:Lr,config:n});$(wt,fn)||(wt.textContent=Lr);let at=document.createElement("div");at.className="persona-tool-group-stack persona-flex persona-flex-col",cr.append(wt,at),Yt.appendChild(cr),rr[0].before(Yt),rr.forEach((Tr,Pn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),Pn<rr.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(Tr),at.appendChild(gn)})})}ux(Ee,K);let yt=g.some(D=>D.role==="assistant"&&D.streaming),ot=g[g.length-1],kt=(ot==null?void 0:ot.role)==="assistant"&&!ot.streaming&&ot.variant!=="approval";if(Tn&&g.some(D=>D.role==="user")&&!yt&&!kt){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:xa},Je=o.find(ft=>ft.renderLoadingIndicator),pe=null;if(Je!=null&&Je.renderLoadingIndicator&&(pe=Je.renderLoadingIndicator(D)),pe===null&&((qe=n.loadingIndicator)!=null&&qe.render)&&(pe=n.loadingIndicator.render(D)),pe===null&&(pe=xa()),pe){let ft=document.createElement("div"),rr=((rt=n.loadingIndicator)==null?void 0:rt.showBubble)!==!1;ft.className=rr?["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(" "),ft.setAttribute("data-typing-indicator","true"),ft.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ft.appendChild(pe);let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id="wrapper-typing-indicator",Yt.setAttribute("data-wrapper-id","typing-indicator"),Yt.appendChild(ft),A.appendChild(Yt)}}if(!Tn&&g.length>0){let D=g[g.length-1],Je={config:n,lastMessage:D,messageCount:g.length},pe=o.find(rr=>rr.renderIdleIndicator),ft=null;if(pe!=null&&pe.renderIdleIndicator&&(ft=pe.renderIdleIndicator(Je)),ft===null&&((pt=n.loadingIndicator)!=null&&pt.renderIdle)&&(ft=n.loadingIndicator.renderIdle(Je)),ft){let rr=document.createElement("div"),Yt=((Ht=n.loadingIndicator)==null?void 0:Ht.showBubble)!==!1;rr.className=Yt?["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(" "),rr.setAttribute("data-idle-indicator","true"),rr.appendChild(ft);let cr=document.createElement("div");cr.className="persona-flex",cr.id="wrapper-idle-indicator",cr.setAttribute("data-wrapper-id","idle-indicator"),cr.appendChild(rr),A.appendChild(cr)}}if(Cl(c,A),Ce.length>0)for(let{messageId:D,fingerprint:Je,bubble:pe}of Ce){let ft=c.querySelector(`#wrapper-${D}`);ft&&pe!==null&&(ft.replaceChildren(pe),ft.setAttribute("data-bubble-fp",Je),pn.set(D,Je))}if(pn.size>0)for(let D of pn.keys())K.has(D)||pn.delete(D);if(se.length>0)for(let{messageId:D,fingerprint:Je,bubble:pe}of se){let ft=c.querySelector(`#wrapper-${D}`);ft&&pe!==null&&(ft.replaceChildren(pe),ft.setAttribute("data-bubble-fp",Je),Mn.set(D,Je))}if(Mn.size>0)for(let D of Mn.keys())K.has(D)||Mn.delete(D);if(et.length>0)for(let{messageId:D,fingerprint:Je,bubble:pe}of et){let ft=c.querySelector(`#wrapper-${D}`);ft&&pe!==null&&(ft.replaceChildren(pe),ft.setAttribute("data-bubble-fp",Je),Fn.set(D,Je))}if(Fn.size>0)for(let D of Fn.keys())K.has(D)||Fn.delete(D)},Eo=null,mi=()=>{var b;if(Eo)return;let c=A=>{let B=A.composedPath();B.includes(ke)||tt&&B.includes(tt)||Qt(!1,"user")};Eo=c,((b=t.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},ss=()=>{var g;if(!Eo)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Eo,!0),Eo=null};Bt.push(()=>ss());let Lo=null,gi=()=>{var b;if(Lo)return;let c=A=>{A.key==="Escape"&&(A.isComposing||Qt(!1,"user"))};Lo=c,((b=t.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},is=()=>{var g;if(!Lo)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("keydown",Lo,!0),Lo=null};Bt.push(()=>is());let Po=!1,ls=new Set,hi=()=>{var g,b,A,B;let c=(A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:A.streamAnimation;return c||((B=n.features)==null?void 0:B.streamAnimation)},co=()=>{var kt,St,ze,qe;if(!W())return;let c=Ue.peekBanner,g=Ue.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(kt=U==null?void 0:U.getMessages())!=null?kt:[],A;for(let rt=b.length-1;rt>=0;rt--){let pt=b[rt];if(pt.role==="assistant"&&pt.content){A=pt;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let B=A.content,F=!!A.streaming,$=hi(),K=kl($),_=K.type!=="none"?js(K.type,$==null?void 0:$.plugins):null,We=((St=_==null?void 0:_.isAnimating)==null?void 0:St.call(_,A))===!0,Ce=_!==null&&(F||We);Ce&&_&&!ls.has(_.name)&&(qp(_,t),ls.add(_.name));let se=Ce&&(_!=null&&_.containerClass)?_.containerClass:null,Re=(ze=g.dataset.personaPeekStreamClass)!=null?ze:null;Re&&Re!==se&&(g.classList.remove(Re),delete g.dataset.personaPeekStreamClass),se&&Re!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),Ce?(g.style.setProperty("--persona-stream-step",`${K.speed}ms`),g.style.setProperty("--persona-stream-duration",`${K.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let _e=Ce?El(B,K.buffer,_,A,F):B;if(Ce&&K.placeholder==="skeleton"&&F&&(!_e||!_e.trim())){let rt=document.createElement("div"),pt=Ks();pt.classList.add("persona-pill-peek__skeleton"),rt.appendChild(pt),Cl(g,rt)}else{let rt=Math.max(0,_e.length-100),pt=_e.length>100?_e.slice(-100):_e,Ht=la(pt);if(!Ce||!_){let D=_e.length>100?`\u2026${pt}`:pt;g.textContent!==D&&(g.textContent=D)}else{let D=Ht;(_.wrap==="char"||_.wrap==="word")&&(D=Gs(Ht,_.wrap,`peek-${A.id}`,{skipTags:_.skipTags,startIndex:rt}));let Je=document.createElement("div");if(Je.innerHTML=D,_.useCaret&&pt.length>0){let pe=Ll(),ft=Je.querySelectorAll(".persona-stream-char, .persona-stream-word"),rr=ft[ft.length-1];rr!=null&&rr.parentNode?rr.parentNode.insertBefore(pe,rr.nextSibling):Je.appendChild(pe)}Cl(g,Je),(qe=_.onAfterRender)==null||qe.call(_,{container:g,bubble:c,messageId:A.id,message:A,speed:K.speed,duration:K.duration})}}let ot=Tn||Po;c.classList.toggle("persona-pill-peek--visible",ot)};if(W()){let c=Ue.peekBanner;if(c){let A=B=>{B.preventDefault(),B.stopPropagation(),Qt(!0,"user")};c.addEventListener("pointerdown",A),Bt.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{Po||(Po=!0,co())},b=()=>{Po&&(Po=!1,co())};ye.addEventListener("pointerenter",g),ye.addEventListener("pointerleave",b),Bt.push(()=>{ye.removeEventListener("pointerenter",g),ye.removeEventListener("pointerleave",b)}),tt&&(tt.addEventListener("pointerenter",g),tt.addEventListener("pointerleave",b),Bt.push(()=>{tt.removeEventListener("pointerenter",g),tt.removeEventListener("pointerleave",b)}))}let xi=c=>{var Re,_e,et,yt,ot,kt,St,ze;let g=(_e=(Re=n.launcher)==null?void 0:Re.composerBar)!=null?_e:{},b=(et=g.expandedSize)!=null?et:"anchored",A=(yt=g.bottomOffset)!=null?yt:"16px",B=g.collapsedMaxWidth,F=(ot=g.expandedMaxWidth)!=null?ot:"880px",$=(kt=g.expandedTopOffset)!=null?kt:"5vh",K=(St=g.modalMaxWidth)!=null?St:"880px",_=(ze=g.modalMaxHeight)!=null?ze:"min(90vh, 800px)",We="calc(100vw - 32px)",Ce="var(--persona-pill-area-height, 80px)",se=ke.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",tt){let qe=tt.style;qe.bottom=A,qe.width=B!=null?B:""}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=K,se.maxWidth=We,se.maxHeight=_,se.height=_;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${A} + ${Ce})`,se.top=$,se.width=F,se.maxWidth=We}},Io=()=>{var _,We,Ce,se,Re,_e,et,yt;if(!P())return;if(W()){let kt=(Ce=((We=(_=n.launcher)==null?void 0:_.composerBar)!=null?We:{}).expandedSize)!=null?Ce:"anchored",St=R?"expanded":"collapsed";ke.dataset.state=St,ke.dataset.expandedSize=kt,tt&&(tt.dataset.state=St,tt.dataset.expandedSize=kt),ke.style.removeProperty("display"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),xi(R),he.style.display=R?"flex":"none",Nn(),R?(mi(),gi()):(ss(),is()),co();return}let c=kr(n),g=(se=t.ownerDocument.defaultView)!=null?se:window,b=(_e=(Re=n.launcher)==null?void 0:Re.mobileBreakpoint)!=null?_e:640,A=(yt=(et=n.launcher)==null?void 0:et.mobileFullscreen)!=null?yt:!0,B=g.innerWidth<=b,F=A&&B&&M,$=Wn(n).reveal;R?(ke.style.removeProperty("display"),ke.style.display=c?"flex":"",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),ct?ct.element.style.display="none":ut&&(ut.style.display="none")):(c?c&&($==="overlay"||$==="push")&&!F?(ke.style.removeProperty("display"),ke.style.display="flex",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.setProperty("display","none","important"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.display="",ke.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),ct?ct.element.style.display=c?"none":"":ut&&(ut.style.display=c?"none":""))},Qt=(c,g="user")=>{var F,$;if(!P()||R===c)return;let b=R;R=c,Io();let A=(()=>{var et,yt,ot,kt,St,ze,qe,rt,pt,Ht;let K=(yt=(et=n.launcher)==null?void 0:et.sidebarMode)!=null?yt:!1,_=(ot=t.ownerDocument.defaultView)!=null?ot:window,We=(St=(kt=n.launcher)==null?void 0:kt.mobileFullscreen)!=null?St:!0,Ce=(qe=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?qe:640,se=_.innerWidth<=Ce,Re=kr(n)&&We&&se,_e=W()&&((Ht=(pt=(rt=n.launcher)==null?void 0:rt.composerBar)==null?void 0:pt.expandedSize)!=null?Ht:"fullscreen")==="fullscreen";return K||We&&se&&M||Re||_e})();if(R&&A){if(!xr){let K=t.getRootNode(),_=K instanceof ShadowRoot?K.host:t.closest(".persona-host");_&&(xr=zp(_,($=(F=n.launcher)==null?void 0:F.zIndex)!=null?$:Kr))}yr||(yr=Vp(t.ownerDocument))}else R||(xr==null||xr(),xr=null,yr==null||yr(),yr=null);R&&(br(),ko(!0));let B={open:R,source:g,timestamp:Date.now()};R&&!b?s.emit("widget:opened",B):!R&&b&&s.emit("widget:closed",B),s.emit("widget:state",{open:R,launcherEnabled:M,voiceActive:Wt.active,streaming:U.isStreaming()})},Aa=c=>{Zt(c?"stop":"send"),X&&(X.disabled=c),_n.buttons.forEach(g=>{g.disabled=c}),Ke.dataset.personaComposerStreaming=c?"true":"false",Ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Sa=()=>{Wt.active||xe&&xe.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Sa(),200)});let ds=()=>{var b,A,B,F,$,K,_,We,Ce,se,Re;ue.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",Oe.textContent=(F=(B=n.copy)==null?void 0:B.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",xe.placeholder=(K=($=n.copy)==null?void 0:$.inputPlaceholder)!=null?K:"How can I help...";let c=Q.querySelector("[data-persona-intro-card]");if(c){let _e=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(Q.classList.remove("persona-gap-3"),Q.classList.add("persona-gap-6")):(Q.classList.remove("persona-gap-6"),Q.classList.add("persona-gap-3"))}!((Ce=(We=n.sendButton)==null?void 0:We.useIcon)!=null&&Ce)&&!(U!=null&&U.isStreaming())&&(z.textContent=(Re=(se=n.copy)==null?void 0:se.sendButtonLabel)!=null?Re:"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Jn=null,yi=()=>{Jn==null&&(Jn=setInterval(()=>{let c=Ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Jn),Jn=null;return}let g=Date.now();c.forEach(b=>{let A=Number(b.getAttribute("data-tool-elapsed"));A&&(b.textContent=ji(g-A))})},100))};if(U=new _a(n,{onMessagesChanged(c){Go(Ve,c,ve),yi(),U&&(c.some(B=>B.role==="user")?_n.render([],U,xe,c):_n.render(n.suggestionChips,U,xe,c,n.suggestionChipsConfig)),ko(!Tn),fi(c);let g=[...c].reverse().find(A=>A.role==="user"),b=Wt.lastUserMessageId;g&&g.id!==b&&(Wt.lastUserMessageId=g.id,s.emit("user:message",g)),Wt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Ca(c),co()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};gt(ge,(B=>{var F,$,K,_;return B==="idle"?(F=g.idleText)!=null?F:Gr.idle:B==="connecting"?($=g.connectingText)!=null?$:Gr.connecting:B==="connected"?(K=g.connectedText)!=null?K:Gr.connected:B==="error"?(_=g.errorText)!=null?_:Gr.error:Gr[B]})(c),g,c)},onStreamingChanged(c){Tn=c,Aa(c),U&&Go(Ve,U.getMessages(),ve),c||ko(!0),co()},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(),ae();break;case"speaking":Y(),me();break;default:c==="idle"&&U.isBargeInActive()?(Y(),H(),X==null||X.setAttribute("aria-label","End voice session")):(Wt.active=!1,Y(),kn("system"),nn());break}},onArtifactsState(c){te=c,ln(),Ca()}}),Ze.current=U,((Sf=(Af=n.voiceRecognition)==null?void 0:Af.provider)==null?void 0:Sf.type)==="runtype")try{U.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&U.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(G||n.onSSEEvent)&&U.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,c,g),Ae==null||Ae.processEvent(c,g),G==null||G.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=mu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length&&U.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&U.hydrateArtifacts(c.artifacts,(A=c.selectedArtifactId)!=null?A:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let cs=()=>{var g,b,A;!W()||R||!((A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||A)||Qt(!0,"auto")},ps=c=>{var B;if(c.preventDefault(),U.isStreaming()){U.cancel(),Ae==null||Ae.reset(),J==null||J.update();return}let g=xe.value.trim(),b=(B=ht==null?void 0:ht.hasAttachments())!=null?B:!1;if(!g&&!b)return;cs();let A;b&&(A=[],A.push(...ht.getContentParts()),g&&A.push(Ds(g))),xe.value="",xe.style.height="auto",Ko(),U.sendMessage(g,{contentParts:A}),b&&ht.clearAttachments()},bi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},Ta={...Al},Ma=!1,Ko=()=>{Ta={...Al}},wi=()=>U.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),vi=c=>{if(!xe)return;Ma=!0,xe.value=c,xe.dispatchEvent(new Event("input",{bubbles:!0})),Ma=!1;let g=xe.value.length;xe.setSelectionRange(g,g)},us=()=>{Ma||Ko()},fs=c=>{if(xe){if(bi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=xe.selectionStart===0&&xe.selectionEnd===0,b=ix({direction:c.key==="ArrowUp"?"up":"down",history:wi(),currentValue:xe.value,atStart:g,state:Ta});if(Ta=b.state,b.handled){c.preventDefault(),b.value!==void 0&&vi(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(U.isStreaming()){c.preventDefault();return}Ko(),c.preventDefault(),z.click()}}},ms=c=>{c.key!=="Escape"||c.isComposing||U.isStreaming()&&c.composedPath().includes(he)&&(U.cancel(),Ae==null||Ae.reset(),J==null||J.update(),Ko(),c.preventDefault(),c.stopImmediatePropagation())},gs=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!ht)return;let g=vC(c.clipboardData);g.length!==0&&(c.preventDefault(),await ht.handleFiles(g))},Xr=null,un=!1,po=null,Ct=null,hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Xo=(c="user")=>{var F,$,K,_,We,Ce,se;if(un||U.isStreaming())return;let g=hs();if(!g)return;Xr=new g;let A=($=((F=n.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;Xr.continuous=!0,Xr.interimResults=!0,Xr.lang="en-US";let B=xe.value;Xr.onresult=Re=>{let _e="",et="";for(let ot=0;ot<Re.results.length;ot++){let kt=Re.results[ot],St=kt[0].transcript;kt.isFinal?_e+=St+" ":et=St}let yt=B+_e+et;xe.value=yt,po&&clearTimeout(po),(_e||et)&&(po=window.setTimeout(()=>{let ot=xe.value.trim();ot&&Xr&&un&&(zn(),xe.value="",xe.style.height="auto",U.sendMessage(ot,{viaVoice:!0}))},A))},Xr.onerror=Re=>{Re.error!=="no-speech"&&zn()},Xr.onend=()=>{if(un){let Re=xe.value.trim();Re&&Re!==B.trim()&&(xe.value="",xe.style.height="auto",U.sendMessage(Re,{viaVoice:!0})),zn()}};try{if(Xr.start(),un=!0,Wt.active=!0,c!=="system"&&(Wt.manuallyDeactivated=!1),kn(c),nn(),X){let Re=(K=n.voiceRecognition)!=null?K:{};Ct={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:(_=Re.iconName)!=null?_:"mic",iconSize:parseFloat((se=(Ce=Re.iconSize)!=null?Ce:(We=n.sendButton)==null?void 0:We.size)!=null?se:"40")||24};let _e=Re.recordingBackgroundColor,et=Re.recordingIconColor,yt=Re.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",X.style.color=et!=null?et:"var(--persona-voice-recording-indicator, #ffffff)",et){let ot=X.querySelector("svg");ot&&ot.setAttribute("stroke",et)}yt&&(X.style.borderColor=yt),X.setAttribute("aria-label","Stop voice recognition")}}catch{zn("system")}},zn=(c="user")=>{if(un){if(un=!1,po&&(clearTimeout(po),po=null),Xr){try{Xr.stop()}catch{}Xr=null}if(Wt.active=!1,kn(c),nn(),X){if(X.classList.remove("persona-voice-recording"),Ct){X.style.backgroundColor=Ct.backgroundColor,X.style.color=Ct.color,X.style.borderColor=Ct.borderColor;let g=X.querySelector("svg");g&&g.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}X.setAttribute("aria-label","Start voice recognition")}}},ka=(c,g)=>{var kt,St,ze,qe,rt,pt,Ht,D;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((kt=c==null?void 0:c.provider)==null?void 0:kt.type)==="runtype";if(!(b||A))return null;let F=v("div","persona-send-button-wrapper"),$=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let K=(St=c==null?void 0:c.iconName)!=null?St:"mic",_=(ze=g==null?void 0:g.size)!=null?ze:"40px",We=(qe=c==null?void 0:c.iconSize)!=null?qe:_,Ce=parseFloat(We)||24,se=(rt=c==null?void 0:c.backgroundColor)!=null?rt:g==null?void 0:g.backgroundColor,Re=(pt=c==null?void 0:c.iconColor)!=null?pt:g==null?void 0:g.textColor;$.style.width=We,$.style.height=We,$.style.minWidth=We,$.style.minHeight=We,$.style.fontSize="18px",$.style.lineHeight="1",Re?$.style.color=Re:$.style.color="var(--persona-text, #111827)";let et=Be(K,Ce,Re||"currentColor",1.5);et?$.appendChild(et):$.textContent="\u{1F3A4}",se?$.style.backgroundColor=se:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),F.appendChild($);let yt=(Ht=c==null?void 0:c.tooltipText)!=null?Ht:"Start voice recognition";if(((D=c==null?void 0:c.showTooltip)!=null?D:!1)&&yt){let Je=v("div","persona-send-button-tooltip");Je.textContent=yt,F.appendChild(Je)}return{micButton:$,micButtonWrapper:F}},lt=()=>{var g,b,A,B,F;if(!X||Ct)return;let c=(g=n.voiceRecognition)!=null?g:{};Ct={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((F=(B=c.iconSize)!=null?B:(A=n.sendButton)==null?void 0:A.size)!=null?F:"40")||24}},L=(c,g)=>{var F,$,K,_,We;if(!X)return;let b=X.querySelector("svg");b&&b.remove();let A=(We=Ct==null?void 0:Ct.iconSize)!=null?We:parseFloat((_=(K=(F=n.voiceRecognition)==null?void 0:F.iconSize)!=null?K:($=n.sendButton)==null?void 0:$.size)!=null?_:"40")||24,B=Be(c,A,g,1.5);B&&X.appendChild(B)},q=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},H=()=>{var B;if(!X)return;lt();let c=(B=n.voiceRecognition)!=null?B:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,A=c.recordingBorderColor;if(q(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",X.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let F=X.querySelector("svg");F&&F.setAttribute("stroke",b)}A&&(X.style.borderColor=A),X.setAttribute("aria-label","Stop voice recognition")},ae=()=>{var K,_,We,Ce,se,Re,_e,et;if(!X)return;lt();let c=(K=n.voiceRecognition)!=null?K:{},g=U.getVoiceInterruptionMode(),b=(_=c.processingIconName)!=null?_:"loader",A=(Ce=(We=c.processingIconColor)!=null?We:Ct==null?void 0:Ct.color)!=null?Ce:"",B=(Re=(se=c.processingBackgroundColor)!=null?se:Ct==null?void 0:Ct.backgroundColor)!=null?Re:"",F=(et=(_e=c.processingBorderColor)!=null?_e:Ct==null?void 0:Ct.borderColor)!=null?et:"";q(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=B,X.style.borderColor=F;let $=A||"currentColor";X.style.color=$,L(b,$),X.setAttribute("aria-label","Processing voice input"),g==="none"&&(X.style.cursor="default")},me=()=>{var We,Ce,se,Re,_e,et,yt,ot,kt,St,ze,qe;if(!X)return;lt();let c=(We=n.voiceRecognition)!=null?We:{},g=U.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(Ce=c.speakingIconName)!=null?Ce:b,B=(et=c.speakingIconColor)!=null?et:g==="barge-in"?(Re=(se=c.recordingIconColor)!=null?se:Ct==null?void 0:Ct.color)!=null?Re:"":(_e=Ct==null?void 0:Ct.color)!=null?_e:"",F=(kt=c.speakingBackgroundColor)!=null?kt:g==="barge-in"?(yt=c.recordingBackgroundColor)!=null?yt:"var(--persona-voice-recording-bg, #ef4444)":(ot=Ct==null?void 0:Ct.backgroundColor)!=null?ot:"",$=(qe=c.speakingBorderColor)!=null?qe:g==="barge-in"?(St=c.recordingBorderColor)!=null?St:"":(ze=Ct==null?void 0:Ct.borderColor)!=null?ze:"";q(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=F,X.style.borderColor=$;let K=B||"currentColor";X.style.color=K,L(A,K);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",_),g==="none"&&(X.style.cursor="default"),g==="barge-in"&&X.classList.add("persona-voice-recording")},Y=()=>{var c,g,b;X&&(q(),Ct&&(X.style.backgroundColor=(c=Ct.backgroundColor)!=null?c:"",X.style.color=(g=Ct.color)!=null?g:"",X.style.borderColor=(b=Ct.borderColor)!=null?b:"",L(Ct.iconName,Ct.color||"currentColor"),Ct=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},Fe=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=U.getVoiceStatus(),A=U.getVoiceInterruptionMode();if(A==="none"&&(b==="processing"||b==="speaking"))return;if(A==="cancel"&&(b==="processing"||b==="speaking")){U.stopVoicePlayback();return}if(U.isBargeInActive()){U.stopVoicePlayback(),U.deactivateBargeIn().then(()=>{Wt.active=!1,Wt.manuallyDeactivated=!0,nn(),kn("user"),Y()});return}U.toggleVoice().then(()=>{Wt.active=U.isVoiceActive(),Wt.manuallyDeactivated=!U.isVoiceActive(),nn(),kn("user"),U.isVoiceActive()?H():Y()});return}if(un){let b=xe.value.trim();Wt.manuallyDeactivated=!0,nn(),zn("user"),b&&(xe.value="",xe.style.height="auto",U.sendMessage(b))}else Wt.manuallyDeactivated=!1,nn(),Xo("user")};ur=Fe,X&&(X.addEventListener("click",Fe),Bt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(U.isVoiceActive()&&U.toggleVoice(),Y()):zn("system"),X&&X.removeEventListener("click",Fe)}));let Ye=s.on("assistant:complete",()=>{ns&&(Wt.active||Wt.manuallyDeactivated||ns==="assistant"&&!Wt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Wt.active&&!Wt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?U.toggleVoice().then(()=>{Wt.active=U.isVoiceActive(),kn("auto"),U.isVoiceActive()&&H()}):Xo("auto"))},600))});Bt.push(Ye);let At=s.on("action:resubmit",()=>{setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)});Bt.push(At);let dt=()=>{Qt(!R,"user")},ct=null,ut=null;if(M&&!W()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Js(n,dt).element,onToggle:dt});g&&(ut=g)}ut||(ct=Js(n,dt))}ct?t.appendChild(ct.element):ut&&t.appendChild(ut),Io(),_n.render(n.suggestionChips,U,xe,void 0,n.suggestionChipsConfig),ds(),Aa(U.isStreaming()),ko(!0),di(),T&&(!M||W()?setTimeout(()=>Sa(),0):R&&setTimeout(()=>Sa(),200));let br=()=>{var _,We,Ce,se,Re,_e,et,yt,ot,kt,St,ze,qe,rt,pt,Ht,D,Je,pe,ft,rr,Yt;if(W()){Rt(),Io();return}let c=kr(n),g=(We=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?We:!1,b=c||g||((se=(Ce=n.launcher)==null?void 0:Ce.fullHeight)!=null?se:!1),A=(Re=t.ownerDocument.defaultView)!=null?Re:window,B=(et=(_e=n.launcher)==null?void 0:_e.mobileFullscreen)!=null?et:!0,F=(ot=(yt=n.launcher)==null?void 0:yt.mobileBreakpoint)!=null?ot:640,$=A.innerWidth<=F,K=B&&$&&M;try{if(K){Nn(),Do(t,n);return}if(E&&(E=!1,Nn(),Do(t,n)),!M&&!c){ye.style.height="",ye.style.width="";return}if(!g&&!c){let cr=(St=(kt=n==null?void 0:n.launcher)==null?void 0:kt.width)!=null?St:n==null?void 0:n.launcherWidth,wt=cr!=null?cr:wn;ye.style.width=wt,ye.style.maxWidth=wt}if(Xn(),!b){let cr=A.innerHeight,wt=64,Lr=(qe=(ze=n.launcher)==null?void 0:ze.heightOffset)!=null?qe:0,fn=Math.max(200,cr-wt),at=Math.min(640,fn),_t=Math.max(200,at-Lr);ye.style.height=`${_t}px`}}finally{if(Rt(),Io(),R&&M){let wt=((rt=t.ownerDocument.defaultView)!=null?rt:window).innerWidth<=((Ht=(pt=n.launcher)==null?void 0:pt.mobileBreakpoint)!=null?Ht:640),Lr=(Je=(D=n.launcher)==null?void 0:D.sidebarMode)!=null?Je:!1,fn=(ft=(pe=n.launcher)==null?void 0:pe.mobileFullscreen)!=null?ft:!0,at=kr(n)&&fn&&wt,_t=Lr||fn&&wt&&M||at;if(_t&&!yr){let mn=t.getRootNode(),Tr=mn instanceof ShadowRoot?mn.host:t.closest(".persona-host");Tr&&!xr&&(xr=zp(Tr,(Yt=(rr=n.launcher)==null?void 0:rr.zIndex)!=null?Yt:Kr)),yr=Vp(t.ownerDocument)}else _t||(xr==null||xr(),xr=null,yr==null||yr(),yr=null)}}};br();let zt=(Tf=t.ownerDocument.defaultView)!=null?Tf:window;if(zt.addEventListener("resize",br),Bt.push(()=>zt.removeEventListener("resize",br)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Rt()});c.observe(Ke),Bt.push(()=>c.disconnect())}Un=Q.scrollTop;let Xt=Q.scrollHeight,Er=()=>{let c=Q.scrollTop,g=Q.scrollHeight,b=g<Xt;Xt=g;let{action:A,nextLastScrollTop:B}=Tl({following:$n.isFollowing(),currentScrollTop:c,lastScrollTop:Un,nearBottom:qs(Q,rs),userScrollThreshold:ii,isAutoScrolling:so||Vo||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Un=B,A==="resume"){Mo();return}A==="pause"&&as()};Q.addEventListener("scroll",Er,{passive:!0}),Bt.push(()=>Q.removeEventListener("scroll",Er));let zr=c=>{let g=Ml({following:$n.isFollowing(),deltaY:c.deltaY,nearBottom:qs(Q,rs),resumeWhenNearBottom:!0});g==="pause"?as():g==="resume"&&Mo()};Q.addEventListener("wheel",zr,{passive:!0}),Bt.push(()=>Q.removeEventListener("wheel",zr)),Ut.addEventListener("click",()=>{Q.scrollTop=Q.scrollHeight,Un=Q.scrollTop,Mo(),ko(!0)}),Bt.push(()=>Ut.remove()),Bt.push(()=>{os()});let _r=()=>{Z&&(cn&&(Z.removeEventListener("click",cn),cn=null),P()?(Z.style.display="",cn=()=>{Qt(!1,"user")},Z.addEventListener("click",cn)):Z.style.display="none")};_r(),(()=>{let{clearChatButton:c}=Ue;c&&c.addEventListener("click",()=>{U.clearMessages(),Ee.clear(),Mo(),qo(Ue.composerOverlay);try{localStorage.removeItem(Za),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Za}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Za)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(),G==null||G.clear(),Ae==null||Ae.reset(),J==null||J.update()})})(),Le&&Le.addEventListener("submit",ps),xe==null||xe.addEventListener("keydown",fs),xe==null||xe.addEventListener("input",us),xe==null||xe.addEventListener("paste",gs);let En=(Mf=t.ownerDocument)!=null?Mf:document;En.addEventListener("keydown",ms,!0);let Iu="persona-attachment-drop-active",xs=0,id=()=>{xs=0,he.classList.remove(Iu)},Ea=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&ht!==null},Ru=c=>{!rd(c.dataTransfer)||!Ea()||(xs++,xs===1&&he.classList.add(Iu))},Wu=c=>{!rd(c.dataTransfer)||!Ea()||(xs--,xs<=0&&id())},Bu=c=>{!rd(c.dataTransfer)||!Ea()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Hu=c=>{var b;if(!rd(c.dataTransfer)||!Ea())return;c.preventDefault(),c.stopPropagation(),id();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&ht.handleFiles(g)},Ro=!0;he.addEventListener("dragenter",Ru,Ro),he.addEventListener("dragleave",Wu,Ro),t.addEventListener("dragover",Bu,Ro),t.addEventListener("drop",Hu,Ro);let Ci=t.ownerDocument,Du=c=>{Ea()&&c.preventDefault()},Ou=c=>{Ea()&&c.preventDefault()};Ci.addEventListener("dragover",Du),Ci.addEventListener("drop",Ou),Bt.push(()=>{Le&&Le.removeEventListener("submit",ps),xe==null||xe.removeEventListener("keydown",fs),xe==null||xe.removeEventListener("input",us),xe==null||xe.removeEventListener("paste",gs),En.removeEventListener("keydown",ms,!0)}),Bt.push(()=>{he.removeEventListener("dragenter",Ru,Ro),he.removeEventListener("dragleave",Wu,Ro),t.removeEventListener("dragover",Bu,Ro),t.removeEventListener("drop",Hu,Ro),Ci.removeEventListener("dragover",Du),Ci.removeEventListener("drop",Ou),id()}),Bt.push(()=>{U.cancel()}),ct?Bt.push(()=>{ct==null||ct.destroy()}):ut&&Bt.push(()=>{ut==null||ut.remove()});let Sr={update(c){var vr,Qn,Mr,Jr,In,Zo,ea,Ai,ys,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,Tg,Mg,kg,Eg;let g=n.toolCall,b=n.messageActions,A=(vr=n.layout)==null?void 0:vr.messages,B=n.colorScheme,F=n.loadingIndicator,$=n.iterationDisplay,K=(Qn=n.features)==null?void 0:Qn.showReasoning,_=(Mr=n.features)==null?void 0:Mr.showToolCalls,We=(Jr=n.features)==null?void 0:Jr.toolCallDisplay,Ce=(In=n.features)==null?void 0:In.reasoningDisplay;n={...n,...c},Nn(),Do(t,n),Gl(t,n),Kl(t,n),ln(),n.colorScheme!==B&&To();let se=ri.getForInstance(n.plugins);o.length=0,o.push(...se),M=(ea=(Zo=n.launcher)==null?void 0:Zo.enabled)!=null?ea:!0,k=(ys=(Ai=n.launcher)==null?void 0:Ai.autoExpand)!=null?ys:!1,nt=(Bf=(Wf=n.features)==null?void 0:Wf.showReasoning)!=null?Bf:!0,Te=(Df=(Hf=n.features)==null?void 0:Hf.showToolCalls)!=null?Df:!0,Se=(Nf=(Of=n.features)==null?void 0:Of.scrollToBottom)!=null?Nf:{},dr(),lo();let Re=$e;if($e=(Ff=(_f=n.features)==null?void 0:_f.showEventStreamToggle)!=null?Ff:!1,$e&&!Re){if(G||(V=new ei(He),G=new Zs(be,V),Ae=Ae!=null?Ae:new ti,V.open().then(()=>G==null?void 0:G.restore()).catch(()=>{}),U.setSSEEventCallback((ne,$t)=>{var ar;(ar=n.onSSEEvent)==null||ar.call(n,ne,$t),Ae==null||Ae.processEvent(ne,$t),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify($t)})})),!bt&&je){let ne=(Uf=($f=n.features)==null?void 0:$f.eventStream)==null?void 0:Uf.classNames,$t="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=v("button",$t),bt.style.width="28px",bt.style.height="28px",bt.style.color=rn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let ar=Be("activity","18px","currentColor",1.5);ar&&bt.appendChild(ar);let Tt=Ue.clearChatButtonWrapper,Kt=Ue.closeButtonWrapper,Ir=Tt||Kt;Ir&&Ir.parentNode===je?je.insertBefore(bt,Ir):je.appendChild(bt),bt.addEventListener("click",()=>{ie?Ur():Br()})}}else!$e&&Re&&(Ur(),bt&&(bt.remove(),bt=null),G==null||G.clear(),V==null||V.destroy(),G=null,V=null,Ae==null||Ae.reset(),Ae=null);if(((qf=n.launcher)==null?void 0:qf.enabled)===!1&&ct&&(ct.destroy(),ct=null),((zf=n.launcher)==null?void 0:zf.enabled)===!1&&ut&&(ut.remove(),ut=null),((Vf=n.launcher)==null?void 0:Vf.enabled)!==!1&&!ct&&!ut){let ne=o.find($t=>$t.renderLauncher);if(ne!=null&&ne.renderLauncher){let $t=ne.renderLauncher({config:n,defaultRenderer:()=>Js(n,dt).element,onToggle:dt});$t&&(ut=$t,t.appendChild(ut))}ut||(ct=Js(n,dt),t.appendChild(ct.element))}ct&&ct.update(n),Ie&&((jf=n.launcher)==null?void 0:jf.title)!==void 0&&(Ie.textContent=n.launcher.title),Ne&&((Gf=n.launcher)==null?void 0:Gf.subtitle)!==void 0&&(Ne.textContent=n.launcher.subtitle);let _e=(Kf=n.layout)==null?void 0:Kf.header;if((_e==null?void 0:_e.layout)!==w&&je){let ne=_e?qa(n,_e,{showClose:P(),onClose:()=>Qt(!1,"user")}):bo({config:n,showClose:P(),onClose:()=>Qt(!1,"user")});je.replaceWith(ne.header),je=ne.header,O=ne.iconHolder,Ie=ne.headerTitle,Ne=ne.headerSubtitle,Z=ne.closeButton,w=_e==null?void 0:_e.layout}else if(_e&&(O&&(O.style.display=_e.showIcon===!1?"none":""),Ie&&(Ie.style.display=_e.showTitle===!1?"none":""),Ne&&(Ne.style.display=_e.showSubtitle===!1?"none":""),Z&&(Z.style.display=_e.showCloseButton===!1?"none":""),Ue.clearChatButtonWrapper)){let ne=_e.showClearChat;if(ne!==void 0){Ue.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:$t}=Ue;$t&&!$t.classList.contains("persona-absolute")&&(ne?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"))}}let yt=((Xf=n.layout)==null?void 0:Xf.showHeader)!==!1;je&&(je.style.display=yt?"":"none");let ot=((Jf=n.layout)==null?void 0:Jf.showFooter)!==!1;Ke&&(Ke.style.display=ot?"":"none"),Rt(),lo(),M!==C?M?Qt(k,"auto"):(R=!0,Io()):k!==h&&Qt(k,"auto"),h=k,C=M,br(),_r();let ze=JSON.stringify(c.toolCall)!==JSON.stringify(g),qe=JSON.stringify(n.messageActions)!==JSON.stringify(b),rt=JSON.stringify((Qf=n.layout)==null?void 0:Qf.messages)!==JSON.stringify(A),pt=((Yf=n.loadingIndicator)==null?void 0:Yf.render)!==(F==null?void 0:F.render)||((Zf=n.loadingIndicator)==null?void 0:Zf.renderIdle)!==(F==null?void 0:F.renderIdle)||((em=n.loadingIndicator)==null?void 0:em.showBubble)!==(F==null?void 0:F.showBubble),Ht=n.iterationDisplay!==$,D=((rm=(tm=n.features)==null?void 0:tm.showReasoning)!=null?rm:!0)!==(K!=null?K:!0)||((om=(nm=n.features)==null?void 0:nm.showToolCalls)!=null?om:!0)!==(_!=null?_:!0)||JSON.stringify((am=n.features)==null?void 0:am.toolCallDisplay)!==JSON.stringify(We)||JSON.stringify((sm=n.features)==null?void 0:sm.reasoningDisplay)!==JSON.stringify(Ce);(ze||qe||rt||pt||Ht||D)&&U&&(ts++,Go(Ve,U.getMessages(),ve));let pe=(im=n.launcher)!=null?im:{},ft=(lm=pe.headerIconHidden)!=null?lm:!1,rr=(cm=(dm=n.layout)==null?void 0:dm.header)==null?void 0:cm.showIcon,Yt=ft||rr===!1,cr=pe.headerIconName,wt=(pm=pe.headerIconSize)!=null?pm:"48px";if(O){let ne=he.querySelector(".persona-border-b-persona-divider"),$t=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Yt)O.style.display="none",ne&&$t&&!ne.contains($t)&&ne.insertBefore($t,ne.firstChild);else{if(O.style.display="",O.style.height=wt,O.style.width=wt,ne&&$t&&(ne.contains(O)?O.nextSibling!==$t&&(O.remove(),ne.insertBefore(O,$t)):ne.insertBefore(O,$t)),cr){let Tt=parseFloat(wt)||24,Kt=Be(cr,Tt*.6,"#ffffff",2);Kt?O.replaceChildren(Kt):O.textContent=(um=pe.agentIconText)!=null?um:"\u{1F4AC}"}else if(pe.iconUrl){let Tt=O.querySelector("img");if(Tt)Tt.src=pe.iconUrl,Tt.style.height=wt,Tt.style.width=wt;else{let Kt=document.createElement("img");Kt.src=pe.iconUrl,Kt.alt="",Kt.className="persona-rounded-xl persona-object-cover",Kt.style.height=wt,Kt.style.width=wt,O.replaceChildren(Kt)}}else{let Tt=O.querySelector("svg"),Kt=O.querySelector("img");(Tt||Kt)&&O.replaceChildren(),O.textContent=(fm=pe.agentIconText)!=null?fm:"\u{1F4AC}"}let ar=O.querySelector("img");ar&&(ar.style.height=wt,ar.style.width=wt)}}let Lr=(gm=(mm=n.layout)==null?void 0:mm.header)==null?void 0:gm.showTitle,fn=(xm=(hm=n.layout)==null?void 0:hm.header)==null?void 0:xm.showSubtitle;if(Ie&&(Ie.style.display=Lr===!1?"none":""),Ne&&(Ne.style.display=fn===!1?"none":""),Z){((bm=(ym=n.layout)==null?void 0:ym.header)==null?void 0:bm.showCloseButton)===!1?Z.style.display="none":Z.style.display="";let $t=(wm=pe.closeButtonSize)!=null?wm:"32px",ar=(vm=pe.closeButtonPlacement)!=null?vm:"inline";Z.style.height=$t,Z.style.width=$t;let{closeButtonWrapper:Tt}=Ue,Kt=ar==="top-right",Ir=Tt==null?void 0:Tt.classList.contains("persona-absolute");if(Tt&&Kt!==Ir)if(Tt.remove(),Kt)Tt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",he.style.position="relative",he.appendChild(Tt);else{let Lt=(Am=(Cm=pe.clearChat)==null?void 0:Cm.placement)!=null?Am:"inline",Rr=(Tm=(Sm=pe.clearChat)==null?void 0:Sm.enabled)!=null?Tm:!0;Tt.className=Rr&&Lt==="inline"?"":"persona-ml-auto";let an=he.querySelector(".persona-border-b-persona-divider");an&&an.appendChild(Tt)}if(Z.style.color=pe.closeButtonColor||rn.actionIconColor,pe.closeButtonBackgroundColor?(Z.style.backgroundColor=pe.closeButtonBackgroundColor,Z.classList.remove("hover:persona-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Lt=pe.closeButtonBorderWidth||"0px",Rr=pe.closeButtonBorderColor||"transparent";Z.style.border=`${Lt} solid ${Rr}`,Z.classList.remove("persona-border-none")}else Z.style.border="",Z.classList.add("persona-border-none");pe.closeButtonBorderRadius?(Z.style.borderRadius=pe.closeButtonBorderRadius,Z.classList.remove("persona-rounded-full")):(Z.style.borderRadius="",Z.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(Z.style.paddingLeft=pe.closeButtonPaddingX,Z.style.paddingRight=pe.closeButtonPaddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),pe.closeButtonPaddingY?(Z.style.paddingTop=pe.closeButtonPaddingY,Z.style.paddingBottom=pe.closeButtonPaddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let jr=(Mm=pe.closeButtonIconName)!=null?Mm:"x",Vn=(km=pe.closeButtonIconText)!=null?km:"\xD7";Z.innerHTML="";let Qr=Be(jr,"28px","currentColor",1);Qr?Z.appendChild(Qr):Z.textContent=Vn;let wr=(Em=pe.closeButtonTooltipText)!=null?Em:"Close chat",hn=(Lm=pe.closeButtonShowTooltip)!=null?Lm:!0;if(Z.setAttribute("aria-label",wr),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),hn&&wr)){let Lt=null,Rr=()=>{if(Lt||!Z)return;let ta=Z.ownerDocument,bs=ta.body;if(!bs)return;Lt=ro(ta,"div","persona-clear-chat-tooltip"),Lt.textContent=wr;let ws=ro(ta,"div");ws.className="persona-clear-chat-tooltip-arrow",Lt.appendChild(ws);let ra=Z.getBoundingClientRect();Lt.style.position="fixed",Lt.style.zIndex=String(Oo),Lt.style.left=`${ra.left+ra.width/2}px`,Lt.style.top=`${ra.top-8}px`,Lt.style.transform="translate(-50%, -100%)",bs.appendChild(Lt)},an=()=>{Lt&&Lt.parentNode&&(Lt.parentNode.removeChild(Lt),Lt=null)};Tt.addEventListener("mouseenter",Rr),Tt.addEventListener("mouseleave",an),Z.addEventListener("focus",Rr),Z.addEventListener("blur",an),Tt._cleanupTooltip=()=>{an(),Tt&&(Tt.removeEventListener("mouseenter",Rr),Tt.removeEventListener("mouseleave",an)),Z&&(Z.removeEventListener("focus",Rr),Z.removeEventListener("blur",an))}}}let{clearChatButton:at,clearChatButtonWrapper:_t}=Ue;if(at){let ne=(Pm=pe.clearChat)!=null?Pm:{},$t=(Im=ne.enabled)!=null?Im:!0,ar=(Wm=(Rm=n.layout)==null?void 0:Rm.header)==null?void 0:Wm.showClearChat,Tt=ar!==void 0?ar:$t,Kt=(Bm=ne.placement)!=null?Bm:"inline";if(_t){_t.style.display=Tt?"":"none";let{closeButtonWrapper:Ir}=Ue;!W()&&Ir&&!Ir.classList.contains("persona-absolute")&&(Tt?Ir.classList.remove("persona-ml-auto"):Ir.classList.add("persona-ml-auto"));let jr=Kt==="top-right",Vn=_t.classList.contains("persona-absolute");if(!W()&&jr!==Vn&&Tt){if(_t.remove(),jr)_t.className="persona-absolute persona-top-4 persona-z-50",_t.style.right="48px",he.style.position="relative",he.appendChild(_t);else{_t.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",_t.style.right="";let wr=he.querySelector(".persona-border-b-persona-divider"),hn=Ue.closeButtonWrapper;wr&&hn&&hn.parentElement===wr?wr.insertBefore(_t,hn):wr&&wr.appendChild(_t)}let Qr=Ue.closeButtonWrapper;Qr&&!Qr.classList.contains("persona-absolute")&&(jr?Qr.classList.add("persona-ml-auto"):Qr.classList.remove("persona-ml-auto"))}}if(Tt){if(!W()){let Lt=(Hm=ne.size)!=null?Hm:"32px";at.style.height=Lt,at.style.width=Lt}let Ir=(Dm=ne.iconName)!=null?Dm:"refresh-cw",jr=(Om=ne.iconColor)!=null?Om:"";at.style.color=jr||rn.actionIconColor,at.innerHTML="";let Vn=W()?"14px":"20px",Qr=Be(Ir,Vn,"currentColor",2);if(Qr&&at.appendChild(Qr),ne.backgroundColor?(at.style.backgroundColor=ne.backgroundColor,at.classList.remove("hover:persona-bg-gray-100")):(at.style.backgroundColor="",at.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let Lt=ne.borderWidth||"0px",Rr=ne.borderColor||"transparent";at.style.border=`${Lt} solid ${Rr}`,at.classList.remove("persona-border-none")}else at.style.border="",at.classList.add("persona-border-none");ne.borderRadius?(at.style.borderRadius=ne.borderRadius,at.classList.remove("persona-rounded-full")):(at.style.borderRadius="",at.classList.add("persona-rounded-full")),ne.paddingX?(at.style.paddingLeft=ne.paddingX,at.style.paddingRight=ne.paddingX):(at.style.paddingLeft="",at.style.paddingRight=""),ne.paddingY?(at.style.paddingTop=ne.paddingY,at.style.paddingBottom=ne.paddingY):(at.style.paddingTop="",at.style.paddingBottom="");let wr=(Nm=ne.tooltipText)!=null?Nm:"Clear chat",hn=(_m=ne.showTooltip)!=null?_m:!0;if(at.setAttribute("aria-label",wr),_t&&(_t._cleanupTooltip&&(_t._cleanupTooltip(),delete _t._cleanupTooltip),hn&&wr)){let Lt=null,Rr=()=>{if(Lt||!at)return;let ta=at.ownerDocument,bs=ta.body;if(!bs)return;Lt=ro(ta,"div","persona-clear-chat-tooltip"),Lt.textContent=wr;let ws=ro(ta,"div");ws.className="persona-clear-chat-tooltip-arrow",Lt.appendChild(ws);let ra=at.getBoundingClientRect();Lt.style.position="fixed",Lt.style.zIndex=String(Oo),Lt.style.left=`${ra.left+ra.width/2}px`,Lt.style.top=`${ra.top-8}px`,Lt.style.transform="translate(-50%, -100%)",bs.appendChild(Lt)},an=()=>{Lt&&Lt.parentNode&&(Lt.parentNode.removeChild(Lt),Lt=null)};_t.addEventListener("mouseenter",Rr),_t.addEventListener("mouseleave",an),at.addEventListener("focus",Rr),at.addEventListener("blur",an),_t._cleanupTooltip=()=>{an(),_t&&(_t.removeEventListener("mouseenter",Rr),_t.removeEventListener("mouseleave",an)),at&&(at.removeEventListener("focus",Rr),at.removeEventListener("blur",an))}}}}let mn=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ni],Tr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[wa.message,wa.messageAndClick];S=oi({parsers:mn,handlers:Tr,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ve=dy(n,S,oe),U.updateConfig(n),Go(Ve,U.getMessages(),ve),_n.render(n.suggestionChips,U,xe,void 0,n.suggestionChipsConfig),ds(),Aa(U.isStreaming());let Pn=((Fm=n.voiceRecognition)==null?void 0:Fm.enabled)===!0,gn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Jo=((Um=($m=n.voiceRecognition)==null?void 0:$m.provider)==null?void 0:Um.type)==="runtype";if(Pn&&(gn||Jo))if(!X||!er){let ne=ka(n.voiceRecognition,n.sendButton);ne&&(X=ne.micButton,er=ne.micButtonWrapper,Pt.insertBefore(er,De),X.addEventListener("click",Fe),X.disabled=U.isStreaming())}else{let ne=(qm=n.voiceRecognition)!=null?qm:{},$t=(zm=n.sendButton)!=null?zm:{},ar=(Vm=ne.iconName)!=null?Vm:"mic",Tt=(jm=$t.size)!=null?jm:"40px",Kt=(Gm=ne.iconSize)!=null?Gm:Tt,Ir=parseFloat(Kt)||24;X.style.width=Kt,X.style.height=Kt,X.style.minWidth=Kt,X.style.minHeight=Kt;let jr=(Xm=(Km=ne.iconColor)!=null?Km:$t.textColor)!=null?Xm:"currentColor";X.innerHTML="";let Vn=Be(ar,Ir,jr,2);Vn?X.appendChild(Vn):X.textContent="\u{1F3A4}";let Qr=(Jm=ne.backgroundColor)!=null?Jm:$t.backgroundColor;Qr?X.style.backgroundColor=Qr:X.style.backgroundColor="",jr?X.style.color=jr:X.style.color="var(--persona-text, #111827)",ne.borderWidth?(X.style.borderWidth=ne.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),ne.borderColor?X.style.borderColor=ne.borderColor:X.style.borderColor="",ne.paddingX?(X.style.paddingLeft=ne.paddingX,X.style.paddingRight=ne.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),ne.paddingY?(X.style.paddingTop=ne.paddingY,X.style.paddingBottom=ne.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let wr=er==null?void 0:er.querySelector(".persona-send-button-tooltip"),hn=(Qm=ne.tooltipText)!=null?Qm:"Start voice recognition";if(((Ym=ne.showTooltip)!=null?Ym:!1)&&hn)if(wr)wr.textContent=hn,wr.style.display="";else{let Rr=document.createElement("div");Rr.className="persona-send-button-tooltip",Rr.textContent=hn,er==null||er.insertBefore(Rr,X)}else wr&&(wr.style.display="none");er.style.display="",X.disabled=U.isStreaming()}else X&&er&&(er.style.display="none",((eg=(Zm=n.voiceRecognition)==null?void 0:Zm.provider)==null?void 0:eg.type)==="runtype"?U.isVoiceActive()&&U.toggleVoice():un&&zn());if(((tg=n.attachments)==null?void 0:tg.enabled)===!0)if(!Vt||!it){let ne=(rg=n.attachments)!=null?rg:{},ar=(og=((ng=n.sendButton)!=null?ng:{}).size)!=null?og:"40px";we||(we=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),we.style.display="none",Le.insertBefore(we,xe)),de||(de=document.createElement("input"),de.type="file",de.accept=((ag=ne.allowedTypes)!=null?ag:yo).join(","),de.multiple=((sg=ne.maxFiles)!=null?sg:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Le.insertBefore(de,xe)),Vt=v("div","persona-send-button-wrapper"),it=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(ig=ne.buttonTooltipText)!=null?ig:"Attach file");let Tt=(lg=ne.buttonIconName)!=null?lg:"paperclip",Kt=ar,Ir=parseFloat(Kt)||40,jr=Math.round(Ir*.6);it.style.width=Kt,it.style.height=Kt,it.style.minWidth=Kt,it.style.minHeight=Kt,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let Vn=Be(Tt,jr,"currentColor",1.5);Vn?it.appendChild(Vn):it.textContent="\u{1F4CE}",it.addEventListener("click",hn=>{hn.preventDefault(),de==null||de.click()}),Vt.appendChild(it);let Qr=(dg=ne.buttonTooltipText)!=null?dg:"Attach file",wr=v("div","persona-send-button-tooltip");wr.textContent=Qr,Vt.appendChild(wr),st.append(Vt),!ht&&de&&we&&(ht=ma.fromConfig(ne),ht.setPreviewsContainer(we),de.addEventListener("change",async()=>{ht&&(de!=null&&de.files)&&(await ht.handleFileSelect(de.files),de.value="")})),he.querySelector(".persona-attachment-drop-overlay")||he.appendChild(cy(ne.dropOverlay))}else{Vt.style.display="";let ne=(cg=n.attachments)!=null?cg:{};de&&(de.accept=((pg=ne.allowedTypes)!=null?pg:yo).join(","),de.multiple=((ug=ne.maxFiles)!=null?ug:4)>1),ht&&ht.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else Vt&&(Vt.style.display="none"),ht&&ht.clearAttachments(),(fg=he.querySelector(".persona-attachment-drop-overlay"))==null||fg.remove();let fr=(mg=n.sendButton)!=null?mg:{},Qo=(gg=fr.useIcon)!=null?gg:!1,Wo=(hg=fr.iconText)!=null?hg:"\u2191",Bo=fr.iconName,uo=(xg=fr.tooltipText)!=null?xg:"Send message",Yo=(yg=fr.showTooltip)!=null?yg:!1,mt=(bg=fr.size)!=null?bg:"40px",Vr=fr.backgroundColor,Or=fr.textColor;if(Qo){if(z.style.width=mt,z.style.height=mt,z.style.minWidth=mt,z.style.minHeight=mt,z.style.fontSize="18px",z.style.lineHeight="1",z.innerHTML="",Or?z.style.color=Or:z.style.color="var(--persona-button-primary-fg, #ffffff)",Bo){let ne=parseFloat(mt)||24,$t=(Or==null?void 0:Or.trim())||"currentColor",ar=Be(Bo,ne,$t,2);ar?z.appendChild(ar):z.textContent=Wo}else z.textContent=Wo;z.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Vr?(z.style.backgroundColor=Vr,z.classList.remove("persona-bg-persona-primary")):(z.style.backgroundColor="",z.classList.add("persona-bg-persona-primary"))}else z.textContent=(vg=(wg=n.copy)==null?void 0:wg.sendButtonLabel)!=null?vg:"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",Vr?(z.style.backgroundColor=Vr,z.classList.remove("persona-bg-persona-accent")):z.classList.add("persona-bg-persona-accent"),Or?z.style.color=Or:z.classList.add("persona-text-white");fr.borderWidth?(z.style.borderWidth=fr.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),fr.borderColor?z.style.borderColor=fr.borderColor:z.style.borderColor="",fr.paddingX?(z.style.paddingLeft=fr.paddingX,z.style.paddingRight=fr.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),fr.paddingY?(z.style.paddingTop=fr.paddingY,z.style.paddingBottom=fr.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let Pr=De==null?void 0:De.querySelector(".persona-send-button-tooltip");if(Yo&&uo)if(Pr)Pr.textContent=uo,Pr.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=uo,De==null||De.insertBefore(ne,z)}else Pr&&(Pr.style.display="none");let Et=(Mg=(Cg=n.layout)==null?void 0:Cg.contentMaxWidth)!=null?Mg:W()?(Tg=(Sg=(Ag=n.launcher)==null?void 0:Ag.composerBar)==null?void 0:Sg.contentMaxWidth)!=null?Tg:"720px":void 0;Et?(Ve.style.maxWidth=Et,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Le&&(Le.style.maxWidth=Et,Le.style.marginLeft="auto",Le.style.marginRight="auto"),ee&&(ee.style.maxWidth=Et,ee.style.marginLeft="auto",ee.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Le&&(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight=""),ee&&(ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight=""));let vt=(kg=n.statusIndicator)!=null?kg:{},qt=(Eg=vt.visible)!=null?Eg:!0;if(ge.style.display=qt?"":"none",U){let ne=U.getStatus();gt(ge,(ar=>{var Tt,Kt,Ir,jr;return ar==="idle"?(Tt=vt.idleText)!=null?Tt:Gr.idle:ar==="connecting"?(Kt=vt.connectingText)!=null?Kt:Gr.connecting:ar==="connected"?(Ir=vt.connectedText)!=null?Ir:Gr.connected:ar==="error"?(jr=vt.errorText)!=null?jr:Gr.error:Gr[ar]})(ne),vt,ne)}ge.classList.remove("persona-text-left","persona-text-center","persona-text-right");let on=vt.align==="left"?"persona-text-left":vt.align==="center"?"persona-text-center":"persona-text-right";ge.classList.add(on)},open(){P()&&Qt(!0,"api")},close(){P()&&Qt(!1,"api")},toggle(){P()&&Qt(!R,"api")},clearChat(){Pe=!1,U.clearMessages(),Ee.clear(),Mo();try{localStorage.removeItem(Za),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Za}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Za)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(),G==null||G.clear(),Ae==null||Ae.reset(),J==null||J.update()},setMessage(c){return!xe||U.isStreaming()?!1:(!R&&P()&&Qt(!0,"system"),xe.value=c,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(U.isStreaming())return!1;let g=(c==null?void 0:c.trim())||xe.value.trim();return g?(!R&&P()&&Qt(!0,"system"),xe.value="",xe.style.height="auto",U.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return U.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(U.isVoiceActive()||(!R&&P()&&Qt(!0,"system"),Wt.manuallyDeactivated=!1,nn(),U.toggleVoice().then(()=>{Wt.active=U.isVoiceActive(),kn("user"),U.isVoiceActive()&&H()})),!0):un?!0:hs()?(!R&&P()&&Qt(!0,"system"),Wt.manuallyDeactivated=!1,nn(),Xo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?U.isVoiceActive()?(U.toggleVoice().then(()=>{Wt.active=!1,Wt.manuallyDeactivated=!0,nn(),kn("user"),Y()}),!0):!1:un?(Wt.manuallyDeactivated=!0,nn(),zn("user"),!0):!1},injectMessage(c){return!R&&P()&&Qt(!0,"system"),U.injectMessage(c)},injectAssistantMessage(c){!R&&P()&&Qt(!0,"system");let g=U.injectAssistantMessage(c);return N&&(N=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)),g},injectUserMessage(c){return!R&&P()&&Qt(!0,"system"),U.injectUserMessage(c)},injectSystemMessage(c){return!R&&P()&&Qt(!0,"system"),U.injectSystemMessage(c)},injectMessageBatch(c){return!R&&P()&&Qt(!0,"system"),U.injectMessageBatch(c)},injectComponentDirective(c){return!R&&P()&&Qt(!0,"system"),U.injectComponentDirective(c)},injectTestMessage(c){!R&&P()&&Qt(!0,"system"),U.injectTestEvent(c)},async connectStream(c,g){return U.connectStream(c,g)},__pushEventStreamEvent(c){G&&(Ae==null||Ae.processEvent(c.type,c.payload),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!$e||!G||Br()},hideEventStream(){ie&&Ur()},isEventStreamVisible(){return ie},showArtifacts(){Hn(n)&&(Pe=!1,ln(),fe==null||fe.setMobileOpen(!0))},hideArtifacts(){Hn(n)&&(Pe=!0,ln())},upsertArtifact(c){return Hn(n)?(Pe=!1,U.upsertArtifact(c)):null},selectArtifact(c){Hn(n)&&U.selectArtifact(c)},clearArtifacts(){Hn(n)&&U.clearArtifacts()},getArtifacts(){var c;return(c=U==null?void 0:U.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=U==null?void 0:U.getSelectedArtifactId())!=null?c:null},focusInput(){return M&&!R&&!W()||!xe?!1:(xe.focus(),!0)},async resolveApproval(c,g,b){let B=U.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.id)===c});if(!(B!=null&&B.approval))throw new Error(`Approval not found: ${c}`);if(B.approval.toolType==="webmcp"){U.resolveWebMcpApproval(B.id,g);return}return U.resolveApproval(B.approval,g,b)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return P()&&R},isVoiceActive(){return Wt.active},getState(){return{open:P()&&R,launcherEnabled:M,voiceActive:Wt.active,streaming:U.isStreaming()}},showCSATFeedback(c){!R&&P()&&Qt(!0,"system");let g=Ve.querySelector(".persona-feedback-container");g&&g.remove();let b=ed({onSubmit:async(A,B)=>{var F;U.isClientTokenMode()&&await U.submitCSATFeedback(A,B),(F=c==null?void 0:c.onSubmit)==null||F.call(c,A,B)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&P()&&Qt(!0,"system");let g=Ve.querySelector(".persona-feedback-container");g&&g.remove();let b=td({onSubmit:async(A,B)=>{var F;U.isClientTokenMode()&&await U.submitNPSFeedback(A,B),(F=c==null?void 0:c.onSubmit)==null||F.call(c,A,B)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return U.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return U.submitNPSFeedback(c,g)},destroy(){Jn!=null&&(clearInterval(Jn),Jn=null),Bt.forEach(c=>c()),ke.remove(),tt==null||tt.remove(),ct==null||ct.destroy(),ut==null||ut.remove(),cn&&Z.removeEventListener("click",cn)}};if((((kf=r==null?void 0:r.debugTools)!=null?kf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Sr,getMessages:Sr.getMessages,getStatus:Sr.getStatus,getMetadata:Sr.getPersistentMetadata,updateMetadata:Sr.updatePersistentMetadata,clearHistory:()=>Sr.clearChat(),setVoiceActive:b=>b?Sr.startVoiceRecognition():Sr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Bt.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=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Sr.focusInput()};if(window.addEventListener("persona:focusInput",g),Bt.push(()=>{window.removeEventListener("persona:focusInput",g)}),$e){let K=We=>{let Ce=We.detail;(!(Ce!=null&&Ce.instanceId)||Ce.instanceId===c)&&Sr.showEventStream()},_=We=>{let Ce=We.detail;(!(Ce!=null&&Ce.instanceId)||Ce.instanceId===c)&&Sr.hideEventStream()};window.addEventListener("persona:showEventStream",K),window.addEventListener("persona:hideEventStream",_),Bt.push(()=>{window.removeEventListener("persona:showEventStream",K),window.removeEventListener("persona:hideEventStream",_)})}let b=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Sr.showArtifacts()},A=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Sr.hideArtifacts()},B=K=>{let _=K.detail;_!=null&&_.instanceId&&_.instanceId!==c||_!=null&&_.artifact&&Sr.upsertArtifact(_.artifact)},F=K=>{let _=K.detail;_!=null&&_.instanceId&&_.instanceId!==c||typeof(_==null?void 0:_.id)=="string"&&Sr.selectArtifact(_.id)},$=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Sr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",B),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),Bt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",B),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let Ln=CC(n.persistState);if(Ln&&P()){let c=AC(Ln.storage),g=`${Ln.keyPrefix}widget-open`,b=`${Ln.keyPrefix}widget-voice`,A=`${Ln.keyPrefix}widget-voice-mode`;if(c){let B=((Ef=Ln.persist)==null?void 0:Ef.openState)&&c.getItem(g)==="true",F=((Lf=Ln.persist)==null?void 0:Lf.voiceState)&&c.getItem(b)==="true",$=((Pf=Ln.persist)==null?void 0:Pf.voiceState)&&c.getItem(A)==="true";if(B&&setTimeout(()=>{Sr.open(),setTimeout(()=>{var K;if(F||$)Sr.startVoiceRecognition();else if((K=Ln.persist)!=null&&K.focusInput){let _=t.querySelector("textarea");_&&_.focus()}},100)},0),(If=Ln.persist)!=null&&If.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Rf=Ln.persist)!=null&&Rf.voiceState&&(s.on("voice:state",K=>{c.setItem(b,K.active?"true":"false")}),s.on("user:message",K=>{c.setItem(A,K.viaVoice?"true":"false")})),Ln.clearOnChatClear){let K=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(A)},_=()=>K();window.addEventListener("persona:clear-chat",_),Bt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return p&&P()&&setTimeout(()=>{Sr.open()},0),co(),Sr};var SC=(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},py=(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"},yu=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=""},uy=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.minWidth="",yu(t)},gu=t=>{t.style.transition=""},hu=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=""},xu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},od=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},TC=(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)},fy=(t,e,r,n,o,s,a)=>{var y,x,S,M,k,T;let i=Wn(s),d=i.reveal==="push";TC(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=(x=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?x:!0,u=(M=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?M:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),hu(e),gu(n),uy(n),xu(r),od(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((T=(k=s==null?void 0:s.launcher)==null?void 0:k.zIndex)!=null?T:Kr),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"),uy(n),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",hu(e),gu(n),xu(r),od(o,n);let h=i.animate?"transform 180ms ease":"none",C=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":C;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=w,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",gu(n),yu(n),od(o,n);let h=SC(i.width,t.clientWidth),C=Math.max(0,t.clientWidth),w=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=`${C+h}px`,e.style.transition=w,e.style.transform=E,r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${C}px`,r.style.maxWidth=`${C}px`,r.style.minWidth=`${C}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="",hu(e),yu(n),xu(r),od(o,n);let h=i.reveal==="emerge";h?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let C=a?i.width:"0px",w=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 ${C}`,n.style.width=C,n.style.maxWidth=C,n.style.minWidth=C,n.style.minHeight="0",n.style.position="relative",n.style.overflow=h||E?"hidden":"visible",n.style.transition=w,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")}},kC=(t,e)=>{let r=t.ownerDocument.createElement("div");return py(r,e),t.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){py(r,n)},destroy(){r.remove()}}},EC=(t,e)=>{var k,T,h,C;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"),u=(T=(k=e==null?void 0:e.launcher)==null?void 0:k.enabled)==null||T?(C=(h=e==null?void 0:e.launcher)==null?void 0:h.autoExpand)!=null?C:!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 f=null,m=()=>{f==null||f.disconnect(),f=null},y=()=>{m(),Wn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{fy(a,i,d,l,p,e,u)}),f.observe(a))},x=()=>{fy(a,i,d,l,p,e,u),y()},S=a.ownerDocument.defaultView,M=()=>{x()};return S==null||S.addEventListener("resize",M),Wn(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(w){let E=w.launcherEnabled?w.open:!0;u!==E&&(u=E,x())},updateConfig(w){var E,W;e=w,((W=(E=e==null?void 0:e.launcher)==null?void 0:E.enabled)!=null?W:!0)===!1&&(u=!0),x()},destroy(){S==null||S.removeEventListener("resize",M),m(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(t,s):n.appendChild(t)),a.remove()}}},ai=(t,e)=>kr(e)?EC(t,e):kC(t,e);var bu={},my=!1,LC=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},PC=()=>{try{if(typeof bu!="undefined"&&bu.url)return new URL("../widget.css",bu.url).href}catch{}return null},gy=(t,e)=>{let r=PC(),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)}},hy=t=>{let e=LC(t.target),r=t.useShadowDom===!0,n=e.ownerDocument,o=t.config,s=ai(e,o),a,i=[],d=(S,M)=>{var C,w;let T=!((w=(C=M==null?void 0:M.launcher)==null?void 0:C.enabled)!=null?w:!0)||kr(M),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),T&&(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),gy(E,n)}else S.appendChild(h),gy(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()},u=()=>{let S=d(s.host,o);a=nd(S,o,{debugTools:t.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};u(),t.onChatReady?t.onChatReady():t.onReady&&(my||(my=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),t.onReady());let m=S=>{f(),s.destroy(),s=ai(e,S),o=S,u()},y={update(S){var w,E,W,P,R,N;let M={...o,...S,launcher:{...(w=o==null?void 0:o.launcher)!=null?w:{},...(E=S==null?void 0:S.launcher)!=null?E:{},dock:{...(P=(W=o==null?void 0:o.launcher)==null?void 0:W.dock)!=null?P:{},...(N=(R=S==null?void 0:S.launcher)==null?void 0:R.dock)!=null?N:{}}}},k=kr(o),T=kr(M),h=_o(o),C=_o(M);if(k!==T||h!==C){m(M);return}o=M,s.updateConfig(o),a.update(S),l()},destroy(){f(),s.destroy(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}},x=new Proxy(y,{get(S,M,k){if(M==="host")return s.host;if(M in S)return Reflect.get(S,M,k);let T=a[M];return typeof T=="function"?T.bind(a):T}});return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=x),x};var vy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),IC=new Set(["button","a","input","select","textarea","details","summary"]),RC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),wu=/\b(product|card|item|listing|result)\b/i,Cu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,WC=3e3,BC=100;function Cy(t){let e=typeof t.className=="string"?t.className:"";if(wu.test(e)||t.id&&wu.test(t.id))return!0;for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];if(n.name.startsWith("data-")&&wu.test(n.value))return!0}return!1}function Ay(t){var e;return Cu.test(((e=t.textContent)!=null?e:"").trim())}function Sy(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 HC(t){return!!t.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function xy(t){let e=t.match(Cu);return e?e[0]:null}function yy(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 DC(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 OC="commerce-card",NC="result-card";function by(t){return!Cy(t)||!Ay(t)||!Sy(t)&&!HC(t)?0:5200}function wy(t){var n;return!Cy(t)||Ay(t)||!Sy(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 Au=[{id:OC,scoreElement(t){return by(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||Cu.test(n)&&n.length<32)}return!0},formatSummary(t,e){var d,l,p;if(by(t)===0)return null;let{title:r,href:n}=yy(t),o=(p=(l=xy(((d=t.textContent)!=null?d:"").trim()))!=null?l:xy(e.text))!=null?p:"",s=DC(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:NC,scoreElement(t){return wy(t)},formatSummary(t,e){if(wy(t)===0)return null;let{title:r,href:n}=yy(t);return[n&&r?`[${r}](${n})`:r||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
159
- `)}}];function _C(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function FC(t){var p,u,f,m,y,x,S,M,k,T,h,C,w;let e=(p=t.options)!=null?p:{},r=(f=(u=e.maxElements)!=null?u:t.maxElements)!=null?f:80,n=(y=(m=e.excludeSelector)!=null?m:t.excludeSelector)!=null?y:".persona-host",o=(S=(x=e.maxTextLength)!=null?x:t.maxTextLength)!=null?S:200,s=(k=(M=e.visibleOnly)!=null?M:t.visibleOnly)!=null?k:!0,a=(T=e.root)!=null?T:t.root,i=(h=e.mode)!=null?h:"structured",d=(C=e.maxCandidates)!=null?C:Math.max(500,r*10),l=(w=t.rules)!=null?w:Au;return i==="simple"&&t.rules&&t.rules.length>0?(_C(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function vu(t){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/([^\w-])/g,"\\$1")}var $C=["data-testid","data-product","data-action","data-id","data-name","data-type"];function UC(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"||IC.has(e)||r&&RC.has(r)||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||t.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ty(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 qC(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 Su(t){let e=t.tagName.toLowerCase();if(t.id){let o=`#${vu(t.id)}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of $C){let s=t.getAttribute(o);if(s){let a=`${e}[${o}="${vu(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=>vu(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 zC(t){return t==="static"?BC:WC}function My(t,e){var o;let r=t.tagName.toLowerCase(),n=((o=t.textContent)!=null?o:"").trim().substring(0,e);return{selector:Su(t),tagName:r,text:n,role:t.getAttribute("role"),interactivity:UC(t),attributes:qC(t)}}function VC(t,e,r,n){let o=zC(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 jC(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 GC(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(vy.has(p)){i=a.nextNode();continue}if(t.excludeSelector)try{if(l.closest(t.excludeSelector)){i=a.nextNode();continue}}catch{}if(t.visibleOnly&&!Ty(l)){i=a.nextNode();continue}let u=My(l,t.maxTextLength),f=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(S=>S==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(u.selector)){i=a.nextNode();continue}n.add(u.selector);let{score:y,formattingRule:x}=VC(l,u,t.rules,r);o.push({el:l,domIndex:s,enriched:u,score:y,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=t.maxElements)break;jC(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,r);m&&(p=m)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function KC(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(vy.has(l)){s=o.nextNode();continue}if(t.excludeSelector)try{if(d.closest(t.excludeSelector)){s=o.nextNode();continue}}catch{}if(t.visibleOnly&&!Ty(d)){s=o.nextNode();continue}let p=My(d,t.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!f){s=o.nextNode();continue}n.has(p.selector)||(n.add(p.selector),r.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of r)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,t.maxElements)}function ky(t={}){var n;let e=FC(t),r=(n=e.root)!=null?n:document.body;return r?e.mode==="simple"?KC(e,r):GC(e,r):[]}var ad=100;function Ey(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
- ${a.map(i=>`- ${i.split(`
154
+ `}if(!A&&!c){let bt="max-height: -moz-available !important; max-height: stretch !important;",Et=g?"":"padding-top: 1.25em !important;",yt=g?"":`z-index: ${(Mr=(Xr=n.launcher)==null?void 0:Xr.zIndex)!=null?Mr:Gr} !important;`;We.style.cssText+=bt+Et+yt}rt()};Nn(),Do(r,n),_l(r,n),Ul(r,n);let kt=[];kt.push(()=>{document.removeEventListener("keydown",wo)});let yr=null,vr=null;kt.push(()=>{yr==null||yr(),yr=null,vr==null||vr(),vr=null}),_t&&kt.push(()=>{_t==null||_t.disconnect(),_t=null}),kt.push(()=>{Kr==null||Kr(),Kr=null,oo(),jt&&(jt.remove(),jt=null),Ze==null||Ze.element.style.removeProperty("width"),Ze==null||Ze.element.style.removeProperty("maxWidth")}),De&&kt.push(()=>{ke!==null&&(cancelAnimationFrame(ke),ke=null),G==null||G.destroy(),G=null,ge==null||ge.destroy(),ge=null,re=null});let fn=null,To=()=>{fn&&(fn(),fn=null),n.colorScheme==="auto"&&(fn=ml(()=>{Do(r,n)}))};To(),kt.push(()=>{fn&&(fn(),fn=null)});let ve=(yf=n.features)==null?void 0:yf.streamAnimation;if(ve!=null&&ve.type&&ve.type!=="none"){let c=Vs(ve.type,ve.plugins);c&&(Ip(c,r),kt.push(()=>tx(r)))}let Mn=Lx(It),kn=null,q,Kn=!1,ao=jh(),so=new Map,Xn=new Map,On=new Map,rs=0,mn=xl(),gn=0,_n=null,Un=!1,Vo=!1,io=0,zr=null,Qn=null,wa=!1,jo=!1,Aa=null,si=4,Sa=24,ii=80,Ta=new Map,Rt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ns=(Cf=(vf=n.voiceRecognition)==null?void 0:vf.autoResume)!=null?Cf:!1,En=c=>{a.emit("voice:state",{active:Rt.active,source:c,timestamp:Date.now()})},an=()=>{m(c=>({...c,voiceState:{active:Rt.active,timestamp:Date.now(),manuallyDeactivated:Rt.manuallyDeactivated}}))},li=()=>{var A,H;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=nu(d.voiceState),g=!!c.active,b=Number((H=c.timestamp)!=null?H:0);Rt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<hC&&setTimeout(()=>{var _,U;Rt.active||(Rt.manuallyDeactivated=!1,((U=(_=n.voiceRecognition)==null?void 0:_.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{Rt.active=q.isVoiceActive(),En("restore"),q.isVoiceActive()&&hs()}):Wr("restore"))},1e3)},di=()=>q?Kx(q.getMessages()).filter(c=>!c.__skipPersist):[];function Ma(c){if(!(i!=null&&i.save))return;let b={messages:c?Kx(c):q?di():[],metadata:d,artifacts:Zt.artifacts,selectedArtifactId:Zt.selectedId};try{let A=i.save(b);A instanceof Promise&&A.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let lo=null,os=()=>We.querySelector("#persona-scroll-container")||ue,Mo=()=>{lo!==null&&(cancelAnimationFrame(lo),lo=null),Un=!1},as=()=>{_n!==null&&(cancelAnimationFrame(_n),_n=null),Vo=!1,Mo()},ss=()=>{io>0?(ir.textContent=String(io),ir.style.display="",et.setAttribute("aria-label",`${ct()||"Jump to latest"} (${io} new)`)):(ir.textContent="",ir.style.display="none",et.setAttribute("aria-label",ct()||"Jump to latest"))},is=()=>{io!==0&&(io=0,ss())},ls=()=>pt()==="follow"?!mn.isFollowing():!ma(ue,Sa),sn=()=>{if(!Ir()||pe){et.parentNode&&et.remove(),et.style.display="none";return}et.parentNode!==j&&j.appendChild(et),Sr();let g=xo(ue)>0&&ls();g||is(),et.style.display=g?"":"none"},ka=()=>{mn.pause()&&(as(),sn())},Jn=()=>{mn.resume(),is(),sn()},Yn=(c=!1)=>{pt()==="follow"&&mn.isFollowing()&&(!c&&!Kn||(_n!==null&&(cancelAnimationFrame(_n),_n=null),Vo=!0,_n=requestAnimationFrame(()=>{_n=null,Vo=!1,mn.isFollowing()&&ci(os(),c?220:140)})))},ds=(c,g,b,A=()=>!0)=>{let H=c.scrollTop,_=g(),U=_-H;Mo();let $=performance.now();Un=!0;let O=me=>1-Math.pow(1-me,3),Ce=me=>{if(!A()){Mo();return}let oe=g();oe!==_&&(_=oe,U=_-H);let Te=me-$,Ve=Math.min(Te/b,1),Se=O(Ve),dt=H+U*Se;c.scrollTop=dt,gn=c.scrollTop,Ve<1?lo=requestAnimationFrame(Ce):(c.scrollTop=_,gn=c.scrollTop,lo=null,Un=!1)};lo=requestAnimationFrame(Ce)},ci=(c,g=500)=>{let b=xo(c)-c.scrollTop;if(Math.abs(b)<1){gn=c.scrollTop;return}if(Math.abs(b)>=ii){Mo(),Un=!0,c.scrollTop=xo(c),gn=c.scrollTop,Un=!1;return}ds(c,()=>xo(c),g,()=>mn.isFollowing())},cs=()=>{let c=os();Un=!0,c.scrollTop=xo(c),gn=c.scrollTop,Un=!1,sn()},ps=c=>{fr.style.height=`${Math.max(0,Math.round(c))}px`,zr&&(zr.spacerHeight=Math.max(0,c))},Go=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),Mo(),zr=null,fr.style.height="0px"},pi=c=>{Qn!==null&&cancelAnimationFrame(Qn),Qn=requestAnimationFrame(()=>{var Ce;Qn=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=ue.querySelector(`[data-message-id="${g}"]`);if(!b)return;let A=0,H=b;for(;H&&H!==ue;)A+=H.offsetTop,H=H.offsetParent;let _=(Ce=zr==null?void 0:zr.spacerHeight)!=null?Ce:0,U=ue.scrollHeight-_,{targetScrollTop:$,spacerHeight:O}=Jh({anchorOffsetTop:A,topOffset:Pt(),viewportHeight:ue.clientHeight,contentHeight:U});zr={initialSpacerHeight:O,contentHeightAtAnchor:U,spacerHeight:O},ps(O),ds(ue,()=>$,220)})},ui=()=>{if(pt()==="follow"){if(!mn.isFollowing()||ma(ue,1))return;Yn(!Kn);return}if(zr&&zr.initialSpacerHeight>0){let c=ue.scrollHeight-zr.spacerHeight,g=Yh({initialSpacerHeight:zr.initialSpacerHeight,contentHeightAtAnchor:zr.contentHeightAtAnchor,currentContentHeight:c});g!==zr.spacerHeight&&ps(g)}sn()},fi=c=>{let g=pt();g==="follow"?(Jn(),Yn(!0)):g==="anchor-top"&&pi(c)},mi=c=>{let g=new Map;c.forEach(b=>{let A=Ta.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!A&&b.role==="assistant"&&(a.emit("assistant:message",b),!jo&&pt()!=="anchor-top"&&ls()&&(io+=1,ss(),sn())),b.role==="assistant"&&(A!=null&&A.streaming)&&b.streaming===!1&&a.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(A?b.approval.status!=="pending"&&a.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):a.emit("approval:requested",{approval:b.approval,message:b}))}),Ta.clear(),g.forEach((b,A)=>{Ta.set(A,b)})},Ko=(c,g,b)=>{var xt,Be,Le,Ke,rt,Wt;let A=document.createElement("div"),_=(()=>{var Ne;let D=o.find(Ue=>Ue.renderLoadingIndicator);if(D!=null&&D.renderLoadingIndicator)return D.renderLoadingIndicator;if((Ne=n.loadingIndicator)!=null&&Ne.render)return n.loadingIndicator.render})(),U=(D,Ne)=>Ne==null?!1:typeof Ne=="string"?(D.textContent=Ne,!0):(D.appendChild(Ne),!0),$=new Set,O=new Set,Ce=o.some(D=>D.renderAskUserQuestion),me=[],oe=[],Te=n.enableComponentStreaming!==!1,Ve=o.some(D=>D.renderApproval)&&n.approval!==!1,Se=[];if(g.forEach(D=>{var ot,Ut,Er,Rn,xn,Xo,Qo,Ia,Wa,mr,Jo,Wo,Ho,po;$.add(D.id);let Ne=Ce&&yo(D),Ue=Ve&&D.variant==="approval"&&!!D.approval,be=!Ne&&D.role==="assistant"&&!D.variant&&Te&&Vl(D);if(!Ue&&On.has(D.id)){let ut=c.querySelector(`#wrapper-${D.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),On.delete(D.id)}if(!be&&Xn.has(D.id)){let ut=c.querySelector(`#wrapper-${D.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),Xn.delete(D.id)}let Yt=yo(D)?`:${(ot=D.agentMetadata)!=null&&ot.askUserQuestionAnswered?"a":"u"}:${(Ut=D.agentMetadata)!=null&&Ut.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Kt=Vh(D,rs)+Yt,cr=Ne||Ue||be?null:Gh(ao,D.id,Kt);if(cr){A.appendChild(cr.cloneNode(!0)),yo(D)&&((Er=D.toolCall)!=null&&Er.id)&&((Rn=D.agentMetadata)==null?void 0:Rn.awaitingLocalTool)===!0&&!((xn=D.agentMetadata)!=null&&xn.askUserQuestionAnswered)&&(O.add(D.toolCall.id),Ja(D,n,Pe.composerOverlay));return}let Bt=null,lr=o.find(ut=>!!(D.variant==="reasoning"&&ut.renderReasoning||D.variant==="tool"&&ut.renderToolCall||!D.variant&&ut.renderMessage)),hn=(Xo=n.layout)==null?void 0:Xo.messages;if(yo(D)&&((Qo=D.agentMetadata)==null?void 0:Qo.askUserQuestionAnswered)===!0){so.delete(D.id);let ut=c.querySelector(`#wrapper-${D.id}`);ut==null||ut.removeAttribute("data-preserve-runtime");return}if(yo(D)&&((Wa=(Ia=n.features)==null?void 0:Ia.askUserQuestion)==null?void 0:Wa.enabled)!==!1){let ut=o.find(Nr=>typeof Nr.renderAskUserQuestion=="function");if(ut&&wt.current){let Nr=so.get(D.id),Xr=Nr!==Kt,Mr=null;if(Xr){let{payload:yt,complete:ln}=vo(D),Lr=D.id,Zn=()=>{var Pr;return(Pr=wt.current)==null?void 0:Pr.getMessages().find(Qr=>Qr.id===Lr)};Mr=ut.renderAskUserQuestion({message:D,payload:yt,complete:ln,resolve:Pr=>{var In;let Qr=Zn();Qr&&((In=wt.current)==null||In.resolveAskUserQuestion(Qr,Pr))},dismiss:()=>{var Qr,In,Yo;let Pr=Zn();(Qr=Pr==null?void 0:Pr.agentMetadata)!=null&&Qr.awaitingLocalTool&&((In=wt.current)==null||In.markAskUserQuestionResolved(Pr),(Yo=wt.current)==null||Yo.resolveAskUserQuestion(Pr,"(dismissed)"))},config:n})}let bt=Nr!=null;if(Xr&&Mr===null&&!bt){((mr=D.agentMetadata)==null?void 0:mr.awaitingLocalTool)===!0&&!((Jo=D.agentMetadata)!=null&&Jo.askUserQuestionAnswered)&&(O.add(D.toolCall.id),Ja(D,n,Pe.composerOverlay));return}let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${D.id}`,Et.setAttribute("data-wrapper-id",D.id),Et.setAttribute("data-ask-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),A.appendChild(Et),me.push({messageId:D.id,fingerprint:Kt,bubble:Mr});return}else{((Wo=D.agentMetadata)==null?void 0:Wo.awaitingLocalTool)===!0&&!((Ho=D.agentMetadata)!=null&&Ho.askUserQuestionAnswered)&&(O.add(D.toolCall.id),Ja(D,n,Pe.composerOverlay));return}}else if(Ue){let ut=o.find(bt=>typeof bt.renderApproval=="function"),Xr=On.get(D.id)!==Kt,Mr=null;if(Xr&&(ut!=null&&ut.renderApproval)){let bt=D.id,Et=(yt,ln)=>{var Zn,Pr,Qr;let Lr=(Zn=wt.current)==null?void 0:Zn.getMessages().find(In=>In.id===bt);Lr!=null&&Lr.approval&&(Lr.approval.toolType==="webmcp"?(Pr=wt.current)==null||Pr.resolveWebMcpApproval(Lr.id,yt):(Qr=wt.current)==null||Qr.resolveApproval(Lr.approval,yt,ln))};Mr=ut.renderApproval({message:D,defaultRenderer:()=>Nl(D,n),config:n,approve:yt=>Et("approved",yt),deny:yt=>Et("denied",yt)})}if(Xr&&Mr===null){let bt=c.querySelector(`#wrapper-${D.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),On.delete(D.id),Bt=Nl(D,n)}else{let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${D.id}`,bt.setAttribute("data-wrapper-id",D.id),bt.setAttribute("data-approval-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),A.appendChild(bt),Se.push({messageId:D.id,fingerprint:Kt,bubble:Mr});return}}else if(lr)if(D.variant==="reasoning"&&D.reasoning&&lr.renderReasoning){if(!Je)return;Bt=lr.renderReasoning({message:D,defaultRenderer:()=>qp(D,n),config:n})}else if(D.variant==="tool"&&D.toolCall&&lr.renderToolCall){if(!we)return;Bt=lr.renderToolCall({message:D,defaultRenderer:()=>zp(D,n),config:n})}else lr.renderMessage&&(Bt=lr.renderMessage({message:D,defaultRenderer:()=>{let ut=ja(D,b,hn,n.messageActions,ne,{loadingIndicatorRenderer:_,widgetConfig:n});return D.role!=="user"&&eu(ut,D,n,q),ut},config:n}));if(!Bt&&be){let ut=jl(D);if(ut){let Nr=Xn.get(D.id),Xr=Nr!==Kt,Mr=n.wrapComponentDirectiveInBubble!==!1,bt=null;if(Xr){let Et=$l(ut,{config:n,message:D,transform:b});if(Et)if(Mr){let yt=document.createElement("div");if(yt.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(" "),yt.id=`bubble-${D.id}`,yt.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let ln=document.createElement("div");ln.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ln.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),yt.appendChild(ln)}yt.appendChild(Et),bt=yt}else{let yt=document.createElement("div");if(yt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",yt.id=`bubble-${D.id}`,yt.setAttribute("data-message-id",D.id),yt.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let ln=document.createElement("div");ln.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ln.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),yt.appendChild(ln)}yt.appendChild(Et),bt=yt}}if(bt||Nr!=null){let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${D.id}`,Et.setAttribute("data-wrapper-id",D.id),Et.setAttribute("data-component-directive-stub","true"),Et.setAttribute("data-preserve-runtime","true"),Mr||Et.classList.add("persona-w-full"),A.appendChild(Et),oe.push({messageId:D.id,fingerprint:Kt,bubble:bt});return}}}if(!Bt)if(D.variant==="reasoning"&&D.reasoning){if(!Je)return;Bt=qp(D,n)}else if(D.variant==="tool"&&D.toolCall){if(!we)return;Bt=zp(D,n)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;Bt=Nl(D,n)}else{let ut=(po=n.layout)==null?void 0:po.messages;ut!=null&&ut.renderUserMessage&&D.role==="user"?Bt=ut.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):ut!=null&&ut.renderAssistantMessage&&D.role==="assistant"?Bt=ut.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):Bt=ja(D,b,ut,n.messageActions,ne,{loadingIndicatorRenderer:_,widgetConfig:n}),D.role!=="user"&&Bt&&eu(Bt,D,n,q)}let Tr=document.createElement("div");Tr.className="persona-flex",Tr.id=`wrapper-${D.id}`,Tr.setAttribute("data-wrapper-id",D.id),D.role==="user"&&Tr.classList.add("persona-justify-end"),(Bt==null?void 0:Bt.getAttribute("data-persona-component-directive"))==="true"&&Tr.classList.add("persona-w-full"),Tr.appendChild(Bt),Kh(ao,D.id,Kt,Tr),A.appendChild(Tr)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Ue=Ne.getAttribute("data-persona-ask-sheet-for");Ue&&!O.has(Ue)&&zo(Pe.composerOverlay,Ue)}),(Be=(xt=n.features)==null?void 0:xt.toolCallDisplay)!=null&&Be.grouped){let D=[],Ne=[];g.forEach(Ue=>{if(Ue.variant==="tool"&&Ue.toolCall&&we){Ne.push(Ue);return}Ne.length>1&&D.push(Ne),Ne=[]}),Ne.length>1&&D.push(Ne),D.forEach((Ue,be)=>{var ot,Ut;let Yt=Ue.map(Er=>Array.from(A.children).find(Rn=>Rn instanceof HTMLElement&&Rn.getAttribute("data-wrapper-id")===Er.id)).filter(Er=>!!Er);if(Yt.length<2)return;let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-tool-group-${be}-${Ue[0].id}`,Kt.setAttribute("data-wrapper-id",`tool-group-${be}-${Ue[0].id}`);let cr=document.createElement("div");cr.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",cr.setAttribute("data-persona-tool-group","true");let Bt=document.createElement("div");Bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let lr=`Called ${Ue.length} tools`,hn=(Ut=(ot=n.toolCall)==null?void 0:ot.renderGroupedSummary)==null?void 0:Ut.call(ot,{messages:Ue,toolCalls:Ue.map(Er=>Er.toolCall).filter(Er=>!!Er),defaultSummary:lr,config:n});U(Bt,hn)||(Bt.textContent=lr);let Tr=document.createElement("div");Tr.className="persona-tool-group-stack persona-flex persona-flex-col",cr.append(Bt,Tr),Kt.appendChild(cr),Yt[0].before(Kt),Yt.forEach((Er,Rn)=>{let xn=document.createElement("div");xn.className="persona-tool-group-item persona-relative",xn.setAttribute("data-persona-tool-group-item","true"),Rn<Yt.length-1&&xn.setAttribute("data-persona-tool-group-connector","true"),xn.appendChild(Er),Tr.appendChild(xn)})})}Xh(ao,$);let dt=g.some(D=>D.role==="assistant"&&D.streaming),Qe=g[g.length-1],ht=(Qe==null?void 0:Qe.role)==="assistant"&&!Qe.streaming&&Qe.variant!=="approval";if(Kn&&g.some(D=>D.role==="user")&&!dt&&!ht){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:xa},Ne=o.find(be=>be.renderLoadingIndicator),Ue=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(Ue=Ne.renderLoadingIndicator(D)),Ue===null&&((Le=n.loadingIndicator)!=null&&Le.render)&&(Ue=n.loadingIndicator.render(D)),Ue===null&&(Ue=xa()),Ue){let be=document.createElement("div"),Yt=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;be.className=Yt?["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(" "),be.setAttribute("data-typing-indicator","true"),be.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",be.appendChild(Ue);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-typing-indicator",Kt.setAttribute("data-wrapper-id","typing-indicator"),Kt.appendChild(be),A.appendChild(Kt)}}if(!Kn&&g.length>0){let D=g[g.length-1],Ne={config:n,lastMessage:D,messageCount:g.length},Ue=o.find(Yt=>Yt.renderIdleIndicator),be=null;if(Ue!=null&&Ue.renderIdleIndicator&&(be=Ue.renderIdleIndicator(Ne)),be===null&&((rt=n.loadingIndicator)!=null&&rt.renderIdle)&&(be=n.loadingIndicator.renderIdle(Ne)),be){let Yt=document.createElement("div"),Kt=((Wt=n.loadingIndicator)==null?void 0:Wt.showBubble)!==!1;Yt.className=Kt?["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(" "),Yt.setAttribute("data-idle-indicator","true"),Yt.appendChild(be);let cr=document.createElement("div");cr.className="persona-flex",cr.id="wrapper-idle-indicator",cr.setAttribute("data-wrapper-id","idle-indicator"),cr.appendChild(Yt),A.appendChild(cr)}}if(gl(c,A),me.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Ue}of me){let be=c.querySelector(`#wrapper-${D}`);be&&Ue!==null&&(be.replaceChildren(Ue),be.setAttribute("data-bubble-fp",Ne),so.set(D,Ne))}if(so.size>0)for(let D of so.keys())$.has(D)||so.delete(D);if(oe.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Ue}of oe){let be=c.querySelector(`#wrapper-${D}`);be&&Ue!==null&&(be.replaceChildren(Ue),be.setAttribute("data-bubble-fp",Ne),Xn.set(D,Ne))}if(Xn.size>0)for(let D of Xn.keys())$.has(D)||Xn.delete(D);if(Se.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Ue}of Se){let be=c.querySelector(`#wrapper-${D}`);be&&Ue!==null&&(be.replaceChildren(Ue),be.setAttribute("data-bubble-fp",Ne),On.set(D,Ne))}if(On.size>0)for(let D of On.keys())$.has(D)||On.delete(D)},ko=null,gi=()=>{var b;if(ko)return;let c=A=>{let H=A.composedPath();H.includes(We)||at&&H.includes(at)||Gt(!1,"user")};ko=c,((b=r.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},us=()=>{var g;if(!ko)return;((g=r.ownerDocument)!=null?g:document).removeEventListener("pointerdown",ko,!0),ko=null};kt.push(()=>us());let Eo=null,hi=()=>{var b;if(Eo)return;let c=A=>{A.key==="Escape"&&(A.isComposing||Gt(!1,"user"))};Eo=c,((b=r.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},fs=()=>{var g;if(!Eo)return;((g=r.ownerDocument)!=null?g:document).removeEventListener("keydown",Eo,!0),Eo=null};kt.push(()=>fs());let Lo=!1,ms=new Set,xi=()=>{var g,b,A,H;let c=(A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:A.streamAnimation;return c||((H=n.features)==null?void 0:H.streamAnimation)},co=()=>{var ht,xt,Be,Le;if(!W())return;let c=Pe.peekBanner,g=Pe.peekTextNode;if(!c||!g)return;if(I){c.classList.remove("persona-pill-peek--visible");return}let b=(ht=q==null?void 0:q.getMessages())!=null?ht:[],A;for(let Ke=b.length-1;Ke>=0;Ke--){let rt=b[Ke];if(rt.role==="assistant"&&rt.content){A=rt;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let H=A.content,_=!!A.streaming,U=xi(),$=vl(U),O=$.type!=="none"?Vs($.type,U==null?void 0:U.plugins):null,Ce=((xt=O==null?void 0:O.isAnimating)==null?void 0:xt.call(O,A))===!0,me=O!==null&&(_||Ce);me&&O&&!ms.has(O.name)&&(Ip(O,r),ms.add(O.name));let oe=me&&(O!=null&&O.containerClass)?O.containerClass:null,Te=(Be=g.dataset.personaPeekStreamClass)!=null?Be:null;Te&&Te!==oe&&(g.classList.remove(Te),delete g.dataset.personaPeekStreamClass),oe&&Te!==oe&&(g.classList.add(oe),g.dataset.personaPeekStreamClass=oe),me?(g.style.setProperty("--persona-stream-step",`${$.speed}ms`),g.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ve=me?Cl(H,$.buffer,O,A,_):H;if(me&&$.placeholder==="skeleton"&&_&&(!Ve||!Ve.trim())){let Ke=document.createElement("div"),rt=Gs();rt.classList.add("persona-pill-peek__skeleton"),Ke.appendChild(rt),gl(g,Ke)}else{let Ke=Math.max(0,Ve.length-100),rt=Ve.length>100?Ve.slice(-100):Ve,Wt=ia(rt);if(!me||!O){let D=Ve.length>100?`\u2026${rt}`:rt;g.textContent!==D&&(g.textContent=D)}else{let D=Wt;(O.wrap==="char"||O.wrap==="word")&&(D=js(Wt,O.wrap,`peek-${A.id}`,{skipTags:O.skipTags,startIndex:Ke}));let Ne=document.createElement("div");if(Ne.innerHTML=D,O.useCaret&&rt.length>0){let Ue=wl(),be=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Yt=be[be.length-1];Yt!=null&&Yt.parentNode?Yt.parentNode.insertBefore(Ue,Yt.nextSibling):Ne.appendChild(Ue)}gl(g,Ne),(Le=O.onAfterRender)==null||Le.call(O,{container:g,bubble:c,messageId:A.id,message:A,speed:$.speed,duration:$.duration})}}let Qe=Kn||Lo;c.classList.toggle("persona-pill-peek--visible",Qe)};if(W()){let c=Pe.peekBanner;if(c){let A=H=>{H.preventDefault(),H.stopPropagation(),Gt(!0,"user")};c.addEventListener("pointerdown",A),kt.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{Lo||(Lo=!0,co())},b=()=>{Lo&&(Lo=!1,co())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",b),kt.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",b)}),at&&(at.addEventListener("pointerenter",g),at.addEventListener("pointerleave",b),kt.push(()=>{at.removeEventListener("pointerenter",g),at.removeEventListener("pointerleave",b)}))}let bi=c=>{var Te,Ve,Se,dt,Qe,ht,xt,Be;let g=(Ve=(Te=n.launcher)==null?void 0:Te.composerBar)!=null?Ve:{},b=(Se=g.expandedSize)!=null?Se:"anchored",A=(dt=g.bottomOffset)!=null?dt:"16px",H=g.collapsedMaxWidth,_=(Qe=g.expandedMaxWidth)!=null?Qe:"880px",U=(ht=g.expandedTopOffset)!=null?ht:"5vh",$=(xt=g.modalMaxWidth)!=null?xt:"880px",O=(Be=g.modalMaxHeight)!=null?Be:"min(90vh, 800px)",Ce="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",oe=We.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",at){let Le=at.style;Le.bottom=A,Le.width=H!=null?H:""}if(c&&b!=="fullscreen"){if(b==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=$,oe.maxWidth=Ce,oe.maxHeight=O,oe.height=O;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${A} + ${me})`,oe.top=U,oe.width=_,oe.maxWidth=Ce}},Po=()=>{var O,Ce,me,oe,Te,Ve,Se,dt;if(!R())return;if(W()){let ht=(me=((Ce=(O=n.launcher)==null?void 0:O.composerBar)!=null?Ce:{}).expandedSize)!=null?me:"anchored",xt=I?"expanded":"collapsed";We.dataset.state=xt,We.dataset.expandedSize=ht,at&&(at.dataset.state=xt,at.dataset.expandedSize=ht),We.style.removeProperty("display"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),bi(I),j.style.display=I?"flex":"none",Nn(),I?(gi(),hi()):(us(),fs()),co();return}let c=Rr(n),g=(oe=r.ownerDocument.defaultView)!=null?oe:window,b=(Ve=(Te=n.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Ve:640,A=(dt=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?dt:!0,H=g.innerWidth<=b,_=A&&H&&M,U=Hn(n).reveal;I?(We.style.removeProperty("display"),We.style.display=c?"flex":"",We.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"),Cr?Cr.element.style.display="none":wr&&(wr.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!_?(We.style.removeProperty("display"),We.style.display="flex",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.setProperty("display","none","important"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.display="",We.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")),Cr?Cr.element.style.display=c?"none":"":wr&&(wr.style.display=c?"none":""))},Gt=(c,g="user")=>{var _,U;if(!R()||I===c)return;let b=I;I=c,Po();let A=(()=>{var Se,dt,Qe,ht,xt,Be,Le,Ke,rt,Wt;let $=(dt=(Se=n.launcher)==null?void 0:Se.sidebarMode)!=null?dt:!1,O=(Qe=r.ownerDocument.defaultView)!=null?Qe:window,Ce=(xt=(ht=n.launcher)==null?void 0:ht.mobileFullscreen)!=null?xt:!0,me=(Le=(Be=n.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Le:640,oe=O.innerWidth<=me,Te=Rr(n)&&Ce&&oe,Ve=W()&&((Wt=(rt=(Ke=n.launcher)==null?void 0:Ke.composerBar)==null?void 0:rt.expandedSize)!=null?Wt:"fullscreen")==="fullscreen";return $||Ce&&oe&&M||Te||Ve})();if(I&&A){if(!yr){let $=r.getRootNode(),O=$ instanceof ShadowRoot?$.host:r.closest(".persona-host");O&&(yr=Wp(O,(U=(_=n.launcher)==null?void 0:_.zIndex)!=null?U:Gr))}vr||(vr=Hp(r.ownerDocument))}else I||(yr==null||yr(),yr=null,vr==null||vr(),vr=null);I&&(xs(),pt()==="follow"?Yn(!0):cs());let H={open:I,source:g,timestamp:Date.now()};I&&!b?a.emit("widget:opened",H):!I&&b&&a.emit("widget:closed",H),a.emit("widget:state",{open:I,launcherEnabled:M,voiceActive:Rt.active,streaming:q.isStreaming()})},Ea=c=>{sr(c?"stop":"send"),K&&(K.disabled=c),Mn.buttons.forEach(g=>{g.disabled=c}),Oe.dataset.personaComposerStreaming=c?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},La=()=>{Rt.active||ee&&ee.focus()};a.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>La(),200)});let gs=()=>{var b,A,H,_,U,$,O,Ce,me,oe,Te;gr.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",nn.textContent=(_=(H=n.copy)==null?void 0:H.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",ee.placeholder=($=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?$:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let Ve=((O=n.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ve?"":"none",Ve?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(Ce=n.sendButton)==null?void 0:Ce.useIcon)!=null&&me)&&!(q!=null&&q.isStreaming())&&(je.textContent=(Te=(oe=n.copy)==null?void 0:oe.sendButtonLabel)!=null?Te:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Ln=null,tt=()=>{Ln==null&&(Ln=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ln),Ln=null;return}let g=Date.now();c.forEach(b=>{let A=Number(b.getAttribute("data-tool-elapsed"));A&&(b.textContent=Oi(g-A))})},100))};if(q=new _a(n,{onMessagesChanged(c){var A;Ko(nt,c,xe),tt(),q&&(c.some(_=>_.role==="user")?Mn.render([],q,ee,c):Mn.render(n.suggestionChips,q,ee,c,n.suggestionChipsConfig)),Yn(!Kn),mi(c);let g=[...c].reverse().find(H=>H.role==="user");c.length===0&&Go(),!wa||jo?(wa=!0,Aa=(A=g==null?void 0:g.id)!=null?A:null):g&&g.id!==Aa&&(Aa=g.id,fi(g.id));let b=Rt.lastUserMessageId;g&&g.id!==b&&(Rt.lastUserMessageId=g.id,a.emit("user:message",g)),Rt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Ma(c),co()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};St(ar,(H=>{var _,U,$,O;return H==="idle"?(_=g.idleText)!=null?_:jr.idle:H==="connecting"?(U=g.connectingText)!=null?U:jr.connecting:H==="connected"?($=g.connectedText)!=null?$:jr.connected:H==="error"?(O=g.errorText)!=null?O:jr.error:jr[H]})(c),g,c)},onStreamingChanged(c){Kn=c,Ea(c),q&&Ko(nt,q.getMessages(),xe),c||Yn(!0),co()},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":Ro(),Db();break;case"speaking":Ro(),Fb();break;default:c==="idle"&&q.isBargeInActive()?(Ro(),hs(),K==null||K.setAttribute("aria-label","End voice session")):(Rt.active=!1,Ro(),En("system"),an());break}},onArtifactsState(c){Zt=c,un(),Ma()}}),wt.current=q,wa=!0,((Af=(wf=n.voiceRecognition)==null?void 0:wf.provider)==null?void 0:Af.type)==="runtype")try{q.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&q.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(ge||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,c,g),Z==null||Z.processEvent(c,g),ge==null||ge.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;if(c){if(c.metadata&&(d=nu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length){jo=!0;try{q.hydrateMessages(c.messages)}finally{jo=!1}}(b=c.artifacts)!=null&&b.length&&q.hydrateArtifacts(c.artifacts,(A=c.selectedArtifactId)!=null?A:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let L=()=>{var g,b,A;!W()||I||!((A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||A)||Gt(!0,"auto")},z=c=>{var H;if(c.preventDefault(),q.isStreaming()){q.cancel(),Z==null||Z.reset(),G==null||G.update();return}let g=ee.value.trim(),b=(H=Mt==null?void 0:Mt.hasAttachments())!=null?H:!1;if(!g&&!b)return;L();let A;b&&(A=[],A.push(...Mt.getContentParts()),g&&A.push(Fs(g))),ee.value="",ee.style.height="auto",X(),q.sendMessage(g,{contentParts:A}),b&&Mt.clearAttachments()},B=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},te={...hl},ce=!1,X=()=>{te={...hl}},He=()=>q.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),$e=c=>{if(!ee)return;ce=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),ce=!1;let g=ee.value.length;ee.setSelectionRange(g,g)},mt=()=>{ce||X()},lt=c=>{if(ee){if(B()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ee.selectionStart===0&&ee.selectionEnd===0,b=$h({direction:c.key==="ArrowUp"?"up":"down",history:He(),currentValue:ee.value,atStart:g,state:te});if(te=b.state,b.handled){c.preventDefault(),b.value!==void 0&&$e(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(q.isStreaming()){c.preventDefault();return}X(),c.preventDefault(),je.click()}}},zt=c=>{c.key!=="Escape"||c.isComposing||q.isStreaming()&&c.composedPath().includes(j)&&(q.cancel(),Z==null||Z.reset(),G==null||G.update(),X(),c.preventDefault(),c.stopImmediatePropagation())},er=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!Mt)return;let g=bC(c.clipboardData);g.length!==0&&(c.preventDefault(),await Mt.handleFiles(g))},Jt=null,gt=!1,Ft=null,Ge=null,$r=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wr=(c="user")=>{var _,U,$,O,Ce,me,oe;if(gt||q.isStreaming())return;let g=$r();if(!g)return;Jt=new g;let A=(U=((_=n.voiceRecognition)!=null?_:{}).pauseDuration)!=null?U:2e3;Jt.continuous=!0,Jt.interimResults=!0,Jt.lang="en-US";let H=ee.value;Jt.onresult=Te=>{let Ve="",Se="";for(let Qe=0;Qe<Te.results.length;Qe++){let ht=Te.results[Qe],xt=ht[0].transcript;ht.isFinal?Ve+=xt+" ":Se=xt}let dt=H+Ve+Se;ee.value=dt,Ft&&clearTimeout(Ft),(Ve||Se)&&(Ft=window.setTimeout(()=>{let Qe=ee.value.trim();Qe&&Jt&&gt&&(tr(),ee.value="",ee.style.height="auto",q.sendMessage(Qe,{viaVoice:!0}))},A))},Jt.onerror=Te=>{Te.error!=="no-speech"&&tr()},Jt.onend=()=>{if(gt){let Te=ee.value.trim();Te&&Te!==H.trim()&&(ee.value="",ee.style.height="auto",q.sendMessage(Te,{viaVoice:!0})),tr()}};try{if(Jt.start(),gt=!0,Rt.active=!0,c!=="system"&&(Rt.manuallyDeactivated=!1),En(c),an(),K){let Te=($=n.voiceRecognition)!=null?$:{};Ge={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(O=Te.iconName)!=null?O:"mic",iconSize:parseFloat((oe=(me=Te.iconSize)!=null?me:(Ce=n.sendButton)==null?void 0:Ce.size)!=null?oe:"40")||24};let Ve=Te.recordingBackgroundColor,Se=Te.recordingIconColor,dt=Te.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Ve!=null?Ve:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let Qe=K.querySelector("svg");Qe&&Qe.setAttribute("stroke",Se)}dt&&(K.style.borderColor=dt),K.setAttribute("aria-label","Stop voice recognition")}}catch{tr("system")}},tr=(c="user")=>{if(gt){if(gt=!1,Ft&&(clearTimeout(Ft),Ft=null),Jt){try{Jt.stop()}catch{}Jt=null}if(Rt.active=!1,En(c),an(),K){if(K.classList.remove("persona-voice-recording"),Ge){K.style.backgroundColor=Ge.backgroundColor,K.style.color=Ge.color,K.style.borderColor=Ge.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",Ge.color||"currentColor"),Ge=null}K.setAttribute("aria-label","Start voice recognition")}}},qn=(c,g)=>{var ht,xt,Be,Le,Ke,rt,Wt,D;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((ht=c==null?void 0:c.provider)==null?void 0:ht.type)==="runtype";if(!(b||A))return null;let _=y("div","persona-send-button-wrapper"),U=y("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 $=(xt=c==null?void 0:c.iconName)!=null?xt:"mic",O=(Be=g==null?void 0:g.size)!=null?Be:"40px",Ce=(Le=c==null?void 0:c.iconSize)!=null?Le:O,me=parseFloat(Ce)||24,oe=(Ke=c==null?void 0:c.backgroundColor)!=null?Ke:g==null?void 0:g.backgroundColor,Te=(rt=c==null?void 0:c.iconColor)!=null?rt:g==null?void 0:g.textColor;U.style.width=Ce,U.style.height=Ce,U.style.minWidth=Ce,U.style.minHeight=Ce,U.style.fontSize="18px",U.style.lineHeight="1",Te?U.style.color=Te:U.style.color="var(--persona-text, #111827)";let Se=Me($,me,Te||"currentColor",1.5);Se?U.appendChild(Se):U.textContent="\u{1F3A4}",oe?U.style.backgroundColor=oe: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 dt=(Wt=c==null?void 0:c.tooltipText)!=null?Wt:"Start voice recognition";if(((D=c==null?void 0:c.showTooltip)!=null?D:!1)&&dt){let Ne=y("div","persona-send-button-tooltip");Ne.textContent=dt,_.appendChild(Ne)}return{micButton:U,micButtonWrapper:_}},ed=()=>{var g,b,A,H,_;if(!K||Ge)return;let c=(g=n.voiceRecognition)!=null?g:{};Ge={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((_=(H=c.iconSize)!=null?H:(A=n.sendButton)==null?void 0:A.size)!=null?_:"40")||24}},td=(c,g)=>{var _,U,$,O,Ce;if(!K)return;let b=K.querySelector("svg");b&&b.remove();let A=(Ce=Ge==null?void 0:Ge.iconSize)!=null?Ce:parseFloat((O=($=(_=n.voiceRecognition)==null?void 0:_.iconSize)!=null?$:(U=n.sendButton)==null?void 0:U.size)!=null?O:"40")||24,H=Me(c,A,g,1.5);H&&K.appendChild(H)},yi=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hs=()=>{var H;if(!K)return;ed();let c=(H=n.voiceRecognition)!=null?H:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,A=c.recordingBorderColor;if(yi(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let _=K.querySelector("svg");_&&_.setAttribute("stroke",b)}A&&(K.style.borderColor=A),K.setAttribute("aria-label","Stop voice recognition")},Db=()=>{var $,O,Ce,me,oe,Te,Ve,Se;if(!K)return;ed();let c=($=n.voiceRecognition)!=null?$:{},g=q.getVoiceInterruptionMode(),b=(O=c.processingIconName)!=null?O:"loader",A=(me=(Ce=c.processingIconColor)!=null?Ce:Ge==null?void 0:Ge.color)!=null?me:"",H=(Te=(oe=c.processingBackgroundColor)!=null?oe:Ge==null?void 0:Ge.backgroundColor)!=null?Te:"",_=(Se=(Ve=c.processingBorderColor)!=null?Ve:Ge==null?void 0:Ge.borderColor)!=null?Se:"";yi(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=H,K.style.borderColor=_;let U=A||"currentColor";K.style.color=U,td(b,U),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},Fb=()=>{var Ce,me,oe,Te,Ve,Se,dt,Qe,ht,xt,Be,Le;if(!K)return;ed();let c=(Ce=n.voiceRecognition)!=null?Ce:{},g=q.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(me=c.speakingIconName)!=null?me:b,H=(Se=c.speakingIconColor)!=null?Se:g==="barge-in"?(Te=(oe=c.recordingIconColor)!=null?oe:Ge==null?void 0:Ge.color)!=null?Te:"":(Ve=Ge==null?void 0:Ge.color)!=null?Ve:"",_=(ht=c.speakingBackgroundColor)!=null?ht:g==="barge-in"?(dt=c.recordingBackgroundColor)!=null?dt:"var(--persona-voice-recording-bg, #ef4444)":(Qe=Ge==null?void 0:Ge.backgroundColor)!=null?Qe:"",U=(Le=c.speakingBorderColor)!=null?Le:g==="barge-in"?(xt=c.recordingBorderColor)!=null?xt:"":(Be=Ge==null?void 0:Ge.borderColor)!=null?Be:"";yi(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=_,K.style.borderColor=U;let $=H||"currentColor";K.style.color=$,td(A,$);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",O),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},Ro=()=>{var c,g,b;K&&(yi(),Ge&&(K.style.backgroundColor=(c=Ge.backgroundColor)!=null?c:"",K.style.color=(g=Ge.color)!=null?g:"",K.style.borderColor=(b=Ge.borderColor)!=null?b:"",td(Ge.iconName,Ge.color||"currentColor"),Ge=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},vi=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=q.getVoiceStatus(),A=q.getVoiceInterruptionMode();if(A==="none"&&(b==="processing"||b==="speaking"))return;if(A==="cancel"&&(b==="processing"||b==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{Rt.active=!1,Rt.manuallyDeactivated=!0,an(),En("user"),Ro()});return}q.toggleVoice().then(()=>{Rt.active=q.isVoiceActive(),Rt.manuallyDeactivated=!q.isVoiceActive(),an(),En("user"),q.isVoiceActive()?hs():Ro()});return}if(gt){let b=ee.value.trim();Rt.manuallyDeactivated=!0,an(),tr("user"),b&&(ee.value="",ee.style.height="auto",q.sendMessage(b))}else Rt.manuallyDeactivated=!1,an(),Wr("user")};_r=vi,K&&(K.addEventListener("click",vi),kt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Ro()):tr("system"),K&&K.removeEventListener("click",vi)}));let Nb=a.on("assistant:complete",()=>{ns&&(Rt.active||Rt.manuallyDeactivated||ns==="assistant"&&!Rt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Rt.active&&!Rt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{Rt.active=q.isVoiceActive(),En("auto"),q.isVoiceActive()&&hs()}):Wr("auto"))},600))});kt.push(Nb);let Ob=a.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});kt.push(Ob);let Pa=()=>{Gt(!I,"user")},Cr=null,wr=null;if(M&&!W()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Xs(n,Pa).element,onToggle:Pa});g&&(wr=g)}wr||(Cr=Xs(n,Pa))}Cr?r.appendChild(Cr.element):wr&&r.appendChild(wr),Po(),Mn.render(n.suggestionChips,q,ee,void 0,n.suggestionChipsConfig),gs(),Ea(q.isStreaming()),pt()==="follow"?Yn(!0):cs(),li(),k&&(!M||W()?setTimeout(()=>La(),0):I&&setTimeout(()=>La(),200));let xs=()=>{var O,Ce,me,oe,Te,Ve,Se,dt,Qe,ht,xt,Be,Le,Ke,rt,Wt,D,Ne,Ue,be,Yt,Kt;if(W()){Sr(),Po();return}let c=Rr(n),g=(Ce=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?Ce:!1,b=c||g||((oe=(me=n.launcher)==null?void 0:me.fullHeight)!=null?oe:!1),A=(Te=r.ownerDocument.defaultView)!=null?Te:window,H=(Se=(Ve=n.launcher)==null?void 0:Ve.mobileFullscreen)!=null?Se:!0,_=(Qe=(dt=n.launcher)==null?void 0:dt.mobileBreakpoint)!=null?Qe:640,U=A.innerWidth<=_,$=H&&U&&M;try{if($){Nn(),Do(r,n);return}if(T&&(T=!1,Nn(),Do(r,n)),!M&&!c){he.style.height="",he.style.width="";return}if(!g&&!c){let cr=(xt=(ht=n==null?void 0:n.launcher)==null?void 0:ht.width)!=null?xt:n==null?void 0:n.launcherWidth,Bt=cr!=null?cr:Cn;he.style.width=Bt,he.style.maxWidth=Bt}if(Gn(),!b){let cr=A.innerHeight,Bt=64,lr=(Le=(Be=n.launcher)==null?void 0:Be.heightOffset)!=null?Le:0,hn=Math.max(200,cr-Bt),Tr=Math.min(640,hn),ot=Math.max(200,Tr-lr);he.style.height=`${ot}px`}}finally{if(Sr(),Po(),I&&M){let Bt=((Ke=r.ownerDocument.defaultView)!=null?Ke:window).innerWidth<=((Wt=(rt=n.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Wt:640),lr=(Ne=(D=n.launcher)==null?void 0:D.sidebarMode)!=null?Ne:!1,hn=(be=(Ue=n.launcher)==null?void 0:Ue.mobileFullscreen)!=null?be:!0,Tr=Rr(n)&&hn&&Bt,ot=lr||hn&&Bt&&M||Tr;if(ot&&!vr){let Ut=r.getRootNode(),Er=Ut instanceof ShadowRoot?Ut.host:r.closest(".persona-host");Er&&!yr&&(yr=Wp(Er,(Kt=(Yt=n.launcher)==null?void 0:Yt.zIndex)!=null?Kt:Gr)),vr=Hp(r.ownerDocument)}else ot||(yr==null||yr(),yr=null,vr==null||vr(),vr=null)}}};xs();let vu=(Sf=r.ownerDocument.defaultView)!=null?Sf:window;if(vu.addEventListener("resize",xs),kt.push(()=>vu.removeEventListener("resize",xs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Sr()});c.observe(Oe),kt.push(()=>c.disconnect())}gn=ue.scrollTop;let Cu=xo(ue),_b=()=>{let c=ue.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:ue.ownerDocument.getSelection()},rd=()=>Qh(_b(),ue),wu=()=>{let c=ue.scrollTop,g=xo(ue),b=g<Cu;if(Cu=g,pt()!=="follow"){gn=c,sn();return}let{action:A,nextLastScrollTop:H}=bl({following:mn.isFollowing(),currentScrollTop:c,lastScrollTop:gn,nearBottom:ma(ue,Sa),userScrollThreshold:si,isAutoScrolling:Un||Vo||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gn=H,A==="resume"){rd()||Jn();return}A==="pause"&&ka()};if(ue.addEventListener("scroll",wu,{passive:!0}),kt.push(()=>ue.removeEventListener("scroll",wu)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{ui()});c.observe(nt),c.observe(ue),kt.push(()=>c.disconnect())}let Au=()=>{pt()==="follow"&&mn.isFollowing()&&rd()&&ka()},Su=ue.ownerDocument;Su.addEventListener("selectionchange",Au),kt.push(()=>{Su.removeEventListener("selectionchange",Au)});let Tu=c=>{if(pt()!=="follow")return;let g=yl({following:mn.isFollowing(),deltaY:c.deltaY,nearBottom:ma(ue,Sa),resumeWhenNearBottom:!0});g==="pause"?ka():g==="resume"&&!rd()&&Jn()};ue.addEventListener("wheel",Tu,{passive:!0}),kt.push(()=>ue.removeEventListener("wheel",Tu)),et.addEventListener("click",()=>{Go(),ue.scrollTop=ue.scrollHeight,gn=ue.scrollTop,Jn(),Yn(!0),sn()}),kt.push(()=>et.remove()),kt.push(()=>{as(),Go()});let Mu=()=>{F&&(kn&&(F.removeEventListener("click",kn),kn=null),R()?(F.style.display="",kn=()=>{Gt(!1,"user")},F.addEventListener("click",kn)):F.style.display="none")};Mu(),(()=>{let{clearChatButton:c}=Pe;c&&c.addEventListener("click",()=>{q.clearMessages(),ao.clear(),Jn(),zo(Pe.composerOverlay);try{localStorage.removeItem(es),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==es)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(),ge==null||ge.clear(),Z==null||Z.reset(),G==null||G.update()})})(),Dt&&Dt.addEventListener("submit",z),ee==null||ee.addEventListener("keydown",lt),ee==null||ee.addEventListener("input",mt),ee==null||ee.addEventListener("paste",er);let ku=(Tf=r.ownerDocument)!=null?Tf:document;ku.addEventListener("keydown",zt,!0);let Eu="persona-attachment-drop-active",bs=0,nd=()=>{bs=0,j.classList.remove(Eu)},Ra=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&Mt!==null},Lu=c=>{!Xl(c.dataTransfer)||!Ra()||(bs++,bs===1&&j.classList.add(Eu))},Pu=c=>{!Xl(c.dataTransfer)||!Ra()||(bs--,bs<=0&&nd())},Ru=c=>{!Xl(c.dataTransfer)||!Ra()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Iu=c=>{var b;if(!Xl(c.dataTransfer)||!Ra())return;c.preventDefault(),c.stopPropagation(),nd();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&Mt.handleFiles(g)},Io=!0;j.addEventListener("dragenter",Lu,Io),j.addEventListener("dragleave",Pu,Io),r.addEventListener("dragover",Ru,Io),r.addEventListener("drop",Iu,Io);let Ci=r.ownerDocument,Wu=c=>{Ra()&&c.preventDefault()},Hu=c=>{Ra()&&c.preventDefault()};Ci.addEventListener("dragover",Wu),Ci.addEventListener("drop",Hu),kt.push(()=>{Dt&&Dt.removeEventListener("submit",z),ee==null||ee.removeEventListener("keydown",lt),ee==null||ee.removeEventListener("input",mt),ee==null||ee.removeEventListener("paste",er),ku.removeEventListener("keydown",zt,!0)}),kt.push(()=>{j.removeEventListener("dragenter",Lu,Io),j.removeEventListener("dragleave",Pu,Io),r.removeEventListener("dragover",Ru,Io),r.removeEventListener("drop",Iu,Io),Ci.removeEventListener("dragover",Wu),Ci.removeEventListener("drop",Hu),nd()}),kt.push(()=>{q.cancel()}),Cr?kt.push(()=>{Cr==null||Cr.destroy()}):wr&&kt.push(()=>{wr==null||wr.remove()});let kr={update(c){var Zn,Pr,Qr,In,Yo,Zo,wi,ys,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,zf,$f,Vf,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,bm,ym,vm,Cm,wm,Am,Sm,Tm,Mm,km,Em,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,zm,$m,Vm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,ng,og,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,bg,yg,vg,Cg,wg,Ag,Sg,Tg,Mg,kg,Eg,Lg,Pg;let g=n.toolCall,b=n.messageActions,A=(Zn=n.layout)==null?void 0:Zn.messages,H=n.colorScheme,_=n.loadingIndicator,U=n.iterationDisplay,$=(Pr=n.features)==null?void 0:Pr.showReasoning,O=(Qr=n.features)==null?void 0:Qr.showToolCalls,Ce=(In=n.features)==null?void 0:In.toolCallDisplay,me=(Yo=n.features)==null?void 0:Yo.reasoningDisplay;n={...n,...c},Nn(),Do(r,n),_l(r,n),Ul(r,n),un(),n.colorScheme!==H&&To();let oe=ti.getForInstance(n.plugins);o.length=0,o.push(...oe),M=(wi=(Zo=n.launcher)==null?void 0:Zo.enabled)!=null?wi:!0,E=(If=(ys=n.launcher)==null?void 0:ys.autoExpand)!=null?If:!1,Je=(Hf=(Wf=n.features)==null?void 0:Wf.showReasoning)!=null?Hf:!0,we=(Df=(Bf=n.features)==null?void 0:Bf.showToolCalls)!=null?Df:!0,Ae=(Nf=(Ff=n.features)==null?void 0:Ff.scrollToBottom)!=null?Nf:{};let Te=pt();qe=(_f=(Of=n.features)==null?void 0:Of.scrollBehavior)!=null?_f:{},Te!==pt()&&(Go(),Jn()),cn(),sn();let Ve=De;if(De=(qf=(Uf=n.features)==null?void 0:Uf.showEventStreamToggle)!=null?qf:!1,De&&!Ve){if(ge||(re=new Zs(J),ge=new Ys(Q,re),Z=Z!=null?Z:new ei,re.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),q.setSSEEventCallback((Y,Nt)=>{var rr;(rr=n.onSSEEvent)==null||rr.call(n,Y,Nt),Z==null||Z.processEvent(Y,Nt),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(Nt)})})),!Ct&&Fe){let Y=($f=(zf=n.features)==null?void 0:zf.eventStream)==null?void 0:$f.classNames,Nt="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"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");Ct=y("button",Nt),Ct.style.width="28px",Ct.style.height="28px",Ct.style.color=rn.actionIconColor,Ct.type="button",Ct.setAttribute("aria-label","Event Stream"),Ct.title="Event Stream";let rr=Me("activity","18px","currentColor",1.5);rr&&Ct.appendChild(rr);let vt=Pe.clearChatButtonWrapper,qt=Pe.closeButtonWrapper,Hr=vt||qt;Hr&&Hr.parentNode===Fe?Fe.insertBefore(Ct,Hr):Fe.appendChild(Ct),Ct.addEventListener("click",()=>{pe?on():An()})}}else!De&&Ve&&(on(),Ct&&(Ct.remove(),Ct=null),ge==null||ge.clear(),re==null||re.destroy(),ge=null,re=null,Z==null||Z.reset(),Z=null);if(((Vf=n.launcher)==null?void 0:Vf.enabled)===!1&&Cr&&(Cr.destroy(),Cr=null),((jf=n.launcher)==null?void 0:jf.enabled)===!1&&wr&&(wr.remove(),wr=null),((Gf=n.launcher)==null?void 0:Gf.enabled)!==!1&&!Cr&&!wr){let Y=o.find(Nt=>Nt.renderLauncher);if(Y!=null&&Y.renderLauncher){let Nt=Y.renderLauncher({config:n,defaultRenderer:()=>Xs(n,Pa).element,onToggle:Pa});Nt&&(wr=Nt,r.appendChild(wr))}wr||(Cr=Xs(n,Pa),r.appendChild(Cr.element))}Cr&&Cr.update(n),Re&&((Kf=n.launcher)==null?void 0:Kf.title)!==void 0&&(Re.textContent=n.launcher.title),Xe&&((Xf=n.launcher)==null?void 0:Xf.subtitle)!==void 0&&(Xe.textContent=n.launcher.subtitle);let Se=(Qf=n.layout)==null?void 0:Qf.header;if((Se==null?void 0:Se.layout)!==C&&Fe){let Y=Se?$a(n,Se,{showClose:R(),onClose:()=>Gt(!1,"user")}):bo({config:n,showClose:R(),onClose:()=>Gt(!1,"user")});Fe.replaceWith(Y.header),Fe=Y.header,fe=Y.iconHolder,Re=Y.headerTitle,Xe=Y.headerSubtitle,F=Y.closeButton,C=Se==null?void 0:Se.layout}else if(Se&&(fe&&(fe.style.display=Se.showIcon===!1?"none":""),Re&&(Re.style.display=Se.showTitle===!1?"none":""),Xe&&(Xe.style.display=Se.showSubtitle===!1?"none":""),F&&(F.style.display=Se.showCloseButton===!1?"none":""),Pe.clearChatButtonWrapper)){let Y=Se.showClearChat;if(Y!==void 0){Pe.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:Nt}=Pe;Nt&&!Nt.classList.contains("persona-absolute")&&(Y?Nt.classList.remove("persona-ml-auto"):Nt.classList.add("persona-ml-auto"))}}let Qe=((Jf=n.layout)==null?void 0:Jf.showHeader)!==!1;Fe&&(Fe.style.display=Qe?"":"none");let ht=((Yf=n.layout)==null?void 0:Yf.showFooter)!==!1;Oe&&(Oe.style.display=ht?"":"none"),Sr(),sn(),M!==w?M?Gt(E,"auto"):(I=!0,Po()):E!==h&&Gt(E,"auto"),h=E,w=M,xs(),Mu();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ke=JSON.stringify(n.messageActions)!==JSON.stringify(b),rt=JSON.stringify((Zf=n.layout)==null?void 0:Zf.messages)!==JSON.stringify(A),Wt=((em=n.loadingIndicator)==null?void 0:em.render)!==(_==null?void 0:_.render)||((tm=n.loadingIndicator)==null?void 0:tm.renderIdle)!==(_==null?void 0:_.renderIdle)||((rm=n.loadingIndicator)==null?void 0:rm.showBubble)!==(_==null?void 0:_.showBubble),D=n.iterationDisplay!==U,Ne=((om=(nm=n.features)==null?void 0:nm.showReasoning)!=null?om:!0)!==($!=null?$:!0)||((sm=(am=n.features)==null?void 0:am.showToolCalls)!=null?sm:!0)!==(O!=null?O:!0)||JSON.stringify((im=n.features)==null?void 0:im.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((lm=n.features)==null?void 0:lm.reasoningDisplay)!==JSON.stringify(me);(Le||Ke||rt||Wt||D||Ne)&&q&&(rs++,Ko(nt,q.getMessages(),xe));let be=(dm=n.launcher)!=null?dm:{},Yt=(cm=be.headerIconHidden)!=null?cm:!1,Kt=(um=(pm=n.layout)==null?void 0:pm.header)==null?void 0:um.showIcon,cr=Yt||Kt===!1,Bt=be.headerIconName,lr=(fm=be.headerIconSize)!=null?fm:"48px";if(fe){let Y=j.querySelector(".persona-border-b-persona-divider"),Nt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(cr)fe.style.display="none",Y&&Nt&&!Y.contains(Nt)&&Y.insertBefore(Nt,Y.firstChild);else{if(fe.style.display="",fe.style.height=lr,fe.style.width=lr,Y&&Nt&&(Y.contains(fe)?fe.nextSibling!==Nt&&(fe.remove(),Y.insertBefore(fe,Nt)):Y.insertBefore(fe,Nt)),Bt){let vt=parseFloat(lr)||24,qt=Me(Bt,vt*.6,"#ffffff",2);qt?fe.replaceChildren(qt):fe.textContent=(mm=be.agentIconText)!=null?mm:"\u{1F4AC}"}else if(be.iconUrl){let vt=fe.querySelector("img");if(vt)vt.src=be.iconUrl,vt.style.height=lr,vt.style.width=lr;else{let qt=document.createElement("img");qt.src=be.iconUrl,qt.alt="",qt.className="persona-rounded-xl persona-object-cover",qt.style.height=lr,qt.style.width=lr,fe.replaceChildren(qt)}}else{let vt=fe.querySelector("svg"),qt=fe.querySelector("img");(vt||qt)&&fe.replaceChildren(),fe.textContent=(gm=be.agentIconText)!=null?gm:"\u{1F4AC}"}let rr=fe.querySelector("img");rr&&(rr.style.height=lr,rr.style.width=lr)}}let hn=(xm=(hm=n.layout)==null?void 0:hm.header)==null?void 0:xm.showTitle,Tr=(ym=(bm=n.layout)==null?void 0:bm.header)==null?void 0:ym.showSubtitle;if(Re&&(Re.style.display=hn===!1?"none":""),Xe&&(Xe.style.display=Tr===!1?"none":""),F){((Cm=(vm=n.layout)==null?void 0:vm.header)==null?void 0:Cm.showCloseButton)===!1?F.style.display="none":F.style.display="";let Nt=(wm=be.closeButtonSize)!=null?wm:"32px",rr=(Am=be.closeButtonPlacement)!=null?Am:"inline";F.style.height=Nt,F.style.width=Nt;let{closeButtonWrapper:vt}=Pe,qt=rr==="top-right",Hr=vt==null?void 0:vt.classList.contains("persona-absolute");if(vt&&qt!==Hr)if(vt.remove(),qt)vt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(vt);else{let At=(Tm=(Sm=be.clearChat)==null?void 0:Sm.placement)!=null?Tm:"inline",Br=(km=(Mm=be.clearChat)==null?void 0:Mm.enabled)!=null?km:!0;vt.className=Br&&At==="inline"?"":"persona-ml-auto";let dn=j.querySelector(".persona-border-b-persona-divider");dn&&dn.appendChild(vt)}if(F.style.color=be.closeButtonColor||rn.actionIconColor,be.closeButtonBackgroundColor?(F.style.backgroundColor=be.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),be.closeButtonBorderWidth||be.closeButtonBorderColor){let At=be.closeButtonBorderWidth||"0px",Br=be.closeButtonBorderColor||"transparent";F.style.border=`${At} solid ${Br}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");be.closeButtonBorderRadius?(F.style.borderRadius=be.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),be.closeButtonPaddingX?(F.style.paddingLeft=be.closeButtonPaddingX,F.style.paddingRight=be.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),be.closeButtonPaddingY?(F.style.paddingTop=be.closeButtonPaddingY,F.style.paddingBottom=be.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Vr=(Em=be.closeButtonIconName)!=null?Em:"x",zn=(Lm=be.closeButtonIconText)!=null?Lm:"\xD7";F.innerHTML="";let Jr=Me(Vr,"28px","currentColor",1);Jr?F.appendChild(Jr):F.textContent=zn;let Ar=(Pm=be.closeButtonTooltipText)!=null?Pm:"Close chat",bn=(Rm=be.closeButtonShowTooltip)!=null?Rm:!0;if(F.setAttribute("aria-label",Ar),vt&&(vt._cleanupTooltip&&(vt._cleanupTooltip(),delete vt._cleanupTooltip),bn&&Ar)){let At=null,Br=()=>{if(At||!F)return;let ea=F.ownerDocument,vs=ea.body;if(!vs)return;At=to(ea,"div","persona-clear-chat-tooltip"),At.textContent=Ar;let Cs=to(ea,"div");Cs.className="persona-clear-chat-tooltip-arrow",At.appendChild(Cs);let ta=F.getBoundingClientRect();At.style.position="fixed",At.style.zIndex=String(Fo),At.style.left=`${ta.left+ta.width/2}px`,At.style.top=`${ta.top-8}px`,At.style.transform="translate(-50%, -100%)",vs.appendChild(At)},dn=()=>{At&&At.parentNode&&(At.parentNode.removeChild(At),At=null)};vt.addEventListener("mouseenter",Br),vt.addEventListener("mouseleave",dn),F.addEventListener("focus",Br),F.addEventListener("blur",dn),vt._cleanupTooltip=()=>{dn(),vt&&(vt.removeEventListener("mouseenter",Br),vt.removeEventListener("mouseleave",dn)),F&&(F.removeEventListener("focus",Br),F.removeEventListener("blur",dn))}}}let{clearChatButton:ot,clearChatButtonWrapper:Ut}=Pe;if(ot){let Y=(Im=be.clearChat)!=null?Im:{},Nt=(Wm=Y.enabled)!=null?Wm:!0,rr=(Bm=(Hm=n.layout)==null?void 0:Hm.header)==null?void 0:Bm.showClearChat,vt=rr!==void 0?rr:Nt,qt=(Dm=Y.placement)!=null?Dm:"inline";if(Ut){Ut.style.display=vt?"":"none";let{closeButtonWrapper:Hr}=Pe;!W()&&Hr&&!Hr.classList.contains("persona-absolute")&&(vt?Hr.classList.remove("persona-ml-auto"):Hr.classList.add("persona-ml-auto"));let Vr=qt==="top-right",zn=Ut.classList.contains("persona-absolute");if(!W()&&Vr!==zn&&vt){if(Ut.remove(),Vr)Ut.className="persona-absolute persona-top-4 persona-z-50",Ut.style.right="48px",j.style.position="relative",j.appendChild(Ut);else{Ut.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ut.style.right="";let Ar=j.querySelector(".persona-border-b-persona-divider"),bn=Pe.closeButtonWrapper;Ar&&bn&&bn.parentElement===Ar?Ar.insertBefore(Ut,bn):Ar&&Ar.appendChild(Ut)}let Jr=Pe.closeButtonWrapper;Jr&&!Jr.classList.contains("persona-absolute")&&(Vr?Jr.classList.add("persona-ml-auto"):Jr.classList.remove("persona-ml-auto"))}}if(vt){if(!W()){let At=(Fm=Y.size)!=null?Fm:"32px";ot.style.height=At,ot.style.width=At}let Hr=(Nm=Y.iconName)!=null?Nm:"refresh-cw",Vr=(Om=Y.iconColor)!=null?Om:"";ot.style.color=Vr||rn.actionIconColor,ot.innerHTML="";let zn=W()?"14px":"20px",Jr=Me(Hr,zn,"currentColor",2);if(Jr&&ot.appendChild(Jr),Y.backgroundColor?(ot.style.backgroundColor=Y.backgroundColor,ot.classList.remove("hover:persona-bg-gray-100")):(ot.style.backgroundColor="",ot.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let At=Y.borderWidth||"0px",Br=Y.borderColor||"transparent";ot.style.border=`${At} solid ${Br}`,ot.classList.remove("persona-border-none")}else ot.style.border="",ot.classList.add("persona-border-none");Y.borderRadius?(ot.style.borderRadius=Y.borderRadius,ot.classList.remove("persona-rounded-full")):(ot.style.borderRadius="",ot.classList.add("persona-rounded-full")),Y.paddingX?(ot.style.paddingLeft=Y.paddingX,ot.style.paddingRight=Y.paddingX):(ot.style.paddingLeft="",ot.style.paddingRight=""),Y.paddingY?(ot.style.paddingTop=Y.paddingY,ot.style.paddingBottom=Y.paddingY):(ot.style.paddingTop="",ot.style.paddingBottom="");let Ar=(_m=Y.tooltipText)!=null?_m:"Clear chat",bn=(Um=Y.showTooltip)!=null?Um:!0;if(ot.setAttribute("aria-label",Ar),Ut&&(Ut._cleanupTooltip&&(Ut._cleanupTooltip(),delete Ut._cleanupTooltip),bn&&Ar)){let At=null,Br=()=>{if(At||!ot)return;let ea=ot.ownerDocument,vs=ea.body;if(!vs)return;At=to(ea,"div","persona-clear-chat-tooltip"),At.textContent=Ar;let Cs=to(ea,"div");Cs.className="persona-clear-chat-tooltip-arrow",At.appendChild(Cs);let ta=ot.getBoundingClientRect();At.style.position="fixed",At.style.zIndex=String(Fo),At.style.left=`${ta.left+ta.width/2}px`,At.style.top=`${ta.top-8}px`,At.style.transform="translate(-50%, -100%)",vs.appendChild(At)},dn=()=>{At&&At.parentNode&&(At.parentNode.removeChild(At),At=null)};Ut.addEventListener("mouseenter",Br),Ut.addEventListener("mouseleave",dn),ot.addEventListener("focus",Br),ot.addEventListener("blur",dn),Ut._cleanupTooltip=()=>{dn(),Ut&&(Ut.removeEventListener("mouseenter",Br),Ut.removeEventListener("mouseleave",dn)),ot&&(ot.removeEventListener("focus",Br),ot.removeEventListener("blur",dn))}}}}let Er=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ri],Rn=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[va.message,va.messageAndClick];S=ni({parsers:Er,handlers:Rn,getSessionMetadata:u,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),xe=Xx(n,S,ie),q.updateConfig(n),Ko(nt,q.getMessages(),xe),Mn.render(n.suggestionChips,q,ee,void 0,n.suggestionChipsConfig),gs(),Ea(q.isStreaming());let xn=((qm=n.voiceRecognition)==null?void 0:qm.enabled)===!0,Xo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Qo=(($m=(zm=n.voiceRecognition)==null?void 0:zm.provider)==null?void 0:$m.type)==="runtype";if(xn&&(Xo||Qo))if(!K||!ft){let Y=qn(n.voiceRecognition,n.sendButton);Y&&(K=Y.micButton,ft=Y.micButtonWrapper,Qt.insertBefore(ft,Fr),K.addEventListener("click",vi),K.disabled=q.isStreaming())}else{let Y=(Vm=n.voiceRecognition)!=null?Vm:{},Nt=(jm=n.sendButton)!=null?jm:{},rr=(Gm=Y.iconName)!=null?Gm:"mic",vt=(Km=Nt.size)!=null?Km:"40px",qt=(Xm=Y.iconSize)!=null?Xm:vt,Hr=parseFloat(qt)||24;K.style.width=qt,K.style.height=qt,K.style.minWidth=qt,K.style.minHeight=qt;let Vr=(Jm=(Qm=Y.iconColor)!=null?Qm:Nt.textColor)!=null?Jm:"currentColor";K.innerHTML="";let zn=Me(rr,Hr,Vr,2);zn?K.appendChild(zn):K.textContent="\u{1F3A4}";let Jr=(Ym=Y.backgroundColor)!=null?Ym:Nt.backgroundColor;Jr?K.style.backgroundColor=Jr:K.style.backgroundColor="",Vr?K.style.color=Vr:K.style.color="var(--persona-text, #111827)",Y.borderWidth?(K.style.borderWidth=Y.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Y.borderColor?K.style.borderColor=Y.borderColor:K.style.borderColor="",Y.paddingX?(K.style.paddingLeft=Y.paddingX,K.style.paddingRight=Y.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Y.paddingY?(K.style.paddingTop=Y.paddingY,K.style.paddingBottom=Y.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Ar=ft==null?void 0:ft.querySelector(".persona-send-button-tooltip"),bn=(Zm=Y.tooltipText)!=null?Zm:"Start voice recognition";if(((eg=Y.showTooltip)!=null?eg:!1)&&bn)if(Ar)Ar.textContent=bn,Ar.style.display="";else{let Br=document.createElement("div");Br.className="persona-send-button-tooltip",Br.textContent=bn,ft==null||ft.insertBefore(Br,K)}else Ar&&(Ar.style.display="none");ft.style.display="",K.disabled=q.isStreaming()}else K&&ft&&(ft.style.display="none",((rg=(tg=n.voiceRecognition)==null?void 0:tg.provider)==null?void 0:rg.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():gt&&tr());if(((ng=n.attachments)==null?void 0:ng.enabled)===!0)if(!ye||!it){let Y=(og=n.attachments)!=null?og:{},rr=(sg=((ag=n.sendButton)!=null?ag:{}).size)!=null?sg:"40px";st||(st=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),st.style.display="none",Dt.insertBefore(st,ee)),se||(se=document.createElement("input"),se.type="file",se.accept=((ig=Y.allowedTypes)!=null?ig:ho).join(","),se.multiple=((lg=Y.maxFiles)!=null?lg:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),Dt.insertBefore(se,ee)),ye=y("div","persona-send-button-wrapper"),it=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(dg=Y.buttonTooltipText)!=null?dg:"Attach file");let vt=(cg=Y.buttonIconName)!=null?cg:"paperclip",qt=rr,Hr=parseFloat(qt)||40,Vr=Math.round(Hr*.6);it.style.width=qt,it.style.height=qt,it.style.minWidth=qt,it.style.minHeight=qt,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let zn=Me(vt,Vr,"currentColor",1.5);zn?it.appendChild(zn):it.textContent="\u{1F4CE}",it.addEventListener("click",bn=>{bn.preventDefault(),se==null||se.click()}),ye.appendChild(it);let Jr=(pg=Y.buttonTooltipText)!=null?pg:"Attach file",Ar=y("div","persona-send-button-tooltip");Ar.textContent=Jr,ye.appendChild(Ar),Tt.append(ye),!Mt&&se&&st&&(Mt=fa.fromConfig(Y),Mt.setPreviewsContainer(st),se.addEventListener("change",async()=>{Mt&&(se!=null&&se.files)&&(await Mt.handleFileSelect(se.files),se.value="")})),j.querySelector(".persona-attachment-drop-overlay")||j.appendChild(Qx(Y.dropOverlay))}else{ye.style.display="";let Y=(ug=n.attachments)!=null?ug:{};se&&(se.accept=((fg=Y.allowedTypes)!=null?fg:ho).join(","),se.multiple=((mg=Y.maxFiles)!=null?mg:4)>1),Mt&&Mt.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ye&&(ye.style.display="none"),Mt&&Mt.clearAttachments(),(gg=j.querySelector(".persona-attachment-drop-overlay"))==null||gg.remove();let mr=(hg=n.sendButton)!=null?hg:{},Jo=(xg=mr.useIcon)!=null?xg:!1,Wo=(bg=mr.iconText)!=null?bg:"\u2191",Ho=mr.iconName,po=(yg=mr.tooltipText)!=null?yg:"Send message",ut=(vg=mr.showTooltip)!=null?vg:!1,Nr=(Cg=mr.size)!=null?Cg:"40px",Xr=mr.backgroundColor,Mr=mr.textColor;if(Jo){if(je.style.width=Nr,je.style.height=Nr,je.style.minWidth=Nr,je.style.minHeight=Nr,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",Mr?je.style.color=Mr:je.style.color="var(--persona-button-primary-fg, #ffffff)",Ho){let Y=parseFloat(Nr)||24,Nt=(Mr==null?void 0:Mr.trim())||"currentColor",rr=Me(Ho,Y,Nt,2);rr?je.appendChild(rr):je.textContent=Wo}else je.textContent=Wo;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Xr?(je.style.backgroundColor=Xr,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(Ag=(wg=n.copy)==null?void 0:wg.sendButtonLabel)!=null?Ag:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.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",Xr?(je.style.backgroundColor=Xr,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),Mr?je.style.color=Mr:je.classList.add("persona-text-white");mr.borderWidth?(je.style.borderWidth=mr.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),mr.borderColor?je.style.borderColor=mr.borderColor:je.style.borderColor="",mr.paddingX?(je.style.paddingLeft=mr.paddingX,je.style.paddingRight=mr.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),mr.paddingY?(je.style.paddingTop=mr.paddingY,je.style.paddingBottom=mr.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let bt=Fr==null?void 0:Fr.querySelector(".persona-send-button-tooltip");if(ut&&po)if(bt)bt.textContent=po,bt.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=po,Fr==null||Fr.insertBefore(Y,je)}else bt&&(bt.style.display="none");let Et=(Eg=(Sg=n.layout)==null?void 0:Sg.contentMaxWidth)!=null?Eg:W()?(kg=(Mg=(Tg=n.launcher)==null?void 0:Tg.composerBar)==null?void 0:Mg.contentMaxWidth)!=null?kg:"720px":void 0;Et?(nt.style.maxWidth=Et,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",Dt&&(Dt.style.maxWidth=Et,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),It&&(It.style.maxWidth=Et,It.style.marginLeft="auto",It.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""));let yt=(Lg=n.statusIndicator)!=null?Lg:{},ln=(Pg=yt.visible)!=null?Pg:!0;if(ar.style.display=ln?"":"none",q){let Y=q.getStatus();St(ar,(rr=>{var vt,qt,Hr,Vr;return rr==="idle"?(vt=yt.idleText)!=null?vt:jr.idle:rr==="connecting"?(qt=yt.connectingText)!=null?qt:jr.connecting:rr==="connected"?(Hr=yt.connectedText)!=null?Hr:jr.connected:rr==="error"?(Vr=yt.errorText)!=null?Vr:jr.error:jr[rr]})(Y),yt,Y)}ar.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Lr=yt.align==="left"?"persona-text-left":yt.align==="center"?"persona-text-center":"persona-text-right";ar.classList.add(Lr)},open(){R()&&Gt(!0,"api")},close(){R()&&Gt(!1,"api")},toggle(){R()&&Gt(!I,"api")},clearChat(){dr=!1,q.clearMessages(),ao.clear(),Jn();try{localStorage.removeItem(es),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==es)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(),ge==null||ge.clear(),Z==null||Z.reset(),G==null||G.update()},setMessage(c){return!ee||q.isStreaming()?!1:(!I&&R()&&Gt(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ee.value.trim();return g?(!I&&R()&&Gt(!0,"system"),ee.value="",ee.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return q.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(q.isVoiceActive()||(!I&&R()&&Gt(!0,"system"),Rt.manuallyDeactivated=!1,an(),q.toggleVoice().then(()=>{Rt.active=q.isVoiceActive(),En("user"),q.isVoiceActive()&&hs()})),!0):gt?!0:$r()?(!I&&R()&&Gt(!0,"system"),Rt.manuallyDeactivated=!1,an(),Wr("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{Rt.active=!1,Rt.manuallyDeactivated=!0,an(),En("user"),Ro()}),!0):!1:gt?(Rt.manuallyDeactivated=!0,an(),tr("user"),!0):!1},injectMessage(c){return!I&&R()&&Gt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!I&&R()&&Gt(!0,"system");let g=q.injectAssistantMessage(c);return N&&(N=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!I&&R()&&Gt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!I&&R()&&Gt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!I&&R()&&Gt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!I&&R()&&Gt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!I&&R()&&Gt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){ge&&(Z==null||Z.processEvent(c.type,c.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!De||!ge||An()},hideEventStream(){pe&&on()},isEventStreamVisible(){return pe},showArtifacts(){Dn(n)&&(dr=!1,un(),Ze==null||Ze.setMobileOpen(!0))},hideArtifacts(){Dn(n)&&(dr=!0,un())},upsertArtifact(c){return Dn(n)?(dr=!1,q.upsertArtifact(c)):null},selectArtifact(c){Dn(n)&&q.selectArtifact(c)},clearArtifacts(){Dn(n)&&q.clearArtifacts()},getArtifacts(){var c;return(c=q==null?void 0:q.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=q==null?void 0:q.getSelectedArtifactId())!=null?c:null},focusInput(){return M&&!I&&!W()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,g,b){let H=q.getMessages().find(_=>{var U;return _.variant==="approval"&&((U=_.approval)==null?void 0:U.id)===c});if(!(H!=null&&H.approval))throw new Error(`Approval not found: ${c}`);if(H.approval.toolType==="webmcp"){q.resolveWebMcpApproval(H.id,g);return}return q.resolveApproval(H.approval,g,b)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return R()&&I},isVoiceActive(){return Rt.active},getState(){return{open:R()&&I,launcherEnabled:M,voiceActive:Rt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!I&&R()&&Gt(!0,"system");let g=nt.querySelector(".persona-feedback-container");g&&g.remove();let b=Gl({onSubmit:async(A,H)=>{var _;q.isClientTokenMode()&&await q.submitCSATFeedback(A,H),(_=c==null?void 0:c.onSubmit)==null||_.call(c,A,H)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!I&&R()&&Gt(!0,"system");let g=nt.querySelector(".persona-feedback-container");g&&g.remove();let b=Kl({onSubmit:async(A,H)=>{var _;q.isClientTokenMode()&&await q.submitNPSFeedback(A,H),(_=c==null?void 0:c.onSubmit)==null||_.call(c,A,H)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return q.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return q.submitNPSFeedback(c,g)},destroy(){Ln!=null&&(clearInterval(Ln),Ln=null),kt.forEach(c=>c()),We.remove(),at==null||at.remove(),Cr==null||Cr.destroy(),wr==null||wr.remove(),kn&&F.removeEventListener("click",kn)}};if((((Mf=t==null?void 0:t.debugTools)!=null?Mf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:kr,getMessages:kr.getMessages,getStatus:kr.getStatus,getMetadata:kr.getPersistentMetadata,updateMetadata:kr.updatePersistentMetadata,clearHistory:()=>kr.clearChat(),setVoiceActive:b=>b?kr.startVoiceRecognition():kr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,kt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=r.getAttribute("data-persona-instance")||r.id||"persona-"+Math.random().toString(36).slice(2,8),g=$=>{let O=$.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&kr.focusInput()};if(window.addEventListener("persona:focusInput",g),kt.push(()=>{window.removeEventListener("persona:focusInput",g)}),De){let $=Ce=>{let me=Ce.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&kr.showEventStream()},O=Ce=>{let me=Ce.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&kr.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",O),kt.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",O)})}let b=$=>{let O=$.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&kr.showArtifacts()},A=$=>{let O=$.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&kr.hideArtifacts()},H=$=>{let O=$.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&kr.upsertArtifact(O.artifact)},_=$=>{let O=$.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&kr.selectArtifact(O.id)},U=$=>{let O=$.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&kr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",H),window.addEventListener("persona:selectArtifact",_),window.addEventListener("persona:clearArtifacts",U),kt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",H),window.removeEventListener("persona:selectArtifact",_),window.removeEventListener("persona:clearArtifacts",U)})}let Pn=yC(n.persistState);if(Pn&&R()){let c=vC(Pn.storage),g=`${Pn.keyPrefix}widget-open`,b=`${Pn.keyPrefix}widget-voice`,A=`${Pn.keyPrefix}widget-voice-mode`;if(c){let H=((kf=Pn.persist)==null?void 0:kf.openState)&&c.getItem(g)==="true",_=((Ef=Pn.persist)==null?void 0:Ef.voiceState)&&c.getItem(b)==="true",U=((Lf=Pn.persist)==null?void 0:Lf.voiceState)&&c.getItem(A)==="true";if(H&&setTimeout(()=>{kr.open(),setTimeout(()=>{var $;if(_||U)kr.startVoiceRecognition();else if(($=Pn.persist)!=null&&$.focusInput){let O=r.querySelector("textarea");O&&O.focus()}},100)},0),(Pf=Pn.persist)!=null&&Pf.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(Rf=Pn.persist)!=null&&Rf.voiceState&&(a.on("voice:state",$=>{c.setItem(b,$.active?"true":"false")}),a.on("user:message",$=>{c.setItem(A,$.viaVoice?"true":"false")})),Pn.clearOnChatClear){let $=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(A)},O=()=>$();window.addEventListener("persona:clear-chat",O),kt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return p&&R()&&setTimeout(()=>{kr.open()},0),co(),kr};var CC=(r,e)=>{let t=r.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},Jx=(r,e)=>{var n,o;let t=(o=(n=e==null?void 0:e.launcher)==null?void 0:n.enabled)!=null?o:!0;r.className="persona-host",r.style.height=t?"":"100%",r.style.display=t?"":"flex",r.style.flexDirection=t?"":"column",r.style.flex=t?"":"1 1 auto",r.style.minHeight=t?"":"0"},iu=r=>{r.style.position="",r.style.top="",r.style.bottom="",r.style.left="",r.style.right="",r.style.zIndex="",r.style.transform="",r.style.pointerEvents=""},Yx=r=>{r.style.inset="",r.style.width="",r.style.height="",r.style.maxWidth="",r.style.minWidth="",iu(r)},ou=r=>{r.style.transition=""},au=r=>{r.style.display="",r.style.flexDirection="",r.style.flex="",r.style.minHeight="",r.style.minWidth="",r.style.width="",r.style.height="",r.style.alignItems="",r.style.transition="",r.style.transform=""},su=r=>{r.style.width="",r.style.maxWidth="",r.style.minWidth="",r.style.flex="1 1 auto"},Jl=(r,e)=>{r.style.width="",r.style.minWidth="",r.style.maxWidth="",r.style.boxSizing="",e.style.alignItems=""},wC=(r,e,t,n,o)=>{o?t.parentElement!==e&&(r.replaceChildren(),e.replaceChildren(t,n),r.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),r.appendChild(t),r.appendChild(n))},AC=(r,e,t,n,o,a)=>{let s=a?e:r;o==="left"?s.firstElementChild!==n&&s.replaceChildren(n,t):s.lastElementChild!==n&&s.replaceChildren(t,n)},Zx=(r,e,t,n,o,a,s)=>{var v,x,S,M,E,k;let i=Hn(a),d=i.reveal==="push";wC(r,e,t,n,d),AC(r,e,t,n,i.side,d),r.dataset.personaHostLayout="docked",r.dataset.personaDockSide=i.side,r.dataset.personaDockOpen=s?"true":"false",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.height="100%",r.style.minHeight="0",r.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.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=r.ownerDocument.defaultView,p=(x=(v=a==null?void 0:a.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(M=(S=a==null?void 0:a.launcher)==null?void 0:S.mobileBreakpoint)!=null?M:640,u=l!=null?l.innerWidth<=f:!1;if(p&&u&&s){r.dataset.personaDockMobileFullscreen="true",r.removeAttribute("data-persona-dock-reveal"),au(e),ou(n),Yx(n),su(t),Jl(o,n),r.style.display="flex",r.style.flexDirection="column",r.style.alignItems="stretch",r.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((k=(E=a==null?void 0:a.launcher)==null?void 0:E.zIndex)!=null?k:Gr),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",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(r.removeAttribute("data-persona-dock-mobile-fullscreen"),Yx(n),i.reveal==="overlay"){r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="hidden",r.dataset.personaDockReveal="overlay",au(e),ou(n),su(t),Jl(o,n);let h=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=s?"translateX(0)":w;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=h,n.style.transform=C,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="hidden",r.dataset.personaDockReveal="push",ou(n),iu(n),Jl(o,n);let h=CC(i.width,r.clientWidth),w=Math.max(0,r.clientWidth),C=i.animate?"transform 180ms ease":"none",T=i.side==="right"?s?`translateX(-${h}px)`:"translateX(0)":s?"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=C,e.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${w}px`,t.style.maxWidth=`${w}px`,t.style.minWidth=`${w}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="",au(e),iu(n),su(t),Jl(o,n);let h=i.reveal==="emerge";h?r.dataset.personaDockReveal="emerge":r.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!s;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${w}`,n.style.width=w,n.style.maxWidth=w,n.style.minWidth=w,n.style.minHeight="0",n.style.position="relative",n.style.overflow=h||T?"hidden":"visible",n.style.transition=C,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")}},SC=(r,e)=>{let t=r.ownerDocument.createElement("div");return Jx(t,e),r.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Jx(t,n)},destroy(){t.remove()}}},TC=(r,e)=>{var E,k,h,w;let{ownerDocument:t}=r,n=r.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=r.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=r.nextSibling,s=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),p=t.createElement("div"),f=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.enabled)==null||k?(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(s,r),d.appendChild(r);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),Hn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{Zx(s,i,d,l,p,e,f)}),u.observe(s))},x=()=>{Zx(s,i,d,l,p,e,f),v()},S=s.ownerDocument.defaultView,M=()=>{x()};return S==null||S.addEventListener("resize",M),Hn(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),x(),{mode:"docked",host:p,shell:s,syncWidgetState(C){let T=C.launcherEnabled?C.open:!0;f!==T&&(f=T,x())},updateConfig(C){var T,W;e=C,((W=(T=e==null?void 0:e.launcher)==null?void 0:T.enabled)!=null?W:!0)===!1&&(f=!0),x()},destroy(){S==null||S.removeEventListener("resize",M),m(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(r,a):n.appendChild(r)),s.remove()}}},oi=(r,e)=>Rr(e)?TC(r,e):SC(r,e);var lu={},eb=!1,MC=r=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof r=="string"){let e=document.querySelector(r);if(!e)throw new Error(`Chat widget target "${r}" was not found`);return e}return r},kC=()=>{try{if(typeof lu!="undefined"&&lu.url)return new URL("../widget.css",lu.url).href}catch{}return null},tb=(r,e)=>{let t=kC(),n=()=>{if(!(r instanceof ShadowRoot)||r.querySelector("link[data-persona]"))return;let o=e.head.querySelector("link[data-persona]");if(!o)return;let a=o.cloneNode(!0);r.insertBefore(a,r.firstChild)};if(r instanceof ShadowRoot)if(t){let o=e.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.insertBefore(o,r.firstChild)}else n();else if(!e.head.querySelector("link[data-persona]")&&t){let a=e.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),e.head.appendChild(a)}},rb=r=>{let e=MC(r.target),t=r.useShadowDom===!0,n=e.ownerDocument,o=r.config,a=oi(e,o),s,i=[],d=(S,M)=>{var w,C;let k=!((C=(w=M==null?void 0:M.launcher)==null?void 0:w.enabled)!=null?C:!0)||Rr(M),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),k&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),t){let T=S.attachShadow({mode:"open"});T.appendChild(h),tb(T,n)}else S.appendChild(h),tb(S,n);return e.id&&h.setAttribute("data-persona-instance",e.id),h},l=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(S=>S()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},f=()=>{let S=d(a.host,o);s=Ql(S,o,{debugTools:r.debugTools}),p()},u=()=>{i.forEach(S=>S()),i=[],s.destroy()};f(),r.onChatReady?r.onChatReady():r.onReady&&(eb||(eb=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),r.onReady());let m=S=>{u(),a.destroy(),a=oi(e,S),o=S,f()},v={update(S){var C,T,W,R,I,N;let M={...o,...S,launcher:{...(C=o==null?void 0:o.launcher)!=null?C:{},...(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:{},...(N=(I=S==null?void 0:S.launcher)==null?void 0:I.dock)!=null?N:{}}}},E=Rr(o),k=Rr(M),h=Oo(o),w=Oo(M);if(E!==k||h!==w){m(M);return}o=M,a.updateConfig(o),s.update(S),l()},destroy(){u(),a.destroy(),r.windowKey&&typeof window!="undefined"&&delete window[r.windowKey]}},x=new Proxy(v,{get(S,M,E){if(M==="host")return a.host;if(M in S)return Reflect.get(S,M,E);let k=s[M];return typeof k=="function"?k.bind(s):k}});return r.windowKey&&typeof window!="undefined"&&(window[r.windowKey]=x),x};var ib=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),EC=new Set(["button","a","input","select","textarea","details","summary"]),LC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),du=/\b(product|card|item|listing|result)\b/i,pu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,PC=3e3,RC=100;function lb(r){let e=typeof r.className=="string"?r.className:"";if(du.test(e)||r.id&&du.test(r.id))return!0;for(let t=0;t<r.attributes.length;t++){let n=r.attributes[t];if(n.name.startsWith("data-")&&du.test(n.value))return!0}return!1}function db(r){var e;return pu.test(((e=r.textContent)!=null?e:"").trim())}function cb(r){var t;let e=r.querySelectorAll("a[href]");for(let n=0;n<e.length;n++){let o=(t=e[n].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function IC(r){return!!r.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function nb(r){let e=r.match(pu);return e?e[0]:null}function ob(r){var n,o,a;let e=(n=r.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:r.querySelector("a[href]");if(e&&((o=e.textContent)!=null&&o.trim())){let s=e.getAttribute("href");return{title:e.textContent.trim(),href:s&&s!=="#"?s:null}}let t=r.querySelector("h1, h2, h3, h4, h5, h6");return(a=t==null?void 0:t.textContent)!=null&&a.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function WC(r){let e=[],t=n=>{let o=n.trim();o&&!e.includes(o)&&e.push(o)};return r.querySelectorAll("button").forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),r.querySelectorAll('[role="button"]').forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),r.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;t((o=n.value)!=null?o:"")}),e.slice(0,6)}var HC="commerce-card",BC="result-card";function ab(r){return!lb(r)||!db(r)||!cb(r)&&!IC(r)?0:5200}function sb(r){var n;return!lb(r)||db(r)||!cb(r)||((n=r.textContent)!=null?n:"").trim().length<20||!(!!r.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!r.querySelector(".snippet, .description, p"))?0:2800}var uu=[{id:HC,scoreElement(r){return ab(r)},shouldSuppressDescendant(r,e,t){if(e===r||!r.contains(e))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||pu.test(n)&&n.length<32)}return!0},formatSummary(r,e){var d,l,p;if(ab(r)===0)return null;let{title:t,href:n}=ob(r),o=(p=(l=nb(((d=r.textContent)!=null?d:"").trim()))!=null?l:nb(e.text))!=null?p:"",a=WC(r);return[n&&t?`[${t}](${n})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||e.text.trim().slice(0,120),`selector: ${e.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
155
+ `)}},{id:BC,scoreElement(r){return sb(r)},formatSummary(r,e){if(sb(r)===0)return null;let{title:t,href:n}=ob(r);return[n&&t?`[${t}](${n})`:t||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
156
+ `)}}];function DC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function FC(r){var p,f,u,m,v,x,S,M,E,k,h,w,C;let e=(p=r.options)!=null?p:{},t=(u=(f=e.maxElements)!=null?f:r.maxElements)!=null?u:80,n=(v=(m=e.excludeSelector)!=null?m:r.excludeSelector)!=null?v:".persona-host",o=(S=(x=e.maxTextLength)!=null?x:r.maxTextLength)!=null?S:200,a=(E=(M=e.visibleOnly)!=null?M:r.visibleOnly)!=null?E:!0,s=(k=e.root)!=null?k:r.root,i=(h=e.mode)!=null?h:"structured",d=(w=e.maxCandidates)!=null?w:Math.max(500,t*10),l=(C=r.rules)!=null?C:uu;return i==="simple"&&r.rules&&r.rules.length>0?(DC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:l}}function cu(r){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^\w-])/g,"\\$1")}var NC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function OC(r){let e=r.tagName.toLowerCase(),t=r.getAttribute("role");return e==="a"&&r.hasAttribute("href")?"navigable":e==="input"||e==="select"||e==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":e==="button"||t==="button"||EC.has(e)||t&&LC.has(t)||r.hasAttribute("tabindex")||r.hasAttribute("onclick")||r.getAttribute("contenteditable")==="true"?"clickable":"static"}function pb(r){if(r.hidden)return!1;try{let e=getComputedStyle(r);if(e.display==="none"||e.visibility==="hidden")return!1}catch{}return!(r.style.display==="none"||r.style.visibility==="hidden")}function _C(r){let e={},t=r.id;t&&(e.id=t);let n=r.getAttribute("href");n&&(e.href=n);let o=r.getAttribute("aria-label");o&&(e["aria-label"]=o);let a=r.getAttribute("type");a&&(e.type=a);let s=r.getAttribute("value");s&&(e.value=s);let i=r.getAttribute("name");i&&(e.name=i);let d=r.getAttribute("role");d&&(e.role=d);for(let l=0;l<r.attributes.length;l++){let p=r.attributes[l];p.name.startsWith("data-")&&(e[p.name]=p.value)}return e}function fu(r){let e=r.tagName.toLowerCase();if(r.id){let o=`#${cu(r.id)}`;try{if(r.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of NC){let a=r.getAttribute(o);if(a){let s=`${e}[${o}="${cu(a)}"]`;try{if(r.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let t=Array.from(r.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${e}.${t.map(s=>cu(s)).join(".")}`;try{if(r.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let a=r.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${e}`)).indexOf(r);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(r.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=r.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${e}`)).indexOf(r);if(a>=0)return`${e}:nth-of-type(${a+1})`}return e}function UC(r){return r==="static"?RC:PC}function ub(r,e){var o;let t=r.tagName.toLowerCase(),n=((o=r.textContent)!=null?o:"").trim().substring(0,e);return{selector:fu(r),tagName:t,text:n,role:r.getAttribute("role"),interactivity:OC(r),attributes:_C(r)}}function qC(r,e,t,n){let o=UC(e.interactivity),a=null;for(let s of t){let i=s.scoreElement(r,e,n);i>0&&(o+=i,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function zC(r,e){var t;for(let n of r)if(e.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(e.el)&&n.formattingRule.shouldSuppressDescendant(n.el,e.el,e.enriched))return!0;return!1}function $C(r,e){let t={doc:e.ownerDocument,maxTextLength:r.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<r.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(ib.has(p)){i=s.nextNode();continue}if(r.excludeSelector)try{if(l.closest(r.excludeSelector)){i=s.nextNode();continue}}catch{}if(r.visibleOnly&&!pb(l)){i=s.nextNode();continue}let f=ub(l,r.maxTextLength),u=f.text.length>0,m=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(S=>S==="role");if(!u&&!m){i=s.nextNode();continue}if(n.has(f.selector)){i=s.nextNode();continue}n.add(f.selector);let{score:v,formattingRule:x}=qC(l,f,r.rules,t);o.push({el:l,domIndex:a,enriched:f,score:v,formattingRule:x}),a+=1}i=s.nextNode()}o.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=r.maxElements)break;zC(d,l)||d.push(l)}return d.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:f===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 m=l.formattingRule.formatSummary(l.el,l.enriched,t);m&&(p=m)}let f={...l.enriched};return p&&(f.formattedSummary=p),f})}function VC(r,e){let t=[],n=new Set,o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&t.length<r.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let d=a,l=d.tagName.toLowerCase();if(ib.has(l)){a=o.nextNode();continue}if(r.excludeSelector)try{if(d.closest(r.excludeSelector)){a=o.nextNode();continue}}catch{}if(r.visibleOnly&&!pb(d)){a=o.nextNode();continue}let p=ub(d,r.maxTextLength),f=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!f&&!u){a=o.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}a=o.nextNode()}let s=[],i=[];for(let d of t)d.interactivity!=="static"?s.push(d):i.push(d);return[...s,...i].slice(0,r.maxElements)}function fb(r={}){var n;let e=FC(r),t=(n=e.root)!=null?n:document.body;return t?e.mode==="simple"?VC(e,t):$C(e,t):[]}var Yl=100;function mb(r,e={}){var a;if(r.length===0)return"No page elements found.";let t=(a=e.mode)!=null?a:"structured",n=[];if(t==="structured"){let s=r.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&n.push(`Structured summaries:
157
+ ${s.map(i=>`- ${i.split(`
161
158
  `).join(`
162
159
  `)}`).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,ad)}" (clickable)`);n.push(`Interactive elements:
164
- ${a.join(`
165
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ad)}" (navigable)`);n.push(`Navigation links:
166
- ${a.join(`
167
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ad)}" (input)`);n.push(`Form inputs:
168
- ${a.join(`
169
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ad)}"`);n.push(`Content:
170
- ${a.join(`
160
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let s of r)t==="structured"&&s.formattedSummary||o[s.interactivity].push(s);if(o.clickable.length>0){let s=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Yl)}" (clickable)`);n.push(`Interactive elements:
161
+ ${s.join(`
162
+ `)}`)}if(o.navigable.length>0){let s=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Yl)}" (navigable)`);n.push(`Navigation links:
163
+ ${s.join(`
164
+ `)}`)}if(o.input.length>0){let s=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Yl)}" (input)`);n.push(`Form inputs:
165
+ ${s.join(`
166
+ `)}`)}if(o.static.length>0){let s=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Yl)}"`);n.push(`Content:
167
+ ${s.join(`
171
168
  `)}`)}return n.join(`
172
169
 
173
- `)}var Ly={name:"@runtypelabs/persona",version:"3.30.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./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"},"./plugin-kit":{types:"./dist/plugin-kit.d.ts",import:"./dist/plugin-kit.js",require:"./dist/plugin-kit.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:plugin-kit && pnpm run build:animations","build:plugin-kit":"tsup src/plugin-kit.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","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 Py=Ly.version;function Iy(){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 Ry(){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 Wy(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:no(t.colors.primary,.95),100:no(t.colors.primary,.9),200:no(t.colors.primary,.8),300:no(t.colors.primary,.7),400:no(t.colors.primary,.6),500:t.colors.primary,600:no(t.colors.primary,.8),700:no(t.colors.primary,.7),800:no(t.colors.primary,.6),900:no(t.colors.primary,.5),950:no(t.colors.primary,.45)}}),{...e,palette:r}}}}function By(){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 Hy(){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 no(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 Dy(t){return{name:t.name,version:t.version,transform:t.transform||(e=>e),cssVariables:t.cssVariables,afterResolve:t.afterResolve}}var JC={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"}}},Oy={components:{panel:{borderRadius:"0",shadow:"none"}}},Tu={id:"shop",label:"Shopping Assistant",config:{theme:JC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:wn},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?"]}},Mu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Oy}},ku={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Oy}},Eu={shop:Tu,minimal:Mu,fullscreen:ku};function Ny(t){return Eu[t]}var QC=`
170
+ `)}var gb="3.31.1";var hb=gb;function xb(){return{name:"@persona/accessibility",version:"1.0.0",transform(r){return{...r,semantic:{...r.semantic,colors:{...r.semantic.colors,interactive:{...r.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 bb(){return{name:"@persona/animations",version:"1.0.0",transform(r){return{...r,palette:{...r.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 yb(r){return{name:"@persona/brand",version:"1.0.0",transform(e){var n;let t={...e.palette};return(n=r.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:ro(r.colors.primary,.95),100:ro(r.colors.primary,.9),200:ro(r.colors.primary,.8),300:ro(r.colors.primary,.7),400:ro(r.colors.primary,.6),500:r.colors.primary,600:ro(r.colors.primary,.8),700:ro(r.colors.primary,.7),800:ro(r.colors.primary,.6),900:ro(r.colors.primary,.5),950:ro(r.colors.primary,.45)}}),{...e,palette:t}}}}function vb(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(r){return{...r,palette:{...r.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(r){return{...r,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Cb(){return{name:"@persona/high-contrast",version:"1.0.0",transform(r){return{...r,semantic:{...r.semantic,colors:{...r.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function ro(r,e){let t=parseInt(r.slice(1,3),16),n=parseInt(r.slice(3,5),16),o=parseInt(r.slice(5,7),16),a=Math.round(t+(255-t)*(1-e)),s=Math.round(n+(255-n)*(1-e)),i=Math.round(o+(255-o)*(1-e));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function wb(r){return{name:r.name,version:r.version,transform:r.transform||(e=>e),cssVariables:r.cssVariables,afterResolve:r.afterResolve}}var GC={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"}}},Ab={components:{panel:{borderRadius:"0",shadow:"none"}}},mu={id:"shop",label:"Shopping Assistant",config:{theme:GC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Cn},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?"]}},gu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ab}},hu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ab}},xu={shop:mu,minimal:gu,fullscreen:hu};function Sb(r){return xu[r]}var KC=`
174
171
  @keyframes persona-stream-wipe {
175
172
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
176
173
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -206,7 +203,7 @@ ${a.join(`
206
203
  mask-image: none !important;
207
204
  }
208
205
  }
209
- `.trim(),YC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:QC};ga(YC);var ZC=`
206
+ `.trim(),XC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:KC};ga(XC);var QC=`
210
207
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
211
208
  animation: persona-stream-glyph-cycle-fade
212
209
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -224,7 +221,7 @@ ${a.join(`
224
221
  opacity: 1 !important;
225
222
  }
226
223
  }
227
- `.trim(),si="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",eA=10,tA=120,Lu=120,rA=.4,nA=50,oA=t=>{var n;if(!t)return Lu;let r=((n=t.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Lu},jy=t=>{let e=t.closest(".persona-stream-glyph-cycle"),r=oA(e);return tA*r/Lu},Pu=t=>{let e=si[Math.floor(Math.random()*si.length)];return t&&e===t&&(e=si[(si.indexOf(e)+1)%si.length]),e},aA=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()<rA&&(o.textContent=Pu())}},_y=new WeakMap,Fy=25,$y=.5,sA=6,Uy=.25,qy=new WeakMap,zy=new WeakMap,iA=(t,e)=>{var o;if(!t)return Fy*$y;let r=qy.get(t);qy.set(t,e);let n=(o=zy.get(t))!=null?o:Fy;if(r!==void 0){let s=e-r;s>1&&(n=n*(1-Uy)+s*Uy,zy.set(t,n))}return Math.max(sA,n*$y)},es=new Map,lA=t=>{var r;let e=t.closest("[data-message-id]");return(r=e==null?void 0:e.dataset.messageId)!=null?r:null},dA=t=>{var e;t&&es.set(t,((e=es.get(t))!=null?e:0)+1)},cA=t=>{var r;if(!t)return;let e=(r=es.get(t))!=null?r:0;e<=1?es.delete(t):es.set(t,e-1)},Gy=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=Pu();let r=lA(t);r&&(t.dataset.glyphCycleMessageId=r),dA(r);let n=t.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=iA(n,o),a=jy(t),i=eA*a,d=o+i;if(n){let p=_y.get(n);p!==void 0&&(d=Math.max(d,p)),_y.set(n,d+s)}pA(t,e,d)},pA=(t,e,r)=>{var a;if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let n=jy(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,cA((d=t.dataset.glyphCycleMessageId)!=null?d:null),delete t.dataset.glyphCycleMessageId;return}let i=Pu(o);t.textContent=i,o=i,aA(t),setTimeout(s,n)};setTimeout(s,n)},Vy=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))Gy(n)},uA=t=>t.nodeType===1,fA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:ZC,bufferContent(t){if(t.length<nA)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=es.get(t.id))!=null?e:0)>0},onAttach(t){Vy(t);let e=new MutationObserver(r=>{for(let n of r)for(let o of Array.from(n.addedNodes))uA(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?Gy(o):Vy(o))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ga(fA);return eb(mA);})();
224
+ `.trim(),ai="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",JC=10,YC=120,bu=120,ZC=.4,ew=50,tw=r=>{var n;if(!r)return bu;let t=((n=r.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return t?parseFloat(t[1]):bu},Ib=r=>{let e=r.closest(".persona-stream-glyph-cycle"),t=tw(e);return YC*t/bu},yu=r=>{let e=ai[Math.floor(Math.random()*ai.length)];return r&&e===r&&(e=ai[(ai.indexOf(e)+1)%ai.length]),e},rw=r=>{let e=r.closest(".persona-stream-glyph-cycle");if(!e)return;let t=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let o of Array.from(t)){if(o===r){n=!0;continue}n&&Math.random()<ZC&&(o.textContent=yu())}},Tb=new WeakMap,Mb=25,kb=.5,nw=6,Eb=.25,Lb=new WeakMap,Pb=new WeakMap,ow=(r,e)=>{var o;if(!r)return Mb*kb;let t=Lb.get(r);Lb.set(r,e);let n=(o=Pb.get(r))!=null?o:Mb;if(t!==void 0){let a=e-t;a>1&&(n=n*(1-Eb)+a*Eb,Pb.set(r,n))}return Math.max(nw,n*kb)},ts=new Map,aw=r=>{var t;let e=r.closest("[data-message-id]");return(t=e==null?void 0:e.dataset.messageId)!=null?t:null},sw=r=>{var e;r&&ts.set(r,((e=ts.get(r))!=null?e:0)+1)},iw=r=>{var t;if(!r)return;let e=(t=ts.get(r))!=null?t:0;e<=1?ts.delete(r):ts.set(r,e-1)},Wb=r=>{var l;if(r.dataset.glyphCycleScheduled==="true")return;let e=(l=r.textContent)!=null?l:"";if(!e||/\s/.test(e))return;r.dataset.glyphCycleScheduled="true",r.dataset.glyphCycleFinal=e,r.setAttribute("data-preserve-runtime","stream-glyph-cycle"),r.textContent=yu();let t=aw(r);t&&(r.dataset.glyphCycleMessageId=t),sw(t);let n=r.closest(".persona-stream-glyph-cycle"),o=Date.now(),a=ow(n,o),s=Ib(r),i=JC*s,d=o+i;if(n){let p=Tb.get(n);p!==void 0&&(d=Math.max(d,p)),Tb.set(n,d+a)}lw(r,e,d)},lw=(r,e,t)=>{var s;if(r.dataset.glyphCycleStarted==="true")return;r.dataset.glyphCycleStarted="true";let n=Ib(r),o=(s=r.textContent)!=null?s:void 0,a=()=>{var d;if(!r.isConnected)return;if(Date.now()>=t){r.textContent=e,r.removeAttribute("data-preserve-runtime"),delete r.dataset.glyphCycleStarted,delete r.dataset.glyphCycleFinal,iw((d=r.dataset.glyphCycleMessageId)!=null?d:null),delete r.dataset.glyphCycleMessageId;return}let i=yu(o);r.textContent=i,o=i,rw(r),setTimeout(a,n)};setTimeout(a,n)},Rb=r=>{var t;let e=(t=r.querySelectorAll)==null?void 0:t.call(r,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))Wb(n)},dw=r=>r.nodeType===1,cw={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:QC,bufferContent(r){if(r.length<ew)return"";let e=0,t=-1,n=0;for(;n<r.length;){if(r[n]==="*"&&r[n+1]==="*"){e+=1,n+=2;continue}/\s/.test(r[n])&&e%2===0&&(t=n),n+=1}return t<0?"":r.slice(0,t)},isAnimating(r){var e;return((e=ts.get(r.id))!=null?e:0)>0},onAttach(r){Rb(r);let e=new MutationObserver(t=>{for(let n of t)for(let o of Array.from(n.addedNodes))dw(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?Wb(o):Rb(o))});return e.observe(r,{childList:!0,subtree:!0}),()=>e.disconnect()}};ga(cw);var Hb,Bb,Ca=typeof document!="undefined"&&(Bb=(Hb=document.currentScript)==null?void 0:Hb.src)!=null?Bb:null;xh(()=>{let r=Ca==null?void 0:Ca.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!r||r===Ca?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Ca!=null?Ca:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(r)});return Xb(pw);})();
228
225
  /*! Bundled license information:
229
226
 
230
227
  dompurify/dist/purify.es.mjs: