@runtypelabs/persona 3.29.1 → 3.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +15 -2547
  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 +6 -6
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +50 -50
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +164 -7
  13. package/dist/index.d.ts +164 -7
  14. package/dist/index.global.js +60 -60
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +49 -49
  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/plugin-kit.cjs +1 -0
  21. package/dist/plugin-kit.d.cts +98 -0
  22. package/dist/plugin-kit.d.ts +98 -0
  23. package/dist/plugin-kit.js +1 -0
  24. package/dist/smart-dom-reader.d.cts +157 -4
  25. package/dist/smart-dom-reader.d.ts +157 -4
  26. package/dist/theme-editor.cjs +40 -40
  27. package/dist/theme-editor.d.cts +161 -6
  28. package/dist/theme-editor.d.ts +161 -6
  29. package/dist/theme-editor.js +40 -40
  30. package/dist/theme-reference.cjs +1 -1
  31. package/dist/theme-reference.d.cts +2 -0
  32. package/dist/theme-reference.d.ts +2 -0
  33. package/dist/theme-reference.js +1 -1
  34. package/dist/widget.css +19 -0
  35. package/package.json +8 -2
  36. package/src/client.ts +6 -0
  37. package/src/components/approval-bubble.test.ts +320 -0
  38. package/src/components/approval-bubble.ts +190 -20
  39. package/src/components/launcher.ts +6 -3
  40. package/src/components/panel.ts +7 -1
  41. package/src/components/tool-bubble.test.ts +39 -0
  42. package/src/components/tool-bubble.ts +4 -0
  43. package/src/defaults.ts +14 -0
  44. package/src/generated/runtype-openapi-contract.ts +4 -0
  45. package/src/index-core.ts +1 -0
  46. package/src/plugin-kit.test.ts +230 -0
  47. package/src/plugin-kit.ts +294 -0
  48. package/src/plugins/types.ts +49 -2
  49. package/src/session.test.ts +161 -0
  50. package/src/session.ts +41 -3
  51. package/src/styles/widget.css +19 -0
  52. package/src/theme-editor/preview-utils.test.ts +10 -0
  53. package/src/theme-editor/preview-utils.ts +29 -1
  54. package/src/theme-editor/sections.test.ts +17 -0
  55. package/src/theme-editor/sections.ts +31 -0
  56. package/src/theme-reference.ts +2 -2
  57. package/src/types/theme.ts +2 -0
  58. package/src/types.ts +109 -2
  59. package/src/ui.approval-plugin.test.ts +204 -0
  60. package/src/ui.scroll.test.ts +383 -0
  61. package/src/ui.ts +539 -56
  62. package/src/utils/auto-follow.test.ts +91 -0
  63. package/src/utils/auto-follow.ts +68 -0
  64. package/src/utils/theme.test.ts +6 -2
  65. package/src/utils/theme.ts +0 -8
  66. package/src/utils/tokens.ts +6 -1
  67. package/src/webmcp-bridge.test.ts +66 -0
  68. package/src/webmcp-bridge.ts +49 -0
@@ -1,23 +1,23 @@
1
- "use strict";var AgentWidget=(()=>{var _y=Object.create;var hs=Object.defineProperty;var Fy=Object.getOwnPropertyDescriptor;var $y=Object.getOwnPropertyNames;var Uy=Object.getPrototypeOf,qy=Object.prototype.hasOwnProperty;var Tg=t=>{throw TypeError(t)};var zy=(t,e,r)=>e in t?hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Gn=(t,e)=>()=>(t&&(e=t(t=0)),e);var Mg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kg=(t,e)=>{for(var r in e)hs(t,r,{get:e[r],enumerable:!0})},Eg=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $y(e))!qy.call(t,o)&&o!==r&&hs(t,o,{get:()=>e[o],enumerable:!(n=Fy(e,o))||n.enumerable});return t};var ad=(t,e,r)=>(r=t!=null?_y(Uy(t)):{},Eg(e||!t||!t.__esModule?hs(r,"default",{value:t,enumerable:!0}):r,t)),Vy=t=>Eg(hs({},"__esModule",{value:!0}),t);var Ht=(t,e,r)=>zy(t,typeof e!="symbol"?e+"":e,r),jy=(t,e,r)=>e.has(t)||Tg("Cannot "+r);var Lg=(t,e,r)=>e.has(t)?Tg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Si=(t,e,r)=>(jy(t,e,"access private method"),r);function La(t,e){let r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let n=t.length;if(n!==e.length)return!1;for(let o=0;o<n;o++)if(!La(t[o],e[o]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(let a of n)if(!La(t[a],e[a]))return!1;return!0}return t===e}var Sd=Gn(()=>{"use strict"});function xn(t){return encodeURI(Yb(t))}function Yb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Wi=Gn(()=>{"use strict"});function uo(t,e=Object.create(null),r=r0,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t.$id||t.id;if(s){let a=new URL(s,r.href);a.hash.length>1?e[a.href]=t:(a.hash="",n===""?r=a:uo(t,e,r))}}else if(t!==!0&&t!==!1)return e;let o=r.href+(n?"#"+n:"");if(e[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(e[o]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),t.$ref&&t.__absolute_ref__===void 0){let s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){let s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(t0[s])continue;let a=`${n}/${xn(s)}`,i=t[s];if(Array.isArray(i)){if(Zb[s]){let d=i.length;for(let l=0;l<d;l++)uo(i[l],e,r,`${a}/${l}`)}}else if(e0[s])for(let d in i)uo(i[d],e,r,`${a}/${xn(d)}`);else uo(i,e,r,a)}return e}var Zb,e0,t0,r0,Bi=Gn(()=>{"use strict";Wi();Zb={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},e0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},t0={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},r0=typeof self!="undefined"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Xn(t){return t.test.bind(t)}function y0(t){return t%4===0&&(t%100!==0||t%400===0)}function ch(t){let e=t.match(n0);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&y0(r)?29:o0[n])}function ph(t,e){let r=e.match(a0);if(!r)return!1;let n=+r[1],o=+r[2],s=+r[3],a=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!t||a)}function w0(t){let e=t.split(b0);return e.length==2&&ch(e[0])&&ph(!0,e[1])}function A0(t){return v0.test(t)&&C0.test(t)}function T0(t){if(S0.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var n0,o0,a0,s0,i0,l0,d0,c0,p0,u0,f0,m0,g0,h0,x0,Td,b0,v0,C0,S0,Md=Gn(()=>{"use strict";n0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o0=[0,31,28,31,30,31,30,31,31,30,31,30,31],a0=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s0=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,i0=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,l0=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,d0=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,c0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,p0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,u0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f0=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,m0=t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},g0=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,h0=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,x0=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));Td={date:ch,time:ph.bind(void 0,!1),"date-time":w0,duration:x0,uri:A0,"uri-reference":Xn(i0),"uri-template":Xn(l0),url:Xn(d0),email:m0,hostname:Xn(s0),ipv4:Xn(g0),ipv6:Xn(h0),regex:T0,uuid:Xn(c0),"json-pointer":Xn(p0),"json-pointer-uri-fragment":Xn(u0),"relative-json-pointer":Xn(f0)};b0=/t|\s/i;v0=/\/|:/,C0=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;S0=/[^\\]\\Z/});var uh,fh=Gn(()=>{"use strict";(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(uh||(uh={}))});function mh(t){let e=0,r=t.length,n=0,o;for(;n<r;)e++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=t.charCodeAt(n),(o&64512)==56320&&n++);return e}var kd=Gn(()=>{"use strict"});function ur(t,e,r="2019-09",n=uo(e),o=!0,s=null,a="#",i="#",d=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let l=typeof t,p;switch(l){case"boolean":case"number":case"string":p=l;break;case"object":t===null?p="null":Array.isArray(t)?p="array":p="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:m,$recursiveRef:u,$recursiveAnchor:f,type:x,const:C,enum:S,required:k,not:T,anyOf:M,allOf:h,oneOf:w,if:y,then:E,else:B,format:P,properties:R,patternProperties:O,additionalProperties:V,unevaluatedProperties:ne,minProperties:be,maxProperties:Ye,propertyNames:Ge,dependentRequired:ve,dependentSchemas:Ee,dependencies:Ke,prefixItems:Ne,items:X,additionalItems:Ue,unevaluatedItems:K,contains:Te,minContains:oe,maxContains:xe,minItems:Me,maxItems:Xe,uniqueItems:ce,minimum:te,maximum:le,exclusiveMinimum:ut,exclusiveMaximum:Ce,multipleOf:he,minLength:rt,maxLength:_e,pattern:me,__absolute_ref__:J,__absolute_recursive_ref__:ze}=e,Z=[];if(f===!0&&s===null&&(s=e),u==="#"){let z=s===null?n[ze]:s,Re=`${i}/$recursiveRef`,Ae=ur(t,s===null?e:s,r,n,o,z,a,Re,d);Ae.valid||Z.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:Re,error:"A subschema had errors."},...Ae.errors)}if(m!==void 0){let Re=n[J||m];if(Re===void 0){let pe=`Unresolved $ref "${m}".`;throw J&&J!==m&&(pe+=` Absolute URI "${J}".`),pe+=`
1
+ "use strict";var AgentWidget=(()=>{var Mb=Object.create;var Is=Object.defineProperty;var kb=Object.getOwnPropertyDescriptor;var Eb=Object.getOwnPropertyNames;var Lb=Object.getPrototypeOf,Pb=Object.prototype.hasOwnProperty;var Zg=t=>{throw TypeError(t)};var Ib=(t,e,r)=>e in t?Is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var oo=(t,e)=>()=>(t&&(e=t(t=0)),e);var eh=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),th=(t,e)=>{for(var r in e)Is(t,r,{get:e[r],enumerable:!0})},rh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Eb(e))!Pb.call(t,o)&&o!==r&&Is(t,o,{get:()=>e[o],enumerable:!(n=kb(e,o))||n.enumerable});return t};var bd=(t,e,r)=>(r=t!=null?Mb(Lb(t)):{},rh(e||!t||!t.__esModule?Is(r,"default",{value:t,enumerable:!0}):r,t)),Rb=t=>rh(Is({},"__esModule",{value:!0}),t);var $t=(t,e,r)=>Ib(t,typeof e!="symbol"?e+"":e,r),Wb=(t,e,r)=>e.has(t)||Zg("Cannot "+r);var nh=(t,e,r)=>e.has(t)?Zg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Ri=(t,e,r)=>(Wb(t,e,"access private method"),r);function za(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(!za(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(!za(t[a],e[a]))return!1;return!0}return t===e}var Nd=oo(()=>{"use strict"});function Sn(t){return encodeURI(_0(t))}function _0(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var $i=oo(()=>{"use strict"});function vo(t,e=Object.create(null),r=q0,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:vo(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(U0[s])continue;let a=`${n}/${Sn(s)}`,i=t[s];if(Array.isArray(i)){if(F0[s]){let d=i.length;for(let l=0;l<d;l++)vo(i[l],e,r,`${a}/${l}`)}}else if($0[s])for(let d in i)vo(i[d],e,r,`${a}/${Sn(d)}`);else vo(i,e,r,a)}return e}var F0,$0,U0,q0,Ui=oo(()=>{"use strict";$i();F0={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},$0={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},U0={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},q0=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 so(t){return t.test.bind(t)}function aw(t){return t%4===0&&(t%100!==0||t%400===0)}function Nh(t){let e=t.match(z0);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&aw(r)?29:V0[n])}function _h(t,e){let r=e.match(j0);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 iw(t){let e=t.split(sw);return e.length==2&&Nh(e[0])&&_h(!0,e[1])}function cw(t){return lw.test(t)&&dw.test(t)}function uw(t){if(pw.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var z0,V0,j0,G0,K0,X0,J0,Q0,Y0,Z0,ew,tw,rw,nw,ow,_d,sw,lw,dw,pw,Fd=oo(()=>{"use strict";z0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,V0=[0,31,28,31,30,31,30,31,31,30,31,30,31],j0=/^(\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,K0=/^(?:[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,J0=/^(?:(?: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,Q0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Y0=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Z0=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ew=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,tw=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))},rw=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,nw=/^((([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,ow=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));_d={date:Nh,time:_h.bind(void 0,!1),"date-time":iw,duration:ow,uri:cw,"uri-reference":so(K0),"uri-template":so(X0),url:so(J0),email:tw,hostname:so(G0),ipv4:so(rw),ipv6:so(nw),regex:uw,uuid:so(Q0),"json-pointer":so(Y0),"json-pointer-uri-fragment":so(Z0),"relative-json-pointer":so(ew)};sw=/t|\s/i;lw=/\/|:/,dw=/^(?:[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;pw=/[^\\]\\Z/});var Fh,$h=oo(()=>{"use strict";(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(Fh||(Fh={}))});function Uh(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 $d=oo(()=>{"use strict"});function br(t,e,r="2019-09",n=vo(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:k,not:E,anyOf:M,allOf:h,oneOf:C,if:v,then:T,else:W,format:P,properties:R,patternProperties:N,additionalProperties:j,unevaluatedProperties:ce,minProperties:be,maxProperties:Ze,propertyNames:Se,dependentRequired:Ne,dependentSchemas:Ce,dependencies:Fe,prefixItems:We,items:Z,additionalItems:ne,unevaluatedItems:ee,contains:we,minContains:Q,maxContains:X,minItems:fe,maxItems:Le,uniqueItems:me,minimum:te,maximum:le,exclusiveMinimum:ht,exclusiveMaximum:mt,multipleOf:Re,minLength:ye,maxLength:ot,pattern:He,__absolute_ref__:G,__absolute_recursive_ref__:he}=e,K=[];if(m===!0&&s===null&&(s=e),f==="#"){let U=s===null?n[he]:s,J=`${i}/$recursiveRef`,qe=br(t,s===null?e:s,r,n,o,U,a,J,d);qe.valid||K.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:J,error:"A subschema had errors."},...qe.errors)}if(u!==void 0){let J=n[G||u];if(J===void 0){let ie=`Unresolved $ref "${u}".`;throw G&&G!==u&&(ie+=` Absolute URI "${G}".`),ie+=`
2
2
  Known schemas:
3
3
  - ${Object.keys(n).join(`
4
- - `)}`,new Error(pe)}let Ae=`${i}/$ref`,fe=ur(t,Re,r,n,o,s,a,Ae,d);if(fe.valid||Z.push({instanceLocation:a,keyword:"$ref",keywordLocation:Ae,error:"A subschema had errors."},...fe.errors),r==="4"||r==="7")return{valid:Z.length===0,errors:Z}}if(Array.isArray(x)){let z=x.length,Re=!1;for(let Ae=0;Ae<z;Ae++)if(p===x[Ae]||x[Ae]==="integer"&&p==="number"&&t%1===0&&t===t){Re=!0;break}Re||Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x.join('", "')}".`})}else x==="integer"?(p!=="number"||t%1||t!==t)&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x}".`}):x!==void 0&&p!==x&&Z.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${x}".`});if(C!==void 0&&(p==="object"||p==="array"?La(t,C)||Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`}):t!==C&&Z.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(C)}.`})),S!==void 0&&(p==="object"||p==="array"?S.some(z=>La(t,z))||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(z=>t===z)||Z.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),T!==void 0){let z=`${i}/not`;ur(t,T,r,n,o,s,a,z).valid&&Z.push({instanceLocation:a,keyword:"not",keywordLocation:z,error:'Instance matched "not" schema.'})}let ge=[];if(M!==void 0){let z=`${i}/anyOf`,Re=Z.length,Ae=!1;for(let fe=0;fe<M.length;fe++){let pe=M[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${z}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae||Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:z,error:"Instance does not match any subschemas."})}if(h!==void 0){let z=`${i}/allOf`,Re=Z.length,Ae=!0;for(let fe=0;fe<h.length;fe++){let pe=h[fe],Be=Object.create(d),Q=ur(t,pe,r,n,o,f===!0?s:null,a,`${z}/${fe}`,Be);Z.push(...Q.errors),Ae=Ae&&Q.valid,Q.valid&&ge.push(Be)}Ae?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"allOf",keywordLocation:z,error:"Instance does not match every subschema."})}if(w!==void 0){let z=`${i}/oneOf`,Re=Z.length,Ae=w.filter((fe,pe)=>{let Be=Object.create(d),Q=ur(t,fe,r,n,o,f===!0?s:null,a,`${z}/${pe}`,Be);return Z.push(...Q.errors),Q.valid&&ge.push(Be),Q.valid}).length;Ae===1?Z.length=Re:Z.splice(Re,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:z,error:`Instance does not match exactly one subschema (${Ae} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...ge),y!==void 0){let z=`${i}/if`;if(ur(t,y,r,n,o,s,a,z,d).valid){if(E!==void 0){let Ae=ur(t,E,r,n,o,s,a,`${i}/then`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "then" schema.'},...Ae.errors)}}else if(B!==void 0){let Ae=ur(t,B,r,n,o,s,a,`${i}/else`,d);Ae.valid||Z.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "else" schema.'},...Ae.errors)}}if(p==="object"){if(k!==void 0)for(let fe of k)fe in t||Z.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${fe}".`});let z=Object.keys(t);if(be!==void 0&&z.length<be&&Z.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${be} properties.`}),Ye!==void 0&&z.length>Ye&&Z.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Ye} properties.`}),Ge!==void 0){let fe=`${i}/propertyNames`;for(let pe in t){let Be=`${a}/${xn(pe)}`,Q=ur(pe,Ge,r,n,o,s,Be,fe);Q.valid||Z.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:fe,error:`Property name "${pe}" does not match schema.`},...Q.errors)}}if(ve!==void 0){let fe=`${i}/dependantRequired`;for(let pe in ve)if(pe in t){let Be=ve[pe];for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`})}}if(Ee!==void 0)for(let fe in Ee){let pe=`${i}/dependentSchemas`;if(fe in t){let Be=ur(t,Ee[fe],r,n,o,s,a,`${pe}/${xn(fe)}`,d);Be.valid||Z.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:pe,error:`Instance has "${fe}" but does not match dependant schema.`},...Be.errors)}}if(Ke!==void 0){let fe=`${i}/dependencies`;for(let pe in Ke)if(pe in t){let Be=Ke[pe];if(Array.isArray(Be))for(let Q of Be)Q in t||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not have "${Q}".`});else{let Q=ur(t,Be,r,n,o,s,a,`${fe}/${xn(pe)}`);Q.valid||Z.push({instanceLocation:a,keyword:"dependencies",keywordLocation:fe,error:`Instance has "${pe}" but does not match dependant schema.`},...Q.errors)}}}let Re=Object.create(null),Ae=!1;if(R!==void 0){let fe=`${i}/properties`;for(let pe in R){if(!(pe in t))continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],R[pe],r,n,o,s,Be,`${fe}/${xn(pe)}`);if(Q.valid)d[pe]=Re[pe]=!0;else if(Ae=o,Z.push({instanceLocation:a,keyword:"properties",keywordLocation:fe,error:`Property "${pe}" does not match schema.`},...Q.errors),Ae)break}}if(!Ae&&O!==void 0){let fe=`${i}/patternProperties`;for(let pe in O){let Be=new RegExp(pe,"u"),Q=O[pe];for(let _ in t){if(!Be.test(_))continue;let ke=`${a}/${xn(_)}`,He=ur(t[_],Q,r,n,o,s,ke,`${fe}/${xn(pe)}`);He.valid?d[_]=Re[_]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:fe,error:`Property "${_}" matches pattern "${pe}" but does not match associated schema.`},...He.errors))}}}if(!Ae&&V!==void 0){let fe=`${i}/additionalProperties`;for(let pe in t){if(Re[pe])continue;let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],V,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:(Ae=o,Z.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:fe,error:`Property "${pe}" does not match additional properties schema.`},...Q.errors))}}else if(!Ae&&ne!==void 0){let fe=`${i}/unevaluatedProperties`;for(let pe in t)if(!d[pe]){let Be=`${a}/${xn(pe)}`,Q=ur(t[pe],ne,r,n,o,s,Be,fe);Q.valid?d[pe]=!0:Z.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:fe,error:`Property "${pe}" does not match unevaluated properties schema.`},...Q.errors)}}}else if(p==="array"){Xe!==void 0&&t.length>Xe&&Z.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${t.length} > ${Xe}).`}),Me!==void 0&&t.length<Me&&Z.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${t.length} < ${Me}).`});let z=t.length,Re=0,Ae=!1;if(Ne!==void 0){let fe=`${i}/prefixItems`,pe=Math.min(Ne.length,z);for(;Re<pe;Re++){let Be=ur(t[Re],Ne[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}if(X!==void 0){let fe=`${i}/items`;if(Array.isArray(X)){let pe=Math.min(X.length,z);for(;Re<pe;Re++){let Be=ur(t[Re],X[Re],r,n,o,s,`${a}/${Re}`,`${fe}/${Re}`);if(d[Re]=!0,!Be.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...Be.errors),Ae))break}}else for(;Re<z;Re++){let pe=ur(t[Re],X,r,n,o,s,`${a}/${Re}`,fe);if(d[Re]=!0,!pe.valid&&(Ae=o,Z.push({instanceLocation:a,keyword:"items",keywordLocation:fe,error:"Items did not match schema."},...pe.errors),Ae))break}if(!Ae&&Ue!==void 0){let pe=`${i}/additionalItems`;for(;Re<z;Re++){let Be=ur(t[Re],Ue,r,n,o,s,`${a}/${Re}`,pe);d[Re]=!0,Be.valid||(Ae=o,Z.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:pe,error:"Items did not match additional items schema."},...Be.errors))}}}if(Te!==void 0)if(z===0&&oe===void 0)Z.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(oe!==void 0&&z<oe)Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${z}) than minContains (${oe}).`});else{let fe=`${i}/contains`,pe=Z.length,Be=0;for(let Q=0;Q<z;Q++){let _=ur(t[Q],Te,r,n,o,s,`${a}/${Q}`,fe);_.valid?(d[Q]=!0,Be++):Z.push(..._.errors)}Be>=(oe||0)&&(Z.length=pe),oe===void 0&&xe===void 0&&Be===0?Z.splice(pe,0,{instanceLocation:a,keyword:"contains",keywordLocation:fe,error:"Array does not contain item matching schema."}):oe!==void 0&&Be<oe?Z.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${oe} items matching schema. Only ${Be} items were found.`}):xe!==void 0&&Be>xe&&Z.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${xe} items matching schema. ${Be} items were found.`})}if(!Ae&&K!==void 0){let fe=`${i}/unevaluatedItems`;for(Re;Re<z;Re++){if(d[Re])continue;let pe=ur(t[Re],K,r,n,o,s,`${a}/${Re}`,fe);d[Re]=!0,pe.valid||Z.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:fe,error:"Items did not match unevaluated items schema."},...pe.errors)}}if(ce)for(let fe=0;fe<z;fe++){let pe=t[fe],Be=typeof pe=="object"&&pe!==null;for(let Q=0;Q<z;Q++){if(fe===Q)continue;let _=t[Q];(pe===_||Be&&(typeof _=="object"&&_!==null)&&La(pe,_))&&(Z.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${fe} and ${Q}.`}),fe=Number.MAX_SAFE_INTEGER,Q=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(te!==void 0&&(ut===!0&&t<=te||t<te)&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${ut?"or equal to ":""} ${te}.`}),le!==void 0&&(Ce===!0&&t>=le||t>le)&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${Ce?"or equal to ":""} ${le}.`})):(te!==void 0&&t<te&&Z.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${te}.`}),le!==void 0&&t>le&&Z.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${le}.`}),ut!==void 0&&t<=ut&&Z.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${t} is less than ${ut}.`}),Ce!==void 0&&t>=Ce&&Z.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ce}.`})),he!==void 0){let z=t%he;Math.abs(0-z)>=11920929e-14&&Math.abs(he-z)>=11920929e-14&&Z.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${t} is not a multiple of ${he}.`})}}else if(p==="string"){let z=rt===void 0&&_e===void 0?0:mh(t);rt!==void 0&&z<rt&&Z.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${z} < ${rt}).`}),_e!==void 0&&z>_e&&Z.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${z} > ${_e}).`}),me!==void 0&&!new RegExp(me,"u").test(t)&&Z.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),P!==void 0&&Td[P]&&!Td[P](t)&&Z.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${P}".`})}return{valid:Z.length===0,errors:Z}}var Ed=Gn(()=>{"use strict";Sd();Bi();Md();Wi();kd()});var Hi,gh=Gn(()=>{"use strict";Bi();Ed();Hi=class{constructor(e,r="2019-09",n=!0){Ht(this,"schema");Ht(this,"draft");Ht(this,"shortCircuit");Ht(this,"lookup");this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=uo(e)}validate(e){return ur(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),uo(e,this.lookup)}}});var hh=Gn(()=>{"use strict";Sd();Bi();Md();Wi();fh();kd();Ed();gh()});var kh={};kg(kh,{cleanupWebMCPPolyfill:()=>Mh,initializeWebMCPPolyfill:()=>Th,initializeWebModelContextPolyfill:()=>Th,isPlainObject:()=>Hr,validateArgsWithSchema:()=>Ch});function Jn(t){try{return new DOMException(t,"UnknownError")}catch{let e=new Error(t);return e.name="UnknownError",e}}function P0(t){let e;try{e=JSON.parse(t)}catch{throw Jn(xh)}if(!e||typeof e!="object"||Array.isArray(e))throw Jn(xh);return e}function I0(t){if(typeof t=="string")return t;if(Hr(t)&&typeof t.name=="string")return t.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function Hr(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function wh(t){if(!Hr(t))return null;let e=t["~standard"];return Hr(e)?e:null}function R0(t){let e=wh(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function W0(t){let e=wh(t);return!e||e.version!==1||!Hr(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function Oi(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!Hr(e))return{issues:[{message:"expected object arguments"}]};let r=Ch(e,t);return r?{issues:[r]}:{value:e}}}}}function B0(t){for(let e of M0)try{let r=t["~standard"].jsonSchema.input({target:e});return vh(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function H0(t){if(t===void 0){let r=Di;return{inputSchema:r,standardValidator:Oi(r)}}if(W0(t)){let r=B0(t);return{inputSchema:r,standardValidator:Oi(r)}}if(R0(t))return{inputSchema:Di,standardValidator:t};if(vh(t),Object.keys(t).length===0)return{inputSchema:Di,standardValidator:Oi(Di)};let e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:Oi(e)}}function vh(t){if(!Hr(t))throw new Error("inputSchema must be a JSON Schema object");Pa(t,"$")}function Pa(t,e){let r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);let n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);let o=t.properties;if(o!==void 0){if(!Hr(o))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.properties.${i}: expected object schema`);Pa(d,`${e}.properties.${i}`)}}let s=t.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Hr(d))throw new Error(`Invalid JSON Schema at ${e}.items[${i}]: expected object schema`);Pa(d,`${e}.items[${i}]`)}else if(Hr(s))Pa(s,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(let i of["allOf","anyOf","oneOf"]){let d=t[i];if(d!==void 0){if(!Array.isArray(d))throw new Error(`Invalid JSON Schema at ${e}: "${i}" must be an array`);for(let[l,p]of d.entries()){if(!Hr(p))throw new Error(`Invalid JSON Schema at ${e}.${i}[${l}]: expected object schema`);Pa(p,`${e}.${i}[${l}]`)}}}let a=t.not;if(a!==void 0){if(!Hr(a))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);Pa(a,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function D0(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);let r=H0(t.inputSchema),n=t.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...o?{annotations:o}:{},inputSchema:r.inputSchema,[bh]:r.standardValidator}}function Ch(t,e){let r=new Hi(e,"2020-12",!0).validate(t);if(r.valid)return null;let n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function O0(t){if(!t||t.length===0)return null;let e=t.map(r=>Hr(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function N0(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(s){let a=s instanceof Error?`: ${s.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",s),`Input validation error: schema validation failed${a}`}if(!r.issues||r.issues.length===0)return null;let n=r.issues[0];if(!n)return"Input validation error";let o=O0(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function _0(t,e){return N0(t,e[bh])}function F0(t){return Hr(t)&&Array.isArray(t.content)}function $0(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Pd(t){return $0(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>Pd(e)):Hr(t)?Object.values(t).every(e=>Pd(e)):!1}function U0(t){if(!(!Hr(t)||!Pd(t)))return t}function q0(t){var e;if(typeof t=="string")return t;try{return(e=JSON.stringify(t))!=null?e:String(t)}catch{return String(t)}}function z0(t){if(F0(t))return t;let e=U0(t);return{content:[{type:"text",text:q0(t)}],...e?{structuredContent:e}:{},isError:!1}}function V0(t){var e;for(let r of(e=t.content)!=null?e:[])if(r.type==="text"&&"text"in r&&typeof r.text=="string")return r.text;return null}function j0(t){var r;if(t.isError)throw Jn(((r=V0(t))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||Ni);let e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw Jn(Ni)}}function G0(t,e){return e?e.aborted?Promise.reject(Jn(Ld)):new Promise((r,n)=>{let o=()=>{s(),n(Jn(Ld))},s=()=>{e.removeEventListener("abort",o)};e.addEventListener("abort",o,{once:!0}),t.then(a=>{s(),r(a)},a=>{s(),n(a)})}):t}function Ah(){return typeof navigator!="undefined"?navigator:null}function Sh(){return typeof document!="undefined"?document:null}function K0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function yh(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}function X0(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return _i||(_i=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document \u2014 use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),e}})}function Th(t){var d;let e=Ah(),r=Sh();if(!e&&!r||(r==null?void 0:r.modelContext))return;let o=e==null?void 0:e.modelContext,s=!!o;if(lr.installed&&Mh(),r&&o){lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),yh(r,o),lr.installedDocumentModelContext=!0,lr.installed=!0;return}if(s)return;let a=new E0,i=a;if(i[k0]=!0,r&&(lr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),yh(r,i),lr.installedDocumentModelContext=!0),e){lr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),lr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),_i=!1,X0(e,i),lr.installedNavigatorModelContext=!0;let l=(d=t==null?void 0:t.installTestingShim)!=null?d:"if-missing",p=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!p)&&(K0(e,"modelContextTesting",a.getTestingShim()),lr.installedNavigatorModelContextTesting=!0)}lr.installed=!0}function Mh(){if(!lr.installed)return;let t=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},e=Ah(),r=Sh();r&&lr.installedDocumentModelContext&&t(r,"modelContext",lr.previousDocumentModelContextDescriptor),e&&lr.installedNavigatorModelContext&&t(e,"modelContext",lr.previousNavigatorModelContextDescriptor),e&&lr.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",lr.previousNavigatorModelContextTestingDescriptor),lr.installed=!1,lr.previousDocumentModelContextDescriptor=void 0,lr.previousNavigatorModelContextDescriptor=void 0,lr.previousNavigatorModelContextTestingDescriptor=void 0,lr.installedDocumentModelContext=!1,lr.installedNavigatorModelContext=!1,lr.installedNavigatorModelContextTesting=!1,_i=!1}var xh,Ni,Ld,Di,M0,k0,bh,lr,E0,L0,_i,Eh=Gn(()=>{"use strict";hh();xh="Failed to parse input arguments",Ni="Tool was executed but the invocation failed. For example, the script function threw an error",Ld="Tool was cancelled",Di={type:"object",properties:{}},M0=["draft-2020-12","draft-07"],k0="__isWebMCPPolyfill",bh=Symbol("standardValidator"),lr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},E0=class extends EventTarget{constructor(){super(...arguments);Ht(this,"tools",new Map);Ht(this,"testingShim",null);Ht(this,"_ontoolchange",null);Ht(this,"unregisterToolDeprecationWarned",!1)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,r){var s;let n=r==null?void 0:r.signal;if(n!=null&&n.aborted){console.warn(`[WebMCPPolyfill] registerTool("${(s=e==null?void 0:e.name)!=null?s:"<unknown>"}") skipped: options.signal was already aborted.`);return}let o=D0(e,this.tools);this.tools.set(o.name,o),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(o.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let r=I0(e);this.tools.delete(r)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,r,n){return this.executeToolByName(e.name,r,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new L0(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{var n;let r;try{r=JSON.stringify((n=e.inputSchema)!=null?n:{type:"object"})}catch{r='{"type":"object"}'}return{name:e.name,description:e.description,inputSchema:r}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{var n,o,s;let r=this.tools.get(e.name);return{...e,title:(n=r==null?void 0:r.title)!=null?n:"",origin:(s=(o=globalThis.location)==null?void 0:o.origin)!=null?s:"",window:globalThis.window}})}async executeToolForTesting(e,r,n){return this.executeToolByName(e,r,n,!0)}async executeToolByName(e,r,n,o){var p;if((p=n==null?void 0:n.signal)!=null&&p.aborted)throw Jn(Ld);let s=this.tools.get(e);if(!s)throw Jn(`Tool not found: ${e}`);let a=P0(r),i=await _0(a,s);if(i)throw Jn(i);let d=!0,l={requestUserInteraction:async m=>{if(!d)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof m!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return m()}};try{let m=s.execute(a,l),u=await G0(Promise.resolve(m),n==null?void 0:n.signal);if(o)return j0(z0(u));let f=JSON.stringify(u);return f===void 0?null:f}catch(m){throw Jn(m instanceof Error?`${Ni}: ${m.message}`:Ni)}finally{d=!1}}notifyToolsChanged(){queueMicrotask(()=>{var r,n;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(o){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",o)}this.dispatchEvent(e),(n=this.testingShim)==null||n.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) \u2014 pass an AbortSignal and abort it to unregister."))}},L0=class extends EventTarget{constructor(e){super();Ht(this,"context");Ht(this,"_ontoolchange",null);this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,r,n){return this.context.executeToolForTesting(e,r,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",e)}dispatchToolChange(){var r;let e=new Event("toolchange");try{(r=this._ontoolchange)==null||r.call(this,e)}catch(n){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",n)}this.dispatchEvent(e),this.dispatchEvent(new Event("toolschanged"))}};_i=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let t=window.__webMCPPolyfillOptions;if((t==null?void 0:t.autoInitialize)!==!1)try{Th(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}});var Rd=Mg(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.Allow=et.ALL=et.COLLECTION=et.ATOM=et.SPECIAL=et.INF=et._INFINITY=et.INFINITY=et.NAN=et.BOOL=et.NULL=et.OBJ=et.ARR=et.NUM=et.STR=void 0;et.STR=1;et.NUM=2;et.ARR=4;et.OBJ=8;et.NULL=16;et.BOOL=32;et.NAN=64;et.INFINITY=128;et._INFINITY=256;et.INF=et.INFINITY|et._INFINITY;et.SPECIAL=et.NULL|et.BOOL|et.INF|et.NAN;et.ATOM=et.STR|et.NUM|et.SPECIAL;et.COLLECTION=et.ARR|et.OBJ;et.ALL=et.ATOM|et.COLLECTION;et.Allow={STR:et.STR,NUM:et.NUM,ARR:et.ARR,OBJ:et.OBJ,NULL:et.NULL,BOOL:et.BOOL,NAN:et.NAN,INFINITY:et.INFINITY,_INFINITY:et._INFINITY,INF:et.INF,SPECIAL:et.SPECIAL,ATOM:et.ATOM,COLLECTION:et.COLLECTION,ALL:et.ALL};et.default=et.Allow});var qi=Mg(Dr=>{"use strict";var ow=Dr&&Dr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),aw=Dr&&Dr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ow(e,t,r)};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.Allow=Dr.MalformedJSON=Dr.PartialJSON=Dr.parseJSON=Dr.parse=void 0;var Zr=Rd();Object.defineProperty(Dr,"Allow",{enumerable:!0,get:function(){return Zr.Allow}});aw(Rd(),Dr);var $i=class extends Error{};Dr.PartialJSON=$i;var Ui=class extends Error{};Dr.MalformedJSON=Ui;function Ih(t,e=Zr.Allow.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return sw(t.trim(),e)}Dr.parseJSON=Ih;var sw=(t,e)=>{let r=t.length,n=0,o=u=>{throw new $i(`${u} at position ${n}`)},s=u=>{throw new Ui(`${u} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?d():t[n]==="["?l():t.substring(n,n+4)==="null"||Zr.Allow.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||Zr.Allow.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||Zr.Allow.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||Zr.Allow.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||Zr.Allow._INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||Zr.Allow.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):p()),i=()=>{let u=n,f=!1;for(n++;n<r&&(t[n]!=='"'||f&&t[n-1]==="\\");)f=t[n]==="\\"?!f:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(u,++n-Number(f)))}catch(x){s(String(x))}else if(Zr.Allow.STR&e)try{return JSON.parse(t.substring(u,n-Number(f))+'"')}catch{return JSON.parse(t.substring(u,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,m();let u={};try{for(;t[n]!=="}";){if(m(),n>=r&&Zr.Allow.OBJ&e)return u;let f=i();m(),n++;try{let x=a();u[f]=x}catch(x){if(Zr.Allow.OBJ&e)return u;throw x}m(),t[n]===","&&n++}}catch{if(Zr.Allow.OBJ&e)return u;o("Expected '}' at end of object")}return n++,u},l=()=>{n++;let u=[];try{for(;t[n]!=="]";)u.push(a()),m(),t[n]===","&&n++}catch{if(Zr.Allow.ARR&e)return u;o("Expected ']' at end of array")}return n++,u},p=()=>{if(n===0){t==="-"&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(Zr.Allow.NUM&e)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(f))}}let u=n;for(t[n]==="-"&&n++;t[n]&&",]}".indexOf(t[n])===-1;)n++;n==r&&!(Zr.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(u,n))}catch{t.substring(u,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(t.substring(u,t.lastIndexOf("e")))}catch(x){s(String(x))}}},m=()=>{for(;n<r&&`
5
- \r `.includes(t[n]);)n++};return a()},iw=Ih;Dr.parse=iw});var oA={};kg(oA,{ASK_USER_QUESTION_TOOL_NAME:()=>Yp,AgentWidgetClient:()=>sa,AgentWidgetSession:()=>Ba,AttachmentManager:()=>ca,DEFAULT_COMPONENTS:()=>Rp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>hl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>yn,DEFAULT_PALETTE:()=>Pp,DEFAULT_SEMANTIC:()=>Ip,DEFAULT_WIDGET_CONFIG:()=>er,PRESETS:()=>Tu,PRESET_FULLSCREEN:()=>Su,PRESET_MINIMAL:()=>Au,PRESET_SHOP:()=>Cu,THEME_ZONES:()=>Zh,VERSION:()=>vy,WEBMCP_TOOL_PREFIX:()=>Ls,WebMcpBridge:()=>Ia,accessibilityPlugin:()=>Cy,animationsPlugin:()=>Ay,applyThemeVariables:()=>Ro,attachHeaderToContainer:()=>ua,brandPlugin:()=>Sy,buildComposer:()=>_a,buildDefaultHeader:()=>Up,buildHeader:()=>go,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>qp,collectEnrichedPageContext:()=>yy,componentRegistry:()=>yo,createActionManager:()=>ei,createAgentExperience:()=>ed,createAskUserQuestionBubble:()=>Wx,createBestAvailableVoiceProvider:()=>ol,createBubbleWithLayout:()=>yx,createCSATFeedback:()=>Ql,createComboButton:()=>Rl,createComponentMiddleware:()=>Qx,createComponentStreamParser:()=>Gl,createDefaultSanitizer:()=>Ad,createDirectivePostprocessor:()=>Xg,createDropdownMenu:()=>Do,createFlexibleJsonStreamParser:()=>Bh,createIconButton:()=>Er,createImagePart:()=>$h,createJsonStreamParser:()=>Ji,createLabelButton:()=>Gs,createLocalStorageAdapter:()=>jl,createMarkdownProcessor:()=>As,createMarkdownProcessorFromConfig:()=>na,createMessageActions:()=>Kp,createNPSFeedback:()=>Yl,createPlainTextParser:()=>Ki,createPlugin:()=>ky,createRegexJsonParser:()=>Xi,createStandardBubble:()=>Fa,createTextPart:()=>Rs,createTheme:()=>Da,createThemeObserver:()=>wl,createToggleGroup:()=>px,createTypingIndicator:()=>fa,createVoiceProvider:()=>da,createWidgetHostLayout:()=>ti,createXmlParser:()=>Qi,defaultActionHandlers:()=>ha,defaultJsonActionParser:()=>Zs,defaultParseRules:()=>wu,detectColorScheme:()=>Os,directivePostprocessor:()=>Jg,ensureAskUserQuestionSheet:()=>Va,escapeHtml:()=>oa,extractComponentDirectiveFromMessage:()=>Jl,fileToImagePart:()=>Uh,formatEnrichedContext:()=>by,generateAssistantMessageId:()=>ia,generateMessageId:()=>Dh,generateStableSelector:()=>vu,generateUserMessageId:()=>Wa,getActiveTheme:()=>Oa,getColorScheme:()=>Bp,getDisplayText:()=>Nh,getHeaderLayout:()=>zp,getImageParts:()=>Fh,getPreset:()=>Ly,hasComponentDirective:()=>Xl,hasImages:()=>_h,headerLayouts:()=>Wl,highContrastPlugin:()=>My,initAgentWidget:()=>iy,isAskUserQuestionMessage:()=>ho,isComponentDirectiveType:()=>Jx,isDockedMountMode:()=>Ar,isVoiceSupported:()=>Bs,isWebMcpToolName:()=>Io,listRegisteredStreamAnimations:()=>Np,markdownPostprocessor:()=>md,mergeWithDefaults:()=>xl,normalizeContent:()=>Oh,parseAskUserQuestionPayload:()=>xo,pluginRegistry:()=>Ys,reducedMotionPlugin:()=>Ty,registerStreamAnimationPlugin:()=>pa,removeAskUserQuestionSheet:()=>_o,renderComponentDirective:()=>Kl,renderLoadingIndicatorWithFallback:()=>Gp,renderLucideIcon:()=>Ie,resolveDockConfig:()=>kn,resolveSanitizer:()=>Ea,resolveTokens:()=>yl,stripWebMcpPrefix:()=>Id,themeToCssVariables:()=>bl,unregisterStreamAnimationPlugin:()=>Op,validateImageFile:()=>qh,validateTheme:()=>Wp});function ld(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ra=ld();function Hg(t){ra=t}var Dg=/[&<>"']/,Gy=new RegExp(Dg.source,"g"),Og=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Ky=new RegExp(Og.source,"g"),Xy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Pg=t=>Xy[t];function gn(t,e){if(e){if(Dg.test(t))return t.replace(Gy,Pg)}else if(Og.test(t))return t.replace(Ky,Pg);return t}var Jy=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Qy(t){return t.replace(Jy,(e,r)=>(r=r.toLowerCase(),r==="colon"?":":r.charAt(0)==="#"?r.charAt(1)==="x"?String.fromCharCode(parseInt(r.substring(2),16)):String.fromCharCode(+r.substring(1)):""))}var Yy=/(^|[^\[])\^/g;function or(t,e){let r=typeof t=="string"?t:t.source;e=e||"";let n={replace:(o,s)=>{let a=typeof s=="string"?s:s.source;return a=a.replace(Yy,"$1"),r=r.replace(o,a),n},getRegex:()=>new RegExp(r,e)};return n}function Ig(t){try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}var ys={exec:()=>null};function Rg(t,e){let r=t.replace(/\|/g,(s,a,i)=>{let d=!1,l=a;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=r.split(/ \|/),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function Ti(t,e,r){let n=t.length;if(n===0)return"";let o=0;for(;o<n;){let s=t.charAt(n-o-1);if(s===e&&!r)o++;else if(s!==e&&r)o++;else break}return t.slice(0,n-o)}function Zy(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let n=0;n<t.length;n++)if(t[n]==="\\")n++;else if(t[n]===e[0])r++;else if(t[n]===e[1]&&(r--,r<0))return n;return-1}function Wg(t,e,r,n){let o=e.href,s=e.title?gn(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");if(t[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:r,href:o,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,i}return{type:"image",raw:r,href:o,title:s,text:gn(a)}}function eb(t,e){let r=t.match(/^(\s+)(?:```)/);if(r===null)return e;let n=r[1];return e.split(`
4
+ - `)}`,new Error(ie)}let qe=`${i}/$ref`,se=br(t,J,r,n,o,s,a,qe,d);if(se.valid||K.push({instanceLocation:a,keyword:"$ref",keywordLocation:qe,error:"A subschema had errors."},...se.errors),r==="4"||r==="7")return{valid:K.length===0,errors:K}}if(Array.isArray(y)){let U=y.length,J=!1;for(let qe=0;qe<U;qe++)if(p===y[qe]||y[qe]==="integer"&&p==="number"&&t%1===0&&t===t){J=!0;break}J||K.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)&&K.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`}):y!==void 0&&p!==y&&K.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${p}" is invalid. Expected "${y}".`});if(x!==void 0&&(p==="object"||p==="array"?za(t,x)||K.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(x)}.`}):t!==x&&K.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(U=>za(t,U))||K.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(U=>t===U)||K.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),E!==void 0){let U=`${i}/not`;br(t,E,r,n,o,s,a,U).valid&&K.push({instanceLocation:a,keyword:"not",keywordLocation:U,error:'Instance matched "not" schema.'})}let wt=[];if(M!==void 0){let U=`${i}/anyOf`,J=K.length,qe=!1;for(let se=0;se<M.length;se++){let ie=M[se],Be=Object.create(d),Xe=br(t,ie,r,n,o,m===!0?s:null,a,`${U}/${se}`,Be);K.push(...Xe.errors),qe=qe||Xe.valid,Xe.valid&&wt.push(Be)}qe?K.length=J:K.splice(J,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:U,error:"Instance does not match any subschemas."})}if(h!==void 0){let U=`${i}/allOf`,J=K.length,qe=!0;for(let se=0;se<h.length;se++){let ie=h[se],Be=Object.create(d),Xe=br(t,ie,r,n,o,m===!0?s:null,a,`${U}/${se}`,Be);K.push(...Xe.errors),qe=qe&&Xe.valid,Xe.valid&&wt.push(Be)}qe?K.length=J:K.splice(J,0,{instanceLocation:a,keyword:"allOf",keywordLocation:U,error:"Instance does not match every subschema."})}if(C!==void 0){let U=`${i}/oneOf`,J=K.length,qe=C.filter((se,ie)=>{let Be=Object.create(d),Xe=br(t,se,r,n,o,m===!0?s:null,a,`${U}/${ie}`,Be);return K.push(...Xe.errors),Xe.valid&&wt.push(Be),Xe.valid}).length;qe===1?K.length=J:K.splice(J,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:U,error:`Instance does not match exactly one subschema (${qe} matches).`})}if((p==="object"||p==="array")&&Object.assign(d,...wt),v!==void 0){let U=`${i}/if`;if(br(t,v,r,n,o,s,a,U,d).valid){if(T!==void 0){let qe=br(t,T,r,n,o,s,a,`${i}/then`,d);qe.valid||K.push({instanceLocation:a,keyword:"if",keywordLocation:U,error:'Instance does not match "then" schema.'},...qe.errors)}}else if(W!==void 0){let qe=br(t,W,r,n,o,s,a,`${i}/else`,d);qe.valid||K.push({instanceLocation:a,keyword:"if",keywordLocation:U,error:'Instance does not match "else" schema.'},...qe.errors)}}if(p==="object"){if(k!==void 0)for(let se of k)se in t||K.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${se}".`});let U=Object.keys(t);if(be!==void 0&&U.length<be&&K.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${be} properties.`}),Ze!==void 0&&U.length>Ze&&K.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${Ze} properties.`}),Se!==void 0){let se=`${i}/propertyNames`;for(let ie in t){let Be=`${a}/${Sn(ie)}`,Xe=br(ie,Se,r,n,o,s,Be,se);Xe.valid||K.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:se,error:`Property name "${ie}" does not match schema.`},...Xe.errors)}}if(Ne!==void 0){let se=`${i}/dependantRequired`;for(let ie in Ne)if(ie in t){let Be=Ne[ie];for(let Xe of Be)Xe in t||K.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:se,error:`Instance has "${ie}" but does not have "${Xe}".`})}}if(Ce!==void 0)for(let se in Ce){let ie=`${i}/dependentSchemas`;if(se in t){let Be=br(t,Ce[se],r,n,o,s,a,`${ie}/${Sn(se)}`,d);Be.valid||K.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:ie,error:`Instance has "${se}" but does not match dependant schema.`},...Be.errors)}}if(Fe!==void 0){let se=`${i}/dependencies`;for(let ie in Fe)if(ie in t){let Be=Fe[ie];if(Array.isArray(Be))for(let Xe of Be)Xe in t||K.push({instanceLocation:a,keyword:"dependencies",keywordLocation:se,error:`Instance has "${ie}" but does not have "${Xe}".`});else{let Xe=br(t,Be,r,n,o,s,a,`${se}/${Sn(ie)}`);Xe.valid||K.push({instanceLocation:a,keyword:"dependencies",keywordLocation:se,error:`Instance has "${ie}" but does not match dependant schema.`},...Xe.errors)}}}let J=Object.create(null),qe=!1;if(R!==void 0){let se=`${i}/properties`;for(let ie in R){if(!(ie in t))continue;let Be=`${a}/${Sn(ie)}`,Xe=br(t[ie],R[ie],r,n,o,s,Be,`${se}/${Sn(ie)}`);if(Xe.valid)d[ie]=J[ie]=!0;else if(qe=o,K.push({instanceLocation:a,keyword:"properties",keywordLocation:se,error:`Property "${ie}" does not match schema.`},...Xe.errors),qe)break}}if(!qe&&N!==void 0){let se=`${i}/patternProperties`;for(let ie in N){let Be=new RegExp(ie,"u"),Xe=N[ie];for(let B in t){if(!Be.test(B))continue;let xe=`${a}/${Sn(B)}`,De=br(t[B],Xe,r,n,o,s,xe,`${se}/${Sn(ie)}`);De.valid?d[B]=J[B]=!0:(qe=o,K.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:se,error:`Property "${B}" matches pattern "${ie}" but does not match associated schema.`},...De.errors))}}}if(!qe&&j!==void 0){let se=`${i}/additionalProperties`;for(let ie in t){if(J[ie])continue;let Be=`${a}/${Sn(ie)}`,Xe=br(t[ie],j,r,n,o,s,Be,se);Xe.valid?d[ie]=!0:(qe=o,K.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:se,error:`Property "${ie}" does not match additional properties schema.`},...Xe.errors))}}else if(!qe&&ce!==void 0){let se=`${i}/unevaluatedProperties`;for(let ie in t)if(!d[ie]){let Be=`${a}/${Sn(ie)}`,Xe=br(t[ie],ce,r,n,o,s,Be,se);Xe.valid?d[ie]=!0:K.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:se,error:`Property "${ie}" does not match unevaluated properties schema.`},...Xe.errors)}}}else if(p==="array"){Le!==void 0&&t.length>Le&&K.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${t.length} > ${Le}).`}),fe!==void 0&&t.length<fe&&K.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${t.length} < ${fe}).`});let U=t.length,J=0,qe=!1;if(We!==void 0){let se=`${i}/prefixItems`,ie=Math.min(We.length,U);for(;J<ie;J++){let Be=br(t[J],We[J],r,n,o,s,`${a}/${J}`,`${se}/${J}`);if(d[J]=!0,!Be.valid&&(qe=o,K.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:se,error:"Items did not match schema."},...Be.errors),qe))break}}if(Z!==void 0){let se=`${i}/items`;if(Array.isArray(Z)){let ie=Math.min(Z.length,U);for(;J<ie;J++){let Be=br(t[J],Z[J],r,n,o,s,`${a}/${J}`,`${se}/${J}`);if(d[J]=!0,!Be.valid&&(qe=o,K.push({instanceLocation:a,keyword:"items",keywordLocation:se,error:"Items did not match schema."},...Be.errors),qe))break}}else for(;J<U;J++){let ie=br(t[J],Z,r,n,o,s,`${a}/${J}`,se);if(d[J]=!0,!ie.valid&&(qe=o,K.push({instanceLocation:a,keyword:"items",keywordLocation:se,error:"Items did not match schema."},...ie.errors),qe))break}if(!qe&&ne!==void 0){let ie=`${i}/additionalItems`;for(;J<U;J++){let Be=br(t[J],ne,r,n,o,s,`${a}/${J}`,ie);d[J]=!0,Be.valid||(qe=o,K.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:ie,error:"Items did not match additional items schema."},...Be.errors))}}}if(we!==void 0)if(U===0&&Q===void 0)K.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Q!==void 0&&U<Q)K.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${U}) than minContains (${Q}).`});else{let se=`${i}/contains`,ie=K.length,Be=0;for(let Xe=0;Xe<U;Xe++){let B=br(t[Xe],we,r,n,o,s,`${a}/${Xe}`,se);B.valid?(d[Xe]=!0,Be++):K.push(...B.errors)}Be>=(Q||0)&&(K.length=ie),Q===void 0&&X===void 0&&Be===0?K.splice(ie,0,{instanceLocation:a,keyword:"contains",keywordLocation:se,error:"Array does not contain item matching schema."}):Q!==void 0&&Be<Q?K.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${Q} items matching schema. Only ${Be} items were found.`}):X!==void 0&&Be>X&&K.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${X} items matching schema. ${Be} items were found.`})}if(!qe&&ee!==void 0){let se=`${i}/unevaluatedItems`;for(J;J<U;J++){if(d[J])continue;let ie=br(t[J],ee,r,n,o,s,`${a}/${J}`,se);d[J]=!0,ie.valid||K.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:se,error:"Items did not match unevaluated items schema."},...ie.errors)}}if(me)for(let se=0;se<U;se++){let ie=t[se],Be=typeof ie=="object"&&ie!==null;for(let Xe=0;Xe<U;Xe++){if(se===Xe)continue;let B=t[Xe];(ie===B||Be&&(typeof B=="object"&&B!==null)&&za(ie,B))&&(K.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${se} and ${Xe}.`}),se=Number.MAX_SAFE_INTEGER,Xe=Number.MAX_SAFE_INTEGER)}}}else if(p==="number"){if(r==="4"?(te!==void 0&&(ht===!0&&t<=te||t<te)&&K.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${ht?"or equal to ":""} ${te}.`}),le!==void 0&&(mt===!0&&t>=le||t>le)&&K.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${mt?"or equal to ":""} ${le}.`})):(te!==void 0&&t<te&&K.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${t} is less than ${te}.`}),le!==void 0&&t>le&&K.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${t} is greater than ${le}.`}),ht!==void 0&&t<=ht&&K.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${t} is less than ${ht}.`}),mt!==void 0&&t>=mt&&K.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${t} is greater than or equal to ${mt}.`})),Re!==void 0){let U=t%Re;Math.abs(0-U)>=11920929e-14&&Math.abs(Re-U)>=11920929e-14&&K.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${t} is not a multiple of ${Re}.`})}}else if(p==="string"){let U=ye===void 0&&ot===void 0?0:Uh(t);ye!==void 0&&U<ye&&K.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${U} < ${ye}).`}),ot!==void 0&&U>ot&&K.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${U} > ${ot}).`}),He!==void 0&&!new RegExp(He,"u").test(t)&&K.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),P!==void 0&&_d[P]&&!_d[P](t)&&K.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${P}".`})}return{valid:K.length===0,errors:K}}var Ud=oo(()=>{"use strict";Nd();Ui();Fd();$i();$d()});var qi,qh=oo(()=>{"use strict";Ui();Ud();qi=class{constructor(e,r="2019-09",n=!0){$t(this,"schema");$t(this,"draft");$t(this,"shortCircuit");$t(this,"lookup");this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=vo(e)}validate(e){return br(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),vo(e,this.lookup)}}});var zh=oo(()=>{"use strict";Nd();Ui();Fd();$i();$h();$d();Ud();qh()});var tx={};th(tx,{cleanupWebMCPPolyfill:()=>ex,initializeWebMCPPolyfill:()=>Zh,initializeWebModelContextPolyfill:()=>Zh,isPlainObject:()=>Ur,validateArgsWithSchema:()=>Jh});function io(t){try{return new DOMException(t,"UnknownError")}catch{let e=new Error(t);return e.name="UnknownError",e}}function xw(t){let e;try{e=JSON.parse(t)}catch{throw io(Vh)}if(!e||typeof e!="object"||Array.isArray(e))throw io(Vh);return e}function yw(t){if(typeof t=="string")return t;if(Ur(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 Ur(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Kh(t){if(!Ur(t))return null;let e=t["~standard"];return Ur(e)?e:null}function bw(t){let e=Kh(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function ww(t){let e=Kh(t);return!e||e.version!==1||!Ur(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function Vi(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!Ur(e))return{issues:[{message:"expected object arguments"}]};let r=Jh(e,t);return r?{issues:[r]}:{value:e}}}}}function vw(t){for(let e of fw)try{let r=t["~standard"].jsonSchema.input({target:e});return Xh(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 Cw(t){if(t===void 0){let r=zi;return{inputSchema:r,standardValidator:Vi(r)}}if(ww(t)){let r=vw(t);return{inputSchema:r,standardValidator:Vi(r)}}if(bw(t))return{inputSchema:zi,standardValidator:t};if(Xh(t),Object.keys(t).length===0)return{inputSchema:zi,standardValidator:Vi(zi)};let e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:Vi(e)}}function Xh(t){if(!Ur(t))throw new Error("inputSchema must be a JSON Schema object");Va(t,"$")}function Va(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(!Ur(o))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(let[i,d]of Object.entries(o)){if(!Ur(d))throw new Error(`Invalid JSON Schema at ${e}.properties.${i}: expected object schema`);Va(d,`${e}.properties.${i}`)}}let s=t.items;if(s!==void 0)if(Array.isArray(s))for(let[i,d]of s.entries()){if(!Ur(d))throw new Error(`Invalid JSON Schema at ${e}.items[${i}]: expected object schema`);Va(d,`${e}.items[${i}]`)}else if(Ur(s))Va(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(!Ur(p))throw new Error(`Invalid JSON Schema at ${e}.${i}[${l}]: expected object schema`);Va(p,`${e}.${i}[${l}]`)}}}let a=t.not;if(a!==void 0){if(!Ur(a))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);Va(a,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function Aw(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=Cw(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,[Gh]:r.standardValidator}}function Jh(t,e){let r=new qi(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 Sw(t){if(!t||t.length===0)return null;let e=t.map(r=>Ur(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 Tw(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=Sw(n==null?void 0:n.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function Mw(t,e){return Tw(t,e[Gh])}function kw(t){return Ur(t)&&Array.isArray(t.content)}function Ew(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function zd(t){return Ew(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>zd(e)):Ur(t)?Object.values(t).every(e=>zd(e)):!1}function Lw(t){if(!(!Ur(t)||!zd(t)))return t}function Pw(t){var e;if(typeof t=="string")return t;try{return(e=JSON.stringify(t))!=null?e:String(t)}catch{return String(t)}}function Iw(t){if(kw(t))return t;let e=Lw(t);return{content:[{type:"text",text:Pw(t)}],...e?{structuredContent:e}:{},isError:!1}}function Rw(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 Ww(t){var r;if(t.isError)throw io(((r=Rw(t))==null?void 0:r.replace(/^Error:\s*/i,"").trim())||ji);let e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw io(ji)}}function Hw(t,e){return e?e.aborted?Promise.reject(io(qd)):new Promise((r,n)=>{let o=()=>{s(),n(io(qd))},s=()=>{e.removeEventListener("abort",o)};e.addEventListener("abort",o,{once:!0}),t.then(a=>{s(),r(a)},a=>{s(),n(a)})}):t}function Qh(){return typeof navigator!="undefined"?navigator:null}function Yh(){return typeof document!="undefined"?document:null}function Bw(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function jh(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}function Dw(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return Gi||(Gi=!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 Zh(t){var d;let e=Qh(),r=Yh();if(!e&&!r||(r==null?void 0:r.modelContext))return;let o=e==null?void 0:e.modelContext,s=!!o;if(gr.installed&&ex(),r&&o){gr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),jh(r,o),gr.installedDocumentModelContext=!0,gr.installed=!0;return}if(s)return;let a=new gw,i=a;if(i[mw]=!0,r&&(gr.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),jh(r,i),gr.installedDocumentModelContext=!0),e){gr.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),gr.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),Gi=!1,Dw(e,i),gr.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)&&(Bw(e,"modelContextTesting",a.getTestingShim()),gr.installedNavigatorModelContextTesting=!0)}gr.installed=!0}function ex(){if(!gr.installed)return;let t=(n,o,s)=>{if(s){Object.defineProperty(n,o,s);return}delete n[o]},e=Qh(),r=Yh();r&&gr.installedDocumentModelContext&&t(r,"modelContext",gr.previousDocumentModelContextDescriptor),e&&gr.installedNavigatorModelContext&&t(e,"modelContext",gr.previousNavigatorModelContextDescriptor),e&&gr.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",gr.previousNavigatorModelContextTestingDescriptor),gr.installed=!1,gr.previousDocumentModelContextDescriptor=void 0,gr.previousNavigatorModelContextDescriptor=void 0,gr.previousNavigatorModelContextTestingDescriptor=void 0,gr.installedDocumentModelContext=!1,gr.installedNavigatorModelContext=!1,gr.installedNavigatorModelContextTesting=!1,Gi=!1}var Vh,ji,qd,zi,fw,mw,Gh,gr,gw,hw,Gi,rx=oo(()=>{"use strict";zh();Vh="Failed to parse input arguments",ji="Tool was executed but the invocation failed. For example, the script function threw an error",qd="Tool was cancelled",zi={type:"object",properties:{}},fw=["draft-2020-12","draft-07"],mw="__isWebMCPPolyfill",Gh=Symbol("standardValidator"),gr={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1},gw=class extends EventTarget{constructor(){super(...arguments);$t(this,"tools",new Map);$t(this,"testingShim",null);$t(this,"_ontoolchange",null);$t(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=Aw(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=yw(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 hw(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 io(qd);let s=this.tools.get(e);if(!s)throw io(`Tool not found: ${e}`);let a=xw(r),i=await Mw(a,s);if(i)throw io(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 Hw(Promise.resolve(u),n==null?void 0:n.signal);if(o)return Ww(Iw(f));let m=JSON.stringify(f);return m===void 0?null:m}catch(u){throw io(u instanceof Error?`${ji}: ${u.message}`:ji)}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."))}},hw=class extends EventTarget{constructor(e){super();$t(this,"context");$t(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"))}};Gi=!1;if(typeof window!="undefined"&&typeof document!="undefined"){let t=window.__webMCPPolyfillOptions;if((t==null?void 0:t.autoInitialize)!==!1)try{Zh(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}});var Gd=eh(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.Allow=Je.ALL=Je.COLLECTION=Je.ATOM=Je.SPECIAL=Je.INF=Je._INFINITY=Je.INFINITY=Je.NAN=Je.BOOL=Je.NULL=Je.OBJ=Je.ARR=Je.NUM=Je.STR=void 0;Je.STR=1;Je.NUM=2;Je.ARR=4;Je.OBJ=8;Je.NULL=16;Je.BOOL=32;Je.NAN=64;Je.INFINITY=128;Je._INFINITY=256;Je.INF=Je.INFINITY|Je._INFINITY;Je.SPECIAL=Je.NULL|Je.BOOL|Je.INF|Je.NAN;Je.ATOM=Je.STR|Je.NUM|Je.SPECIAL;Je.COLLECTION=Je.ARR|Je.OBJ;Je.ALL=Je.ATOM|Je.COLLECTION;Je.Allow={STR:Je.STR,NUM:Je.NUM,ARR:Je.ARR,OBJ:Je.OBJ,NULL:Je.NULL,BOOL:Je.BOOL,NAN:Je.NAN,INFINITY:Je.INFINITY,_INFINITY:Je._INFINITY,INF:Je.INF,SPECIAL:Je.SPECIAL,ATOM:Je.ATOM,COLLECTION:Je.COLLECTION,ALL:Je.ALL};Je.default=Je.Allow});var Yi=eh(qr=>{"use strict";var Vw=qr&&qr.__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]})),jw=qr&&qr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Vw(e,t,r)};Object.defineProperty(qr,"__esModule",{value:!0});qr.Allow=qr.MalformedJSON=qr.PartialJSON=qr.parseJSON=qr.parse=void 0;var an=Gd();Object.defineProperty(qr,"Allow",{enumerable:!0,get:function(){return an.Allow}});jw(Gd(),qr);var Ji=class extends Error{};qr.PartialJSON=Ji;var Qi=class extends Error{};qr.MalformedJSON=Qi;function sx(t,e=an.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)}qr.parseJSON=sx;var Gw=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Ji(`${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"||an.Allow.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||an.Allow.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||an.Allow.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||an.Allow.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||an.Allow._INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||an.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(an.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&&an.Allow.OBJ&e)return f;let m=i();u(),n++;try{let y=a();f[m]=y}catch(y){if(an.Allow.OBJ&e)return f;throw y}u(),t[n]===","&&n++}}catch{if(an.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(an.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(an.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&&!(an.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()},Kw=sx;qr.parse=Kw});var jA={};th(jA,{ASK_USER_QUESTION_TOOL_NAME:()=>fu,AgentWidgetClient:()=>xa,AgentWidgetSession:()=>Xa,AttachmentManager:()=>va,DEFAULT_COMPONENTS:()=>Gp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Tl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Tn,DEFAULT_PALETTE:()=>Vp,DEFAULT_SEMANTIC:()=>jp,DEFAULT_WIDGET_CONFIG:()=>er,PRESETS:()=>_u,PRESET_FULLSCREEN:()=>Nu,PRESET_MINIMAL:()=>Ou,PRESET_SHOP:()=>Du,THEME_ZONES:()=>Ex,VERSION:()=>nb,WEBMCP_TOOL_PREFIX:()=>Co,WebMcpBridge:()=>ja,accessibilityPlugin:()=>ob,animationsPlugin:()=>ab,applyThemeVariables:()=>zo,attachHeaderToContainer:()=>Sa,brandPlugin:()=>sb,buildComposer:()=>es,buildDefaultHeader:()=>nu,buildHeader:()=>Mo,buildHeaderWithLayout:()=>Za,buildMinimalHeader:()=>ou,collectEnrichedPageContext:()=>eb,componentRegistry:()=>Lo,createActionManager:()=>ui,createAgentExperience:()=>pd,createAskUserQuestionBubble:()=>py,createBestAvailableVoiceProvider:()=>fl,createBubbleWithLayout:()=>Jx,createCSATFeedback:()=>ld,createComboButton:()=>$l,createComponentMiddleware:()=>Wy,createComponentStreamParser:()=>od,createDefaultSanitizer:()=>Od,createDirectivePostprocessor:()=>Ah,createDropdownMenu:()=>Ko,createFlexibleJsonStreamParser:()=>dx,createIconButton:()=>Fr,createImagePart:()=>hx,createJsonStreamParser:()=>al,createLabelButton:()=>ai,createLocalStorageAdapter:()=>nd,createMarkdownProcessor:()=>Ns,createMarkdownProcessorFromConfig:()=>ma,createMessageActions:()=>du,createNPSFeedback:()=>dd,createPlainTextParser:()=>nl,createPlugin:()=>db,createRegexJsonParser:()=>ol,createStandardBubble:()=>ts,createTextPart:()=>js,createTheme:()=>Qa,createThemeObserver:()=>Ll,createToggleGroup:()=>qx,createTypingIndicator:()=>Ta,createVoiceProvider:()=>wa,createWidgetHostLayout:()=>fi,createXmlParser:()=>sl,defaultActionHandlers:()=>Ea,defaultJsonActionParser:()=>pi,defaultParseRules:()=>Hu,detectColorScheme:()=>Qs,directivePostprocessor:()=>Sh,ensureAskUserQuestionSheet:()=>ss,escapeHtml:()=>ga,extractComponentDirectiveFromMessage:()=>id,fileToImagePart:()=>xx,formatEnrichedContext:()=>tb,generateAssistantMessageId:()=>ya,generateMessageId:()=>px,generateStableSelector:()=>Bu,generateUserMessageId:()=>Ka,getActiveTheme:()=>Ya,getColorScheme:()=>Xp,getDisplayText:()=>fx,getHeaderLayout:()=>au,getImageParts:()=>gx,getPreset:()=>pb,hasComponentDirective:()=>sd,hasImages:()=>mx,headerLayouts:()=>Ul,highContrastPlugin:()=>lb,initAgentWidget:()=>qy,isAskUserQuestionMessage:()=>ko,isComponentDirectiveType:()=>Ry,isDockedMountMode:()=>Br,isVoiceSupported:()=>Ks,isWebMcpToolName:()=>qo,listRegisteredStreamAnimations:()=>Zp,markdownPostprocessor:()=>Ed,mergeWithDefaults:()=>Ml,normalizeContent:()=>ux,parseAskUserQuestionPayload:()=>Eo,pluginRegistry:()=>ci,reducedMotionPlugin:()=>ib,registerStreamAnimationPlugin:()=>Aa,removeAskUserQuestionSheet:()=>Qo,renderComponentDirective:()=>ad,renderLoadingIndicatorWithFallback:()=>lu,renderLucideIcon:()=>Ie,resolveDockConfig:()=>Nn,resolveSanitizer:()=>qa,resolveTokens:()=>kl,stripWebMcpPrefix:()=>Xi,themeToCssVariables:()=>El,unregisterStreamAnimationPlugin:()=>Yp,validateImageFile:()=>yx,validateTheme:()=>Kp});function Cd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var fa=Cd();function dh(t){fa=t}var ch=/[&<>"']/,Hb=new RegExp(ch.source,"g"),ph=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Bb=new RegExp(ph.source,"g"),Db={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},oh=t=>Db[t];function Cn(t,e){if(e){if(ch.test(t))return t.replace(Hb,oh)}else if(ph.test(t))return t.replace(Bb,oh);return t}var Ob=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Nb(t){return t.replace(Ob,(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 _b=/(^|[^\[])\^/g;function dr(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(_b,"$1"),r=r.replace(o,a),n},getRegex:()=>new RegExp(r,e)};return n}function ah(t){try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}var Ws={exec:()=>null};function sh(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 Wi(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 Fb(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 ih(t,e,r,n){let o=e.href,s=e.title?Cn(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:Cn(a)}}function $b(t,e){let r=t.match(/^(\s+)(?:```)/);if(r===null)return e;let n=r[1];return e.split(`
6
6
  `).map(o=>{let s=o.match(/^\s+/);if(s===null)return o;let[a]=s;return a.length>=n.length?o.slice(n.length):o}).join(`
7
- `)}var Ma=class{constructor(e){Ht(this,"options");Ht(this,"rules");Ht(this,"lexer");this.options=e||ra}space(e){let r=this.rules.block.newline.exec(e);if(r&&r[0].length>0)return{type:"space",raw:r[0]}}code(e){let r=this.rules.block.code.exec(e);if(r){let n=r[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:r[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Ti(n,`
8
- `)}}}fences(e){let r=this.rules.block.fences.exec(e);if(r){let n=r[0],o=eb(n,r[3]||"");return{type:"code",raw:n,lang:r[2]?r[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):r[2],text:o}}}heading(e){let r=this.rules.block.heading.exec(e);if(r){let n=r[2].trim();if(/#$/.test(n)){let o=Ti(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:r[0],depth:r[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let r=this.rules.block.hr.exec(e);if(r)return{type:"hr",raw:r[0]}}blockquote(e){let r=this.rules.block.blockquote.exec(e);if(r){let n=r[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
9
- $1`);n=Ti(n.replace(/^ *>[ \t]?/gm,""),`
10
- `);let o=this.lexer.state.top;this.lexer.state.top=!0;let s=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:r[0],tokens:s,text:n}}}list(e){let r=this.rules.block.list.exec(e);if(r){let n=r[1].trim(),o=n.length>1,s={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let a=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let p=!1;if(!(r=a.exec(e))||this.rules.block.hr.test(e))break;i=r[0],e=e.substring(i.length);let m=r[2].split(`
11
- `,1)[0].replace(/^\t+/,k=>" ".repeat(3*k.length)),u=e.split(`
12
- `,1)[0],f=0;this.options.pedantic?(f=2,d=m.trimStart()):(f=r[2].search(/[^ ]/),f=f>4?1:f,d=m.slice(f),f+=r[1].length);let x=!1;if(!m&&/^ *$/.test(u)&&(i+=u+`
13
- `,e=e.substring(u.length+1),p=!0),!p){let k=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),T=new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),M=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),h=new RegExp(`^ {0,${Math.min(3,f-1)}}#`);for(;e;){let w=e.split(`
14
- `,1)[0];if(u=w,this.options.pedantic&&(u=u.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),M.test(u)||h.test(u)||k.test(u)||T.test(e))break;if(u.search(/[^ ]/)>=f||!u.trim())d+=`
15
- `+u.slice(f);else{if(x||m.search(/[^ ]/)>=4||M.test(m)||h.test(m)||T.test(m))break;d+=`
16
- `+u}!x&&!u.trim()&&(x=!0),i+=w+`
17
- `,e=e.substring(w.length+1),m=u.slice(f)}}s.loose||(l?s.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let C=null,S;this.options.gfm&&(C=/^\[[ xX]\] /.exec(d),C&&(S=C[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!C,checked:S,loose:!1,text:d,tokens:[]}),s.raw+=i}s.items[s.items.length-1].raw=i.trimEnd(),s.items[s.items.length-1].text=d.trimEnd(),s.raw=s.raw.trimEnd();for(let p=0;p<s.items.length;p++)if(this.lexer.state.top=!1,s.items[p].tokens=this.lexer.blockTokens(s.items[p].text,[]),!s.loose){let m=s.items[p].tokens.filter(f=>f.type==="space"),u=m.length>0&&m.some(f=>/\n.*\n/.test(f.raw));s.loose=u}if(s.loose)for(let p=0;p<s.items.length;p++)s.items[p].loose=!0;return s}}html(e){let r=this.rules.block.html.exec(e);if(r)return{type:"html",block:!0,raw:r[0],pre:r[1]==="pre"||r[1]==="script"||r[1]==="style",text:r[0]}}def(e){let r=this.rules.block.def.exec(e);if(r){let n=r[1].toLowerCase().replace(/\s+/g," "),o=r[2]?r[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=r[3]?r[3].substring(1,r[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):r[3];return{type:"def",tag:n,raw:r[0],href:o,title:s}}}table(e){let r=this.rules.block.table.exec(e);if(!r||!/[:|]/.test(r[2]))return;let n=Rg(r[1]),o=r[2].replace(/^\||\| *$/g,"").split("|"),s=r[3]&&r[3].trim()?r[3].replace(/\n[ \t]*$/,"").split(`
18
- `):[],a={type:"table",raw:r[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let i of o)/^ *-+: *$/.test(i)?a.align.push("right"):/^ *:-+: *$/.test(i)?a.align.push("center"):/^ *:-+ *$/.test(i)?a.align.push("left"):a.align.push(null);for(let i of n)a.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of s)a.rows.push(Rg(i,a.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return a}}lheading(e){let r=this.rules.block.lheading.exec(e);if(r)return{type:"heading",raw:r[0],depth:r[2].charAt(0)==="="?1:2,text:r[1],tokens:this.lexer.inline(r[1])}}paragraph(e){let r=this.rules.block.paragraph.exec(e);if(r){let n=r[1].charAt(r[1].length-1)===`
19
- `?r[1].slice(0,-1):r[1];return{type:"paragraph",raw:r[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let r=this.rules.block.text.exec(e);if(r)return{type:"text",raw:r[0],text:r[0],tokens:this.lexer.inline(r[0])}}escape(e){let r=this.rules.inline.escape.exec(e);if(r)return{type:"escape",raw:r[0],text:gn(r[1])}}tag(e){let r=this.rules.inline.tag.exec(e);if(r)return!this.lexer.state.inLink&&/^<a /i.test(r[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(r[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:r[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:r[0]}}link(e){let r=this.rules.inline.link.exec(e);if(r){let n=r[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let a=Ti(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=Zy(r[2],"()");if(a>-1){let d=(r[0].indexOf("!")===0?5:4)+r[1].length+a;r[2]=r[2].substring(0,a),r[0]=r[0].substring(0,d).trim(),r[3]=""}}let o=r[2],s="";if(this.options.pedantic){let a=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);a&&(o=a[1],s=a[3])}else s=r[3]?r[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(n)?o=o.slice(1):o=o.slice(1,-1)),Wg(r,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},r[0],this.lexer)}}reflink(e,r){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(/\s+/g," "),s=r[o.toLowerCase()];if(!s){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return Wg(n,s,n[0],this.lexer)}}emStrong(e,r,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o||o[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(o[1]||o[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let a=[...o[0]].length-1,i,d,l=a,p=0,m=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,r=r.slice(-1*e.length+a);(o=m.exec(r))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&a%3&&!((a+d)%3)){p+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+p);let u=[...o[0]][0].length,f=e.slice(0,a+o.index+u+d);if(Math.min(a,d)%2){let C=f.slice(1,-1);return{type:"em",raw:f,text:C,tokens:this.lexer.inlineTokens(C)}}let x=f.slice(2,-2);return{type:"strong",raw:f,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(e){let r=this.rules.inline.code.exec(e);if(r){let n=r[2].replace(/\n/g," "),o=/[^ ]/.test(n),s=/^ /.test(n)&&/ $/.test(n);return o&&s&&(n=n.substring(1,n.length-1)),n=gn(n,!0),{type:"codespan",raw:r[0],text:n}}}br(e){let r=this.rules.inline.br.exec(e);if(r)return{type:"br",raw:r[0]}}del(e){let r=this.rules.inline.del.exec(e);if(r)return{type:"del",raw:r[0],text:r[2],tokens:this.lexer.inlineTokens(r[2])}}autolink(e){let r=this.rules.inline.autolink.exec(e);if(r){let n,o;return r[2]==="@"?(n=gn(r[1]),o="mailto:"+n):(n=gn(r[1]),o=n),{type:"link",raw:r[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,o;let r;if(r=this.rules.inline.url.exec(e)){let s,a;if(r[2]==="@")s=gn(r[0]),a="mailto:"+s;else{let i;do i=r[0],r[0]=(o=(n=this.rules.inline._backpedal.exec(r[0]))==null?void 0:n[0])!=null?o:"";while(i!==r[0]);s=gn(r[0]),r[1]==="www."?a="http://"+r[0]:a=r[0]}return{type:"link",raw:r[0],text:s,href:a,tokens:[{type:"text",raw:s,text:s}]}}}inlineText(e){let r=this.rules.inline.text.exec(e);if(r){let n;return this.lexer.state.inRawBlock?n=r[0]:n=gn(r[0]),{type:"text",raw:r[0],text:n}}}},tb=/^(?: *(?:\n|$))+/,rb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,nb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,vs=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ob=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ng=/(?:[*+-]|\d{1,9}[.)])/,_g=or(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Ng).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),dd=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ab=/^[^\n]+/,cd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,sb=or(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",cd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ib=or(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ng).getRegex(),Ei="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",pd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,lb=or("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",pd).replace("tag",Ei).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Fg=or(dd).replace("hr",vs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ei).getRegex(),db=or(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Fg).getRegex(),ud={blockquote:db,code:rb,def:sb,fences:nb,heading:ob,hr:vs,html:lb,lheading:_g,list:ib,newline:tb,paragraph:Fg,table:ys,text:ab},Bg=or("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",vs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ei).getRegex(),cb={...ud,table:Bg,paragraph:or(dd).replace("hr",vs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Bg).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ei).getRegex()},pb={...ud,html:or(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",pd).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ys,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:or(dd).replace("hr",vs).replace("heading",` *#{1,6} *[^
20
- ]`).replace("lheading",_g).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},$g=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ub=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ug=/^( {2,}|\\)\n(?!\s*$)/,fb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Cs="\\p{P}\\p{S}",mb=or(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Cs).getRegex(),gb=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,hb=or(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Cs).getRegex(),xb=or("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Cs).getRegex(),yb=or("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Cs).getRegex(),bb=or(/\\([punct])/,"gu").replace(/punct/g,Cs).getRegex(),wb=or(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),vb=or(pd).replace("(?:-->|$)","-->").getRegex(),Cb=or("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",vb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ki=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ab=or(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",ki).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),qg=or(/^!?\[(label)\]\[(ref)\]/).replace("label",ki).replace("ref",cd).getRegex(),zg=or(/^!?\[(ref)\](?:\[\])?/).replace("ref",cd).getRegex(),Sb=or("reflink|nolink(?!\\()","g").replace("reflink",qg).replace("nolink",zg).getRegex(),fd={_backpedal:ys,anyPunctuation:bb,autolink:wb,blockSkip:gb,br:Ug,code:ub,del:ys,emStrongLDelim:hb,emStrongRDelimAst:xb,emStrongRDelimUnd:yb,escape:$g,link:Ab,nolink:zg,punctuation:mb,reflink:qg,reflinkSearch:Sb,tag:Cb,text:fb,url:ys},Tb={...fd,link:or(/^!?\[(label)\]\((.*?)\)/).replace("label",ki).getRegex(),reflink:or(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ki).getRegex()},sd={...fd,escape:or($g).replace("])","~|])").getRegex(),url:or(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Mb={...sd,br:or(Ug).replace("{2,}","*").getRegex(),text:or(sd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mi={normal:ud,gfm:cb,pedantic:pb},xs={normal:fd,gfm:sd,breaks:Mb,pedantic:Tb},co=class t{constructor(e){Ht(this,"tokens");Ht(this,"options");Ht(this,"state");Ht(this,"tokenizer");Ht(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ra,this.options.tokenizer=this.options.tokenizer||new Ma,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={block:Mi.normal,inline:xs.normal};this.options.pedantic?(r.block=Mi.pedantic,r.inline=xs.pedantic):this.options.gfm&&(r.block=Mi.gfm,this.options.breaks?r.inline=xs.breaks:r.inline=xs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Mi,inline:xs}}static lex(e,r){return new t(r).lex(e)}static lexInline(e,r){return new t(r).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
7
+ `)}var $a=class{constructor(e){$t(this,"options");$t(this,"rules");$t(this,"lexer");this.options=e||fa}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:Wi(n,`
8
+ `)}}}fences(e){let r=this.rules.block.fences.exec(e);if(r){let n=r[0],o=$b(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=Wi(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:r[0],depth:r[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let r=this.rules.block.hr.exec(e);if(r)return{type:"hr",raw:r[0]}}blockquote(e){let r=this.rules.block.blockquote.exec(e);if(r){let n=r[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
9
+ $1`);n=Wi(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+/,k=>" ".repeat(3*k.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 k=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+|$)`),M=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," ")),M.test(f)||h.test(f)||k.test(f)||E.test(e))break;if(f.search(/[^ ]/)>=m||!f.trim())d+=`
15
+ `+f.slice(m);else{if(y||u.search(/[^ ]/)>=4||M.test(u)||h.test(u)||E.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=sh(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(sh(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:Cn(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=Wi(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=Fb(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)),ih(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 ih(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=Cn(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=Cn(r[1]),o="mailto:"+n):(n=Cn(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=Cn(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=Cn(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=Cn(r[0]),{type:"text",raw:r[0],text:n}}}},Ub=/^(?: *(?:\n|$))+/,qb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,zb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ds=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Vb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,uh=/(?:[*+-]|\d{1,9}[.)])/,fh=dr(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,uh).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(),Ad=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,jb=/^[^\n]+/,Sd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Gb=dr(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",Sd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Kb=dr(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,uh).getRegex(),Di="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",Td=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Xb=dr("^ {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",Td).replace("tag",Di).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mh=dr(Ad).replace("hr",Ds).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",Di).getRegex(),Jb=dr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",mh).getRegex(),Md={blockquote:Jb,code:qb,def:Gb,fences:zb,heading:Vb,hr:Ds,html:Xb,lheading:fh,list:Kb,newline:Ub,paragraph:mh,table:Ws,text:jb},lh=dr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ds).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",Di).getRegex(),Qb={...Md,table:lh,paragraph:dr(Ad).replace("hr",Ds).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",lh).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",Di).getRegex()},Yb={...Md,html:dr(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Td).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:Ws,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:dr(Ad).replace("hr",Ds).replace("heading",` *#{1,6} *[^
20
+ ]`).replace("lheading",fh).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},gh=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Zb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,hh=/^( {2,}|\\)\n(?!\s*$)/,e0=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Os="\\p{P}\\p{S}",t0=dr(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Os).getRegex(),r0=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,n0=dr(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Os).getRegex(),o0=dr("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Os).getRegex(),a0=dr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Os).getRegex(),s0=dr(/\\([punct])/,"gu").replace(/punct/g,Os).getRegex(),i0=dr(/^<(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(),l0=dr(Td).replace("(?:-->|$)","-->").getRegex(),d0=dr("^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",l0).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Bi=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,c0=dr(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Bi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xh=dr(/^!?\[(label)\]\[(ref)\]/).replace("label",Bi).replace("ref",Sd).getRegex(),yh=dr(/^!?\[(ref)\](?:\[\])?/).replace("ref",Sd).getRegex(),p0=dr("reflink|nolink(?!\\()","g").replace("reflink",xh).replace("nolink",yh).getRegex(),kd={_backpedal:Ws,anyPunctuation:s0,autolink:i0,blockSkip:r0,br:hh,code:Zb,del:Ws,emStrongLDelim:n0,emStrongRDelimAst:o0,emStrongRDelimUnd:a0,escape:gh,link:c0,nolink:yh,punctuation:t0,reflink:xh,reflinkSearch:p0,tag:d0,text:e0,url:Ws},u0={...kd,link:dr(/^!?\[(label)\]\((.*?)\)/).replace("label",Bi).getRegex(),reflink:dr(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Bi).getRegex()},wd={...kd,escape:dr(gh).replace("])","~|])").getRegex(),url:dr(/^((?: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.!#$%&'*+\/=?_`{\|}~-]+@)))/},f0={...wd,br:dr(hh).replace("{2,}","*").getRegex(),text:dr(wd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Hi={normal:Md,gfm:Qb,pedantic:Yb},Rs={normal:kd,gfm:wd,breaks:f0,pedantic:u0},bo=class t{constructor(e){$t(this,"tokens");$t(this,"options");$t(this,"state");$t(this,"tokenizer");$t(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||fa,this.options.tokenizer=this.options.tokenizer||new $a,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:Hi.normal,inline:Rs.normal};this.options.pedantic?(r.block=Hi.pedantic,r.inline=Rs.pedantic):this.options.gfm&&(r.block=Hi.gfm,this.options.breaks?r.inline=Rs.breaks:r.inline=Rs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Hi,inline:Rs}}static lex(e,r){return new t(r).lex(e)}static lexInline(e,r){return new t(r).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
21
21
  `),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,s,a;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=`
22
22
  `:r.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
23
23
  `+n.raw,o.text+=`
@@ -27,9 +27,9 @@ Known schemas:
27
27
  `+n.raw,o.text+=`
28
28
  `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n),a=s.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&o.type==="text"?(o.raw+=`
29
29
  `+n.raw,o.text+=`
30
- `+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):r.push(n);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){let n,o,s,a=e,i,d,l;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(p=>(n=p.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length),o=r[r.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(n=this.tokenizer.emStrong(e,a,l)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.del(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),r.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),r.push(n);continue}if(s=e,this.options.extensions&&this.options.extensions.startInline){let p=1/0,m=e.slice(1),u;this.options.extensions.startInline.forEach(f=>{u=f.call({lexer:this},m),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(s=e.substring(0,p+1))}if(n=this.tokenizer.inlineText(s)){e=e.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=r[r.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):r.push(n);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return r}},ka=class{constructor(e){Ht(this,"options");this.options=e||ra}code(e,r,n){var s;let o=(s=(r||"").match(/^\S*/))==null?void 0:s[0];return e=e.replace(/\n$/,"")+`
31
- `,o?'<pre><code class="language-'+gn(o)+'">'+(n?e:gn(e,!0))+`</code></pre>
32
- `:"<pre><code>"+(n?e:gn(e,!0))+`</code></pre>
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}},Ua=class{constructor(e){$t(this,"options");this.options=e||fa}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-'+Cn(o)+'">'+(n?e:Cn(e,!0))+`</code></pre>
32
+ `:"<pre><code>"+(n?e:Cn(e,!0))+`</code></pre>
33
33
  `}blockquote(e){return`<blockquote>
34
34
  ${e}</blockquote>
35
35
  `}html(e,r){return e}heading(e,r,n){return`<h${r}>${e}</h${r}>
@@ -45,24 +45,24 @@ ${e}</blockquote>
45
45
  `}tablerow(e){return`<tr>
46
46
  ${e}</tr>
47
47
  `}tablecell(e,r){let n=r.header?"th":"td";return(r.align?`<${n} align="${r.align}">`:`<${n}>`)+e+`</${n}>
48
- `}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,r,n){let o=Ig(e);if(o===null)return n;e=o;let s='<a href="'+e+'"';return r&&(s+=' title="'+r+'"'),s+=">"+n+"</a>",s}image(e,r,n){let o=Ig(e);if(o===null)return n;e=o;let s=`<img src="${e}" alt="${n}"`;return r&&(s+=` title="${r}"`),s+=">",s}text(e){return e}},bs=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,r,n){return""+n}image(e,r,n){return""+n}br(){return""}},po=class t{constructor(e){Ht(this,"options");Ht(this,"renderer");Ht(this,"textRenderer");this.options=e||ra,this.options.renderer=this.options.renderer||new ka,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new bs}static parse(e,r){return new t(r).parse(e)}static parseInline(e,r){return new t(r).parseInline(e)}parse(e,r=!0){let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=s,i=this.options.extensions.renderers[a.type].call({parser:this},a);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(a.type)){n+=i||"";continue}}switch(s.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let a=s;n+=this.renderer.heading(this.parseInline(a.tokens),a.depth,Qy(this.parseInline(a.tokens,this.textRenderer)));continue}case"code":{let a=s;n+=this.renderer.code(a.text,a.lang,!!a.escaped);continue}case"table":{let a=s,i="",d="";for(let p=0;p<a.header.length;p++)d+=this.renderer.tablecell(this.parseInline(a.header[p].tokens),{header:!0,align:a.align[p]});i+=this.renderer.tablerow(d);let l="";for(let p=0;p<a.rows.length;p++){let m=a.rows[p];d="";for(let u=0;u<m.length;u++)d+=this.renderer.tablecell(this.parseInline(m[u].tokens),{header:!1,align:a.align[u]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let a=s,i=this.parse(a.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let a=s,i=a.ordered,d=a.start,l=a.loose,p="";for(let m=0;m<a.items.length;m++){let u=a.items[m],f=u.checked,x=u.task,C="";if(u.task){let S=this.renderer.checkbox(!!f);l?u.tokens.length>0&&u.tokens[0].type==="paragraph"?(u.tokens[0].text=S+" "+u.tokens[0].text,u.tokens[0].tokens&&u.tokens[0].tokens.length>0&&u.tokens[0].tokens[0].type==="text"&&(u.tokens[0].tokens[0].text=S+" "+u.tokens[0].tokens[0].text)):u.tokens.unshift({type:"text",text:S+" "}):C+=S+" "}C+=this.parse(u.tokens,l),p+=this.renderer.listitem(C,x,!!f)}n+=this.renderer.list(p,i,d);continue}case"html":{let a=s;n+=this.renderer.html(a.text,a.block);continue}case"paragraph":{let a=s;n+=this.renderer.paragraph(this.parseInline(a.tokens));continue}case"text":{let a=s,i=a.tokens?this.parseInline(a.tokens):a.text;for(;o+1<e.length&&e[o+1].type==="text";)a=e[++o],i+=`
49
- `+(a.tokens?this.parseInline(a.tokens):a.text);n+=r?this.renderer.paragraph(i):i;continue}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,r){r=r||this.renderer;let n="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){n+=a||"";continue}}switch(s.type){case"escape":{let a=s;n+=r.text(a.text);break}case"html":{let a=s;n+=r.html(a.text);break}case"link":{let a=s;n+=r.link(a.href,a.title,this.parseInline(a.tokens,r));break}case"image":{let a=s;n+=r.image(a.href,a.title,a.text);break}case"strong":{let a=s;n+=r.strong(this.parseInline(a.tokens,r));break}case"em":{let a=s;n+=r.em(this.parseInline(a.tokens,r));break}case"codespan":{let a=s;n+=r.codespan(a.text);break}case"br":{n+=r.br();break}case"del":{let a=s;n+=r.del(this.parseInline(a.tokens,r));break}case"text":{let a=s;n+=r.text(a.text);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}},Zo=class{constructor(e){Ht(this,"options");this.options=e||ra}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};Ht(Zo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var ta,id,Vg,ws=class{constructor(...e){Lg(this,ta);Ht(this,"defaults",ld());Ht(this,"options",this.setOptions);Ht(this,"parse",Si(this,ta,id).call(this,co.lex,po.parse));Ht(this,"parseInline",Si(this,ta,id).call(this,co.lexInline,po.parseInline));Ht(this,"Parser",po);Ht(this,"Renderer",ka);Ht(this,"TextRenderer",bs);Ht(this,"Lexer",co);Ht(this,"Tokenizer",Ma);Ht(this,"Hooks",Zo);this.use(...e)}walkTokens(e,r){var o,s;let n=[];for(let a of e)switch(n=n.concat(r.call(this,a)),a.type){case"table":{let i=a;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,r));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,r));break}case"list":{let i=a;n=n.concat(this.walkTokens(i.items,r));break}default:{let i=a;(s=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&s[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,r))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,r)))}}return n}use(...e){let r=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let a=r.renderers[s.name];a?r.renderers[s.name]=function(...i){let d=s.renderer.apply(this,i);return d===!1&&(d=a.apply(this,i)),d}:r.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=r[s.level];a?a.unshift(s.tokenizer):r[s.level]=[s.tokenizer],s.start&&(s.level==="block"?r.startBlock?r.startBlock.push(s.start):r.startBlock=[s.start]:s.level==="inline"&&(r.startInline?r.startInline.push(s.start):r.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(r.childTokens[s.name]=s.childTokens)}),o.extensions=r),n.renderer){let s=this.defaults.renderer||new ka(this.defaults);for(let a in n.renderer){if(!(a in s))throw new Error(`renderer '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.renderer[i],l=s[i];s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m||""}}o.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Ma(this.defaults);for(let a in n.tokenizer){if(!(a in s))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let i=a,d=n.tokenizer[i],l=s[i];s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m}}o.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new Zo;for(let a in n.hooks){if(!(a in s))throw new Error(`hook '${a}' does not exist`);if(a==="options")continue;let i=a,d=n.hooks[i],l=s[i];Zo.passThroughHooks.has(a)?s[i]=p=>{if(this.defaults.async)return Promise.resolve(d.call(s,p)).then(u=>l.call(s,u));let m=d.call(s,p);return l.call(s,m)}:s[i]=(...p)=>{let m=d.apply(s,p);return m===!1&&(m=l.apply(s,p)),m}}o.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,a=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(a.call(this,i)),s&&(d=d.concat(s.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,r){return co.lex(e,r!=null?r:this.defaults)}parser(e,r){return po.parse(e,r!=null?r:this.defaults)}};ta=new WeakSet,id=function(e,r){return(n,o)=>{let s={...o},a={...this.defaults,...s};this.defaults.async===!0&&s.async===!1&&(a.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),a.async=!0);let i=Si(this,ta,Vg).call(this,!!a.silent,!!a.async);if(typeof n=="undefined"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(a.hooks&&(a.hooks.options=a),a.async)return Promise.resolve(a.hooks?a.hooks.preprocess(n):n).then(d=>e(d,a)).then(d=>a.hooks?a.hooks.processAllTokens(d):d).then(d=>a.walkTokens?Promise.all(this.walkTokens(d,a.walkTokens)).then(()=>d):d).then(d=>r(d,a)).then(d=>a.hooks?a.hooks.postprocess(d):d).catch(i);try{a.hooks&&(n=a.hooks.preprocess(n));let d=e(n,a);a.hooks&&(d=a.hooks.processAllTokens(d)),a.walkTokens&&this.walkTokens(d,a.walkTokens);let l=r(d,a);return a.hooks&&(l=a.hooks.postprocess(l)),l}catch(d){return i(d)}}},Vg=function(e,r){return n=>{if(n.message+=`
50
- Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+gn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var ea=new ws;function nr(t,e){return ea.parse(t,e)}nr.options=nr.setOptions=function(t){return ea.setOptions(t),nr.defaults=ea.defaults,Hg(nr.defaults),nr};nr.getDefaults=ld;nr.defaults=ra;nr.use=function(...t){return ea.use(...t),nr.defaults=ea.defaults,Hg(nr.defaults),nr};nr.walkTokens=function(t,e){return ea.walkTokens(t,e)};nr.parseInline=ea.parseInline;nr.Parser=po;nr.parser=po.parse;nr.Renderer=ka;nr.TextRenderer=bs;nr.Lexer=co;nr.lexer=co.lex;nr.Tokenizer=Ma;nr.Hooks=Zo;nr.parse=nr;var iA=nr.options,lA=nr.setOptions,dA=nr.use,cA=nr.walkTokens,pA=nr.parseInline;var uA=po.parse,fA=co.lex;var kb=t=>{if(t)return t},As=t=>{var o,s;let e=t==null?void 0:t.markedOptions,r=new ws({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=kb(t==null?void 0:t.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},na=t=>t?As({markedOptions:t.options,renderer:t.renderer}):As(),Eb=As(),md=t=>Eb(t),oa=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Gg=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),jg=t=>`%%FORM_PLACEHOLDER_${t}%%`,Kg=(t,e)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=jg(e.length);return e.push({token:a,type:String(s.type)}),a}}catch{return n}return n}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let s=jg(e.length);return e.push({token:s,type:o}),s}),r},Xg=t=>{let e=na(t);return r=>{let n=[],o=Kg(r,n),s=e(o);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Gg(i)}"></div>`;s=s.replace(d,p)}),s}},Jg=t=>{let e=[],r=Kg(t,e),n=md(r);return e.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Gg(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:ah,setPrototypeOf:Qg,isFrozen:Lb,getPrototypeOf:Pb,getOwnPropertyDescriptor:Ib}=Object,{freeze:Qr,seal:Mn,create:Ii}=Object,{apply:vd,construct:Cd}=typeof Reflect!="undefined"&&Reflect;Qr||(Qr=function(e){return e});Mn||(Mn=function(e){return e});vd||(vd=function(e,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return e.apply(r,o)});Cd||(Cd=function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return new e(...n)});var Li=Yr(Array.prototype.forEach),Rb=Yr(Array.prototype.lastIndexOf),Yg=Yr(Array.prototype.pop),Ss=Yr(Array.prototype.push),Wb=Yr(Array.prototype.splice),Ri=Yr(String.prototype.toLowerCase),gd=Yr(String.prototype.toString),hd=Yr(String.prototype.match),Ts=Yr(String.prototype.replace),Bb=Yr(String.prototype.indexOf),Hb=Yr(String.prototype.trim),hn=Yr(Object.prototype.hasOwnProperty),Jr=Yr(RegExp.prototype.test),Ms=Db(TypeError);function Yr(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return vd(t,e,n)}}function Db(t){return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return Cd(t,r)}}function It(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ri;Qg&&Qg(t,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let s=r(o);s!==o&&(Lb(e)||(e[n]=s),o=s)}t[o]=!0}return t}function Ob(t){for(let e=0;e<t.length;e++)hn(t,e)||(t[e]=null);return t}function Kn(t){let e=Ii(null);for(let[r,n]of ah(t))hn(t,r)&&(Array.isArray(n)?e[r]=Ob(n):n&&typeof n=="object"&&n.constructor===Object?e[r]=Kn(n):e[r]=n);return e}function ks(t,e){for(;t!==null;){let n=Ib(t,e);if(n){if(n.get)return Yr(n.get);if(typeof n.value=="function")return Yr(n.value)}t=Pb(t)}function r(){return null}return r}var Zg=Qr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),xd=Qr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),yd=Qr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Nb=Qr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),bd=Qr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),_b=Qr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),eh=Qr(["#text"]),th=Qr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),wd=Qr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),rh=Qr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Pi=Qr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Fb=Mn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),$b=Mn(/<%[\w\W]*|[\w\W]*%>/gm),Ub=Mn(/\$\{[\w\W]*/gm),qb=Mn(/^data-[\-\w.\u00B7-\uFFFF]+$/),zb=Mn(/^aria-[\-\w]+$/),sh=Mn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vb=Mn(/^(?:\w+script|data):/i),jb=Mn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ih=Mn(/^html$/i),Gb=Mn(/^[a-z][.\w]*(-[.\w]+)+$/i),nh=Object.freeze({__proto__:null,ARIA_ATTR:zb,ATTR_WHITESPACE:jb,CUSTOM_ELEMENT:Gb,DATA_ATTR:qb,DOCTYPE_NAME:ih,ERB_EXPR:$b,IS_ALLOWED_URI:sh,IS_SCRIPT_OR_DATA:Vb,MUSTACHE_EXPR:Fb,TMPLIT_EXPR:Ub}),Es={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Kb=function(){return typeof window=="undefined"?null:window},Xb=function(e,r){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(n=r.getAttribute(o));let s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},oh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function lh(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Kb(),e=ue=>lh(ue);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Es.document||!t.Element)return e.isSupported=!1,e;let{document:r}=t,n=r,o=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:i,Element:d,NodeFilter:l,NamedNodeMap:p=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:u,trustedTypes:f}=t,x=d.prototype,C=ks(x,"cloneNode"),S=ks(x,"remove"),k=ks(x,"nextSibling"),T=ks(x,"childNodes"),M=ks(x,"parentNode");if(typeof a=="function"){let ue=r.createElement("template");ue.content&&ue.content.ownerDocument&&(r=ue.content.ownerDocument)}let h,w="",{implementation:y,createNodeIterator:E,createDocumentFragment:B,getElementsByTagName:P}=r,{importNode:R}=n,O=oh();e.isSupported=typeof ah=="function"&&typeof M=="function"&&y&&y.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:ne,TMPLIT_EXPR:be,DATA_ATTR:Ye,ARIA_ATTR:Ge,IS_SCRIPT_OR_DATA:ve,ATTR_WHITESPACE:Ee,CUSTOM_ELEMENT:Ke}=nh,{IS_ALLOWED_URI:Ne}=nh,X=null,Ue=It({},[...Zg,...xd,...yd,...bd,...eh]),K=null,Te=It({},[...th,...wd,...rh,...Pi]),oe=Object.seal(Ii(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),xe=null,Me=null,Xe=Object.seal(Ii(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ce=!0,te=!0,le=!1,ut=!0,Ce=!1,he=!0,rt=!1,_e=!1,me=!1,J=!1,ze=!1,Z=!1,ge=!0,z=!1,Re="user-content-",Ae=!0,fe=!1,pe={},Be=null,Q=It({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),_=null,ke=It({},["audio","video","img","source","image","track"]),He=null,Ve=It({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Je="http://www.w3.org/1998/Math/MathML",gt="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml",Mt=at,Xt=!1,G=null,Jt=It({},[Je,gt,at],gd),st=It({},["mi","mo","mn","ms","mtext"]),_t=It({},["annotation-xml"]),de=It({},["title","style","font","a","script"]),ye=null,Rt=["application/xhtml+xml","text/html"],ar="text/html",kt=null,mr=null,Ot=r.createElement("form"),Wt=function(I){return I instanceof RegExp||I instanceof Function},St=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(mr&&mr===I)){if((!I||typeof I!="object")&&(I={}),I=Kn(I),ye=Rt.indexOf(I.PARSER_MEDIA_TYPE)===-1?ar:I.PARSER_MEDIA_TYPE,kt=ye==="application/xhtml+xml"?gd:Ri,X=hn(I,"ALLOWED_TAGS")?It({},I.ALLOWED_TAGS,kt):Ue,K=hn(I,"ALLOWED_ATTR")?It({},I.ALLOWED_ATTR,kt):Te,G=hn(I,"ALLOWED_NAMESPACES")?It({},I.ALLOWED_NAMESPACES,gd):Jt,He=hn(I,"ADD_URI_SAFE_ATTR")?It(Kn(Ve),I.ADD_URI_SAFE_ATTR,kt):Ve,_=hn(I,"ADD_DATA_URI_TAGS")?It(Kn(ke),I.ADD_DATA_URI_TAGS,kt):ke,Be=hn(I,"FORBID_CONTENTS")?It({},I.FORBID_CONTENTS,kt):Q,xe=hn(I,"FORBID_TAGS")?It({},I.FORBID_TAGS,kt):Kn({}),Me=hn(I,"FORBID_ATTR")?It({},I.FORBID_ATTR,kt):Kn({}),pe=hn(I,"USE_PROFILES")?I.USE_PROFILES:!1,ce=I.ALLOW_ARIA_ATTR!==!1,te=I.ALLOW_DATA_ATTR!==!1,le=I.ALLOW_UNKNOWN_PROTOCOLS||!1,ut=I.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ce=I.SAFE_FOR_TEMPLATES||!1,he=I.SAFE_FOR_XML!==!1,rt=I.WHOLE_DOCUMENT||!1,J=I.RETURN_DOM||!1,ze=I.RETURN_DOM_FRAGMENT||!1,Z=I.RETURN_TRUSTED_TYPE||!1,me=I.FORCE_BODY||!1,ge=I.SANITIZE_DOM!==!1,z=I.SANITIZE_NAMED_PROPS||!1,Ae=I.KEEP_CONTENT!==!1,fe=I.IN_PLACE||!1,Ne=I.ALLOWED_URI_REGEXP||sh,Mt=I.NAMESPACE||at,st=I.MATHML_TEXT_INTEGRATION_POINTS||st,_t=I.HTML_INTEGRATION_POINTS||_t,oe=I.CUSTOM_ELEMENT_HANDLING||{},I.CUSTOM_ELEMENT_HANDLING&&Wt(I.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(oe.tagNameCheck=I.CUSTOM_ELEMENT_HANDLING.tagNameCheck),I.CUSTOM_ELEMENT_HANDLING&&Wt(I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(oe.attributeNameCheck=I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),I.CUSTOM_ELEMENT_HANDLING&&typeof I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(oe.allowCustomizedBuiltInElements=I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ce&&(te=!1),ze&&(J=!0),pe&&(X=It({},eh),K=Ii(null),pe.html===!0&&(It(X,Zg),It(K,th)),pe.svg===!0&&(It(X,xd),It(K,wd),It(K,Pi)),pe.svgFilters===!0&&(It(X,yd),It(K,wd),It(K,Pi)),pe.mathMl===!0&&(It(X,bd),It(K,rh),It(K,Pi))),hn(I,"ADD_TAGS")||(Xe.tagCheck=null),hn(I,"ADD_ATTR")||(Xe.attributeCheck=null),I.ADD_TAGS&&(typeof I.ADD_TAGS=="function"?Xe.tagCheck=I.ADD_TAGS:(X===Ue&&(X=Kn(X)),It(X,I.ADD_TAGS,kt))),I.ADD_ATTR&&(typeof I.ADD_ATTR=="function"?Xe.attributeCheck=I.ADD_ATTR:(K===Te&&(K=Kn(K)),It(K,I.ADD_ATTR,kt))),I.ADD_URI_SAFE_ATTR&&It(He,I.ADD_URI_SAFE_ATTR,kt),I.FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,I.FORBID_CONTENTS,kt)),I.ADD_FORBID_CONTENTS&&(Be===Q&&(Be=Kn(Be)),It(Be,I.ADD_FORBID_CONTENTS,kt)),Ae&&(X["#text"]=!0),rt&&It(X,["html","head","body"]),X.table&&(It(X,["tbody"]),delete xe.tbody),I.TRUSTED_TYPES_POLICY){if(typeof I.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ms('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof I.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ms('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');h=I.TRUSTED_TYPES_POLICY,w=h.createHTML("")}else h===void 0&&(h=Xb(f,o)),h!==null&&typeof w=="string"&&(w=h.createHTML(""));Qr&&Qr(I),mr=I}},Et=It({},[...xd,...yd,...Nb]),sr=It({},[...bd,..._b]),ft=function(I){let ee=M(I);(!ee||!ee.tagName)&&(ee={namespaceURI:Mt,tagName:"template"});let Se=Ri(I.tagName),nt=Ri(ee.tagName);return G[I.namespaceURI]?I.namespaceURI===gt?ee.namespaceURI===at?Se==="svg":ee.namespaceURI===Je?Se==="svg"&&(nt==="annotation-xml"||st[nt]):!!Et[Se]:I.namespaceURI===Je?ee.namespaceURI===at?Se==="math":ee.namespaceURI===gt?Se==="math"&&_t[nt]:!!sr[Se]:I.namespaceURI===at?ee.namespaceURI===gt&&!_t[nt]||ee.namespaceURI===Je&&!st[nt]?!1:!sr[Se]&&(de[Se]||!Et[Se]):!!(ye==="application/xhtml+xml"&&G[I.namespaceURI]):!1},dr=function(I){Ss(e.removed,{element:I});try{M(I).removeChild(I)}catch{S(I)}},wr=function(I,ee){try{Ss(e.removed,{attribute:ee.getAttributeNode(I),from:ee})}catch{Ss(e.removed,{attribute:null,from:ee})}if(ee.removeAttribute(I),I==="is")if(J||ze)try{dr(ee)}catch{}else try{ee.setAttribute(I,"")}catch{}},Lr=function(I){let ee=null,Se=null;if(me)I="<remove></remove>"+I;else{let Ft=hd(I,/^[\r\n\t ]+/);Se=Ft&&Ft[0]}ye==="application/xhtml+xml"&&Mt===at&&(I='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+I+"</body></html>");let nt=h?h.createHTML(I):I;if(Mt===at)try{ee=new u().parseFromString(nt,ye)}catch{}if(!ee||!ee.documentElement){ee=y.createDocument(Mt,"template",null);try{ee.documentElement.innerHTML=Xt?w:nt}catch{}}let Qt=ee.body||ee.documentElement;return I&&Se&&Qt.insertBefore(r.createTextNode(Se),Qt.childNodes[0]||null),Mt===at?P.call(ee,rt?"html":"body")[0]:rt?ee.documentElement:Qt},Or=function(I){return E.call(I.ownerDocument||I,I,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},xt=function(I){return I instanceof m&&(typeof I.nodeName!="string"||typeof I.textContent!="string"||typeof I.removeChild!="function"||!(I.attributes instanceof p)||typeof I.removeAttribute!="function"||typeof I.setAttribute!="function"||typeof I.namespaceURI!="string"||typeof I.insertBefore!="function"||typeof I.hasChildNodes!="function")},sn=function(I){return typeof i=="function"&&I instanceof i};function fr(ue,I,ee){Li(ue,Se=>{Se.call(e,I,ee,mr)})}let Un=function(I){let ee=null;if(fr(O.beforeSanitizeElements,I,null),xt(I))return dr(I),!0;let Se=kt(I.nodeName);if(fr(O.uponSanitizeElement,I,{tagName:Se,allowedTags:X}),he&&I.hasChildNodes()&&!sn(I.firstElementChild)&&Jr(/<[/\w!]/g,I.innerHTML)&&Jr(/<[/\w!]/g,I.textContent)||I.nodeType===Es.progressingInstruction||he&&I.nodeType===Es.comment&&Jr(/<[/\w]/g,I.data))return dr(I),!0;if(!(Xe.tagCheck instanceof Function&&Xe.tagCheck(Se))&&(!X[Se]||xe[Se])){if(!xe[Se]&&Zn(Se)&&(oe.tagNameCheck instanceof RegExp&&Jr(oe.tagNameCheck,Se)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(Se)))return!1;if(Ae&&!Be[Se]){let nt=M(I)||I.parentNode,Qt=T(I)||I.childNodes;if(Qt&&nt){let Ft=Qt.length;for(let tr=Ft-1;tr>=0;--tr){let Pr=C(Qt[tr],!0);Pr.__removalCount=(I.__removalCount||0)+1,nt.insertBefore(Pr,k(I))}}}return dr(I),!0}return I instanceof d&&!ft(I)||(Se==="noscript"||Se==="noembed"||Se==="noframes")&&Jr(/<\/no(script|embed|frames)/i,I.innerHTML)?(dr(I),!0):(Ce&&I.nodeType===Es.text&&(ee=I.textContent,Li([V,ne,be],nt=>{ee=Ts(ee,nt," ")}),I.textContent!==ee&&(Ss(e.removed,{element:I.cloneNode()}),I.textContent=ee)),fr(O.afterSanitizeElements,I,null),!1)},Rr=function(I,ee,Se){if(Me[ee]||ge&&(ee==="id"||ee==="name")&&(Se in r||Se in Ot))return!1;if(!(te&&!Me[ee]&&Jr(Ye,ee))){if(!(ce&&Jr(Ge,ee))){if(!(Xe.attributeCheck instanceof Function&&Xe.attributeCheck(ee,I))){if(!K[ee]||Me[ee]){if(!(Zn(I)&&(oe.tagNameCheck instanceof RegExp&&Jr(oe.tagNameCheck,I)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(I))&&(oe.attributeNameCheck instanceof RegExp&&Jr(oe.attributeNameCheck,ee)||oe.attributeNameCheck instanceof Function&&oe.attributeNameCheck(ee,I))||ee==="is"&&oe.allowCustomizedBuiltInElements&&(oe.tagNameCheck instanceof RegExp&&Jr(oe.tagNameCheck,Se)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(Se))))return!1}else if(!He[ee]){if(!Jr(Ne,Ts(Se,Ee,""))){if(!((ee==="src"||ee==="xlink:href"||ee==="href")&&I!=="script"&&Bb(Se,"data:")===0&&_[I])){if(!(le&&!Jr(ve,Ts(Se,Ee,"")))){if(Se)return!1}}}}}}}return!0},Zn=function(I){return I!=="annotation-xml"&&hd(I,Ke)},Pn=function(I){fr(O.beforeSanitizeAttributes,I,null);let{attributes:ee}=I;if(!ee||xt(I))return;let Se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0},nt=ee.length;for(;nt--;){let Qt=ee[nt],{name:Ft,namespaceURI:tr,value:Pr}=Qt,Nr=kt(Ft),wn=Pr,Vt=Ft==="value"?wn:Hb(wn);if(Se.attrName=Nr,Se.attrValue=Vt,Se.keepAttr=!0,Se.forceKeepAttr=void 0,fr(O.uponSanitizeAttribute,I,Se),Vt=Se.attrValue,z&&(Nr==="id"||Nr==="name")&&(wr(Ft,I),Vt=Re+Vt),he&&Jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){wr(Ft,I);continue}if(Nr==="attributename"&&hd(Vt,"href")){wr(Ft,I);continue}if(Se.forceKeepAttr)continue;if(!Se.keepAttr){wr(Ft,I);continue}if(!ut&&Jr(/\/>/i,Vt)){wr(Ft,I);continue}Ce&&Li([V,ne,be],Ir=>{Vt=Ts(Vt,Ir," ")});let $t=kt(I.nodeName);if(!Rr($t,Nr,Vt)){wr(Ft,I);continue}if(h&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!tr)switch(f.getAttributeType($t,Nr)){case"TrustedHTML":{Vt=h.createHTML(Vt);break}case"TrustedScriptURL":{Vt=h.createScriptURL(Vt);break}}if(Vt!==wn)try{tr?I.setAttributeNS(tr,Ft,Vt):I.setAttribute(Ft,Vt),xt(I)?dr(I):Yg(e.removed)}catch{wr(Ft,I)}}fr(O.afterSanitizeAttributes,I,null)},In=function ue(I){let ee=null,Se=Or(I);for(fr(O.beforeSanitizeShadowDOM,I,null);ee=Se.nextNode();)fr(O.uponSanitizeShadowNode,ee,null),Un(ee),Pn(ee),ee.content instanceof s&&ue(ee.content);fr(O.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(ue){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ee=null,Se=null,nt=null,Qt=null;if(Xt=!ue,Xt&&(ue="<!-->"),typeof ue!="string"&&!sn(ue))if(typeof ue.toString=="function"){if(ue=ue.toString(),typeof ue!="string")throw Ms("dirty is not a string, aborting")}else throw Ms("toString is not a function");if(!e.isSupported)return ue;if(_e||St(I),e.removed=[],typeof ue=="string"&&(fe=!1),fe){if(ue.nodeName){let Pr=kt(ue.nodeName);if(!X[Pr]||xe[Pr])throw Ms("root node is forbidden and cannot be sanitized in-place")}}else if(ue instanceof i)ee=Lr("<!---->"),Se=ee.ownerDocument.importNode(ue,!0),Se.nodeType===Es.element&&Se.nodeName==="BODY"||Se.nodeName==="HTML"?ee=Se:ee.appendChild(Se);else{if(!J&&!Ce&&!rt&&ue.indexOf("<")===-1)return h&&Z?h.createHTML(ue):ue;if(ee=Lr(ue),!ee)return J?null:Z?w:""}ee&&me&&dr(ee.firstChild);let Ft=Or(fe?ue:ee);for(;nt=Ft.nextNode();)Un(nt),Pn(nt),nt.content instanceof s&&In(nt.content);if(fe)return ue;if(J){if(ze)for(Qt=B.call(ee.ownerDocument);ee.firstChild;)Qt.appendChild(ee.firstChild);else Qt=ee;return(K.shadowroot||K.shadowrootmode)&&(Qt=R.call(n,Qt,!0)),Qt}let tr=rt?ee.outerHTML:ee.innerHTML;return rt&&X["!doctype"]&&ee.ownerDocument&&ee.ownerDocument.doctype&&ee.ownerDocument.doctype.name&&Jr(ih,ee.ownerDocument.doctype.name)&&(tr="<!DOCTYPE "+ee.ownerDocument.doctype.name+`>
51
- `+tr),Ce&&Li([V,ne,be],Pr=>{tr=Ts(tr,Pr," ")}),h&&Z?h.createHTML(tr):tr},e.setConfig=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};St(ue),_e=!0},e.clearConfig=function(){mr=null,_e=!1},e.isValidAttribute=function(ue,I,ee){mr||St({});let Se=kt(ue),nt=kt(I);return Rr(Se,nt,ee)},e.addHook=function(ue,I){typeof I=="function"&&Ss(O[ue],I)},e.removeHook=function(ue,I){if(I!==void 0){let ee=Rb(O[ue],I);return ee===-1?void 0:Wb(O[ue],ee,1)[0]}return Yg(O[ue])},e.removeHooks=function(ue){O[ue]=[]},e.removeAllHooks=function(){O=oh()},e}var dh=lh();var Jb={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Qb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ad=()=>{let t=dh(typeof window!="undefined"?window:void 0);return t.addHook("uponSanitizeAttribute",(e,r)=>{if(r.attrName==="src"||r.attrName==="href"){let n=r.attrValue;n.toLowerCase().startsWith("data:")&&!Qb.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),e=>t.sanitize(e,Jb)},Ea=t=>t===!1?null:typeof t=="function"?t:Ad();var Ls="webmcp:",Fi={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}};function Ph(t){if(t.length===0)return"0:empty";let e=t.map(r=>{var n,o;return[r.name,(n=r.description)!=null?n:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(o=r.origin)!=null?o:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${t.length}:${J0(e.join(""))}`}function Lh(t,e){let r=3735928559^e,n=1103547991^e;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);r=Math.imul(r^s,2654435761),n=Math.imul(n^s,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}function J0(t){let e=Lh(t,0).toString(36),r=Lh(t,2654435761).toString(36);return`${e}.${r}`}var Ia=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=e.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let r;try{r=await e.getTools()}catch(o){return Fi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}let n=typeof location!="undefined"?location.origin:"";return r.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...n?{pageOrigin:n}:{}},a=Y0(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,r,n){if(await this.ensureReady(),this.config.enabled!==!0)return Fn("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let f=typeof document!="undefined"&&!!document.modelContext;return Fn(f?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Id(e),a;try{a=await o.getTools()}catch(f){let x=f instanceof Error?f.message:String(f);return Fn(`Failed to read WebMCP registry: ${x}`)}let i=a.find(f=>f.name===s);if(!i)return Fn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Fn(`WebMCP tool not allowed by client allowlist: ${s}`);if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let d={toolName:s,args:r,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return Fn("User declined the tool call.");if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),u=()=>l.abort();n&&(n.aborted?l.abort():n.addEventListener("abort",u,{once:!0}));try{let f=await o.executeTool(i,rw(r),{signal:l.signal});return Z0(f)}catch(f){if(p)return Fn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return Fn("Aborted by cancel()");let x=f instanceof Error?f.message:String(f);return Fn(x)}finally{clearTimeout(m),n&&n.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await Promise.resolve().then(()=>(Eh(),kh))).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Fi.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let r=e;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Fi.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var n;let r=(n=this.confirmHandler)!=null?n:ew;try{return await r(e)}catch(o){return Fi.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(n=>Q0(e,n))}},Id=t=>t.startsWith(Ls)?t.slice(Ls.length):t,Io=t=>t.startsWith(Ls),Q0=(t,e)=>{if(e==="*")return!0;let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(t)},Y0=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Z0=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:nw(e)}]}},Fn=t=>({isError:!0,content:[{type:"text",text:t}]}),ew=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=tw(t.args),r=`Allow the AI to call ${t.toolName}`+(e?`
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=ah(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=ah(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}},Hs=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""}},wo=class t{constructor(e){$t(this,"options");$t(this,"renderer");$t(this,"textRenderer");this.options=e||fa,this.options.renderer=this.options.renderer||new Ua,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Hs}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,Nb(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}},ca=class{constructor(e){$t(this,"options");this.options=e||fa}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};$t(ca,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var ua,vd,bh,Bs=class{constructor(...e){nh(this,ua);$t(this,"defaults",Cd());$t(this,"options",this.setOptions);$t(this,"parse",Ri(this,ua,vd).call(this,bo.lex,wo.parse));$t(this,"parseInline",Ri(this,ua,vd).call(this,bo.lexInline,wo.parseInline));$t(this,"Parser",wo);$t(this,"Renderer",Ua);$t(this,"TextRenderer",Hs);$t(this,"Lexer",bo);$t(this,"Tokenizer",$a);$t(this,"Hooks",ca);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 Ua(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 $a(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 ca;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];ca.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 bo.lex(e,r!=null?r:this.defaults)}parser(e,r){return wo.parse(e,r!=null?r:this.defaults)}};ua=new WeakSet,vd=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=Ri(this,ua,bh).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)}}},bh=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>"+Cn(n.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(n);throw n}};var pa=new Bs;function lr(t,e){return pa.parse(t,e)}lr.options=lr.setOptions=function(t){return pa.setOptions(t),lr.defaults=pa.defaults,dh(lr.defaults),lr};lr.getDefaults=Cd;lr.defaults=fa;lr.use=function(...t){return pa.use(...t),lr.defaults=pa.defaults,dh(lr.defaults),lr};lr.walkTokens=function(t,e){return pa.walkTokens(t,e)};lr.parseInline=pa.parseInline;lr.Parser=wo;lr.parser=wo.parse;lr.Renderer=Ua;lr.TextRenderer=Hs;lr.Lexer=bo;lr.lexer=bo.lex;lr.Tokenizer=$a;lr.Hooks=ca;lr.parse=lr;var JA=lr.options,QA=lr.setOptions,YA=lr.use,ZA=lr.walkTokens,eS=lr.parseInline;var tS=wo.parse,rS=bo.lex;var m0=t=>{if(t)return t},Ns=t=>{var o,s;let e=t==null?void 0:t.markedOptions,r=new Bs({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=m0(t==null?void 0:t.renderer);return n&&r.use({renderer:n}),a=>r.parse(a)},ma=t=>t?Ns({markedOptions:t.options,renderer:t.renderer}):Ns(),g0=Ns(),Ed=t=>g0(t),ga=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),vh=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),wh=t=>`%%FORM_PLACEHOLDER_${t}%%`,Ch=(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=wh(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=wh(e.length);return e.push({token:s,type:o}),s}),r},Ah=t=>{let e=ma(t);return r=>{let n=[],o=Ch(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="${vh(i)}"></div>`;s=s.replace(d,p)}),s}},Sh=t=>{let e=[],r=Ch(t,e),n=Ed(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="${vh(s)}"></div>`;n=n.replace(a,d)}),n};var{entries:Wh,setPrototypeOf:Th,isFrozen:h0,getPrototypeOf:x0,getOwnPropertyDescriptor:y0}=Object,{freeze:nn,seal:On,create:_i}=Object,{apply:Bd,construct:Dd}=typeof Reflect!="undefined"&&Reflect;nn||(nn=function(e){return e});On||(On=function(e){return e});Bd||(Bd=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)});Dd||(Dd=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 Oi=on(Array.prototype.forEach),b0=on(Array.prototype.lastIndexOf),Mh=on(Array.prototype.pop),_s=on(Array.prototype.push),w0=on(Array.prototype.splice),Fi=on(String.prototype.toLowerCase),Ld=on(String.prototype.toString),Pd=on(String.prototype.match),Fs=on(String.prototype.replace),v0=on(String.prototype.indexOf),C0=on(String.prototype.trim),An=on(Object.prototype.hasOwnProperty),rn=on(RegExp.prototype.test),$s=A0(TypeError);function on(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 Bd(t,e,n)}}function A0(t){return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return Dd(t,r)}}function _t(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Fi;Th&&Th(t,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let s=r(o);s!==o&&(h0(e)||(e[n]=s),o=s)}t[o]=!0}return t}function S0(t){for(let e=0;e<t.length;e++)An(t,e)||(t[e]=null);return t}function ao(t){let e=_i(null);for(let[r,n]of Wh(t))An(t,r)&&(Array.isArray(n)?e[r]=S0(n):n&&typeof n=="object"&&n.constructor===Object?e[r]=ao(n):e[r]=n);return e}function Us(t,e){for(;t!==null;){let n=y0(t,e);if(n){if(n.get)return on(n.get);if(typeof n.value=="function")return on(n.value)}t=x0(t)}function r(){return null}return r}var kh=nn(["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"]),Id=nn(["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"]),Rd=nn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),T0=nn(["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"]),Wd=nn(["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"]),M0=nn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Eh=nn(["#text"]),Lh=nn(["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"]),Hd=nn(["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"]),Ph=nn(["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"]),Ni=nn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),k0=On(/\{\{[\w\W]*|[\w\W]*\}\}/gm),E0=On(/<%[\w\W]*|[\w\W]*%>/gm),L0=On(/\$\{[\w\W]*/gm),P0=On(/^data-[\-\w.\u00B7-\uFFFF]+$/),I0=On(/^aria-[\-\w]+$/),Hh=On(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),R0=On(/^(?:\w+script|data):/i),W0=On(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Bh=On(/^html$/i),H0=On(/^[a-z][.\w]*(-[.\w]+)+$/i),Ih=Object.freeze({__proto__:null,ARIA_ATTR:I0,ATTR_WHITESPACE:W0,CUSTOM_ELEMENT:H0,DATA_ATTR:P0,DOCTYPE_NAME:Bh,ERB_EXPR:E0,IS_ALLOWED_URI:Hh,IS_SCRIPT_OR_DATA:R0,MUSTACHE_EXPR:k0,TMPLIT_EXPR:L0}),qs={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},B0=function(){return typeof window=="undefined"?null:window},D0=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}},Rh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Dh(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:B0(),e=Ge=>Dh(Ge);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==qs.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=Us(y,"cloneNode"),S=Us(y,"remove"),k=Us(y,"nextSibling"),E=Us(y,"childNodes"),M=Us(y,"parentNode");if(typeof a=="function"){let Ge=r.createElement("template");Ge.content&&Ge.content.ownerDocument&&(r=Ge.content.ownerDocument)}let h,C="",{implementation:v,createNodeIterator:T,createDocumentFragment:W,getElementsByTagName:P}=r,{importNode:R}=n,N=Rh();e.isSupported=typeof Wh=="function"&&typeof M=="function"&&v&&v.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:j,ERB_EXPR:ce,TMPLIT_EXPR:be,DATA_ATTR:Ze,ARIA_ATTR:Se,IS_SCRIPT_OR_DATA:Ne,ATTR_WHITESPACE:Ce,CUSTOM_ELEMENT:Fe}=Ih,{IS_ALLOWED_URI:We}=Ih,Z=null,ne=_t({},[...kh,...Id,...Rd,...Wd,...Eh]),ee=null,we=_t({},[...Lh,...Hd,...Ph,...Ni]),Q=Object.seal(_i(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}})),X=null,fe=null,Le=Object.seal(_i(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),me=!0,te=!0,le=!1,ht=!0,mt=!1,Re=!0,ye=!1,ot=!1,He=!1,G=!1,he=!1,K=!1,wt=!0,U=!1,J="user-content-",qe=!0,se=!1,ie={},Be=null,Xe=_t({},["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"]),B=null,xe=_t({},["audio","video","img","source","image","track"]),De=null,rt=_t({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ze="http://www.w3.org/1998/Math/MathML",je="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml",Rt=at,tr=!1,cr=null,Y=_t({},[ze,je,at],Ld),vt=_t({},["mi","mo","mn","ms","mtext"]),ut=_t({},["annotation-xml"]),Te=_t({},["title","style","font","a","script"]),ue=null,pt=["application/xhtml+xml","text/html"],hr="text/html",xt=null,vr=null,Dr=r.createElement("form"),yt=function(I){return I instanceof RegExp||I instanceof Function},Dt=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(vr&&vr===I)){if((!I||typeof I!="object")&&(I={}),I=ao(I),ue=pt.indexOf(I.PARSER_MEDIA_TYPE)===-1?hr:I.PARSER_MEDIA_TYPE,xt=ue==="application/xhtml+xml"?Ld:Fi,Z=An(I,"ALLOWED_TAGS")?_t({},I.ALLOWED_TAGS,xt):ne,ee=An(I,"ALLOWED_ATTR")?_t({},I.ALLOWED_ATTR,xt):we,cr=An(I,"ALLOWED_NAMESPACES")?_t({},I.ALLOWED_NAMESPACES,Ld):Y,De=An(I,"ADD_URI_SAFE_ATTR")?_t(ao(rt),I.ADD_URI_SAFE_ATTR,xt):rt,B=An(I,"ADD_DATA_URI_TAGS")?_t(ao(xe),I.ADD_DATA_URI_TAGS,xt):xe,Be=An(I,"FORBID_CONTENTS")?_t({},I.FORBID_CONTENTS,xt):Xe,X=An(I,"FORBID_TAGS")?_t({},I.FORBID_TAGS,xt):ao({}),fe=An(I,"FORBID_ATTR")?_t({},I.FORBID_ATTR,xt):ao({}),ie=An(I,"USE_PROFILES")?I.USE_PROFILES:!1,me=I.ALLOW_ARIA_ATTR!==!1,te=I.ALLOW_DATA_ATTR!==!1,le=I.ALLOW_UNKNOWN_PROTOCOLS||!1,ht=I.ALLOW_SELF_CLOSE_IN_ATTR!==!1,mt=I.SAFE_FOR_TEMPLATES||!1,Re=I.SAFE_FOR_XML!==!1,ye=I.WHOLE_DOCUMENT||!1,G=I.RETURN_DOM||!1,he=I.RETURN_DOM_FRAGMENT||!1,K=I.RETURN_TRUSTED_TYPE||!1,He=I.FORCE_BODY||!1,wt=I.SANITIZE_DOM!==!1,U=I.SANITIZE_NAMED_PROPS||!1,qe=I.KEEP_CONTENT!==!1,se=I.IN_PLACE||!1,We=I.ALLOWED_URI_REGEXP||Hh,Rt=I.NAMESPACE||at,vt=I.MATHML_TEXT_INTEGRATION_POINTS||vt,ut=I.HTML_INTEGRATION_POINTS||ut,Q=I.CUSTOM_ELEMENT_HANDLING||{},I.CUSTOM_ELEMENT_HANDLING&&yt(I.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Q.tagNameCheck=I.CUSTOM_ELEMENT_HANDLING.tagNameCheck),I.CUSTOM_ELEMENT_HANDLING&&yt(I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Q.attributeNameCheck=I.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),I.CUSTOM_ELEMENT_HANDLING&&typeof I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Q.allowCustomizedBuiltInElements=I.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),mt&&(te=!1),he&&(G=!0),ie&&(Z=_t({},Eh),ee=_i(null),ie.html===!0&&(_t(Z,kh),_t(ee,Lh)),ie.svg===!0&&(_t(Z,Id),_t(ee,Hd),_t(ee,Ni)),ie.svgFilters===!0&&(_t(Z,Rd),_t(ee,Hd),_t(ee,Ni)),ie.mathMl===!0&&(_t(Z,Wd),_t(ee,Ph),_t(ee,Ni))),An(I,"ADD_TAGS")||(Le.tagCheck=null),An(I,"ADD_ATTR")||(Le.attributeCheck=null),I.ADD_TAGS&&(typeof I.ADD_TAGS=="function"?Le.tagCheck=I.ADD_TAGS:(Z===ne&&(Z=ao(Z)),_t(Z,I.ADD_TAGS,xt))),I.ADD_ATTR&&(typeof I.ADD_ATTR=="function"?Le.attributeCheck=I.ADD_ATTR:(ee===we&&(ee=ao(ee)),_t(ee,I.ADD_ATTR,xt))),I.ADD_URI_SAFE_ATTR&&_t(De,I.ADD_URI_SAFE_ATTR,xt),I.FORBID_CONTENTS&&(Be===Xe&&(Be=ao(Be)),_t(Be,I.FORBID_CONTENTS,xt)),I.ADD_FORBID_CONTENTS&&(Be===Xe&&(Be=ao(Be)),_t(Be,I.ADD_FORBID_CONTENTS,xt)),qe&&(Z["#text"]=!0),ye&&_t(Z,["html","head","body"]),Z.table&&(_t(Z,["tbody"]),delete X.tbody),I.TRUSTED_TYPES_POLICY){if(typeof I.TRUSTED_TYPES_POLICY.createHTML!="function")throw $s('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof I.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw $s('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');h=I.TRUSTED_TYPES_POLICY,C=h.createHTML("")}else h===void 0&&(h=D0(m,o)),h!==null&&typeof C=="string"&&(C=h.createHTML(""));nn&&nn(I),vr=I}},it=_t({},[...Id,...Rd,...T0]),Xt=_t({},[...Wd,...M0]),Cr=function(I){let pe=M(I);(!pe||!pe.tagName)&&(pe={namespaceURI:Rt,tagName:"template"});let Oe=Fi(I.tagName),zt=Fi(pe.tagName);return cr[I.namespaceURI]?I.namespaceURI===je?pe.namespaceURI===at?Oe==="svg":pe.namespaceURI===ze?Oe==="svg"&&(zt==="annotation-xml"||vt[zt]):!!it[Oe]:I.namespaceURI===ze?pe.namespaceURI===at?Oe==="math":pe.namespaceURI===je?Oe==="math"&&ut[zt]:!!Xt[Oe]:I.namespaceURI===at?pe.namespaceURI===je&&!ut[zt]||pe.namespaceURI===ze&&!vt[zt]?!1:!Xt[Oe]&&(Te[Oe]||!it[Oe]):!!(ue==="application/xhtml+xml"&&cr[I.namespaceURI]):!1},pr=function(I){_s(e.removed,{element:I});try{M(I).removeChild(I)}catch{S(I)}},xr=function(I,pe){try{_s(e.removed,{attribute:pe.getAttributeNode(I),from:pe})}catch{_s(e.removed,{attribute:null,from:pe})}if(pe.removeAttribute(I),I==="is")if(G||he)try{pr(pe)}catch{}else try{pe.setAttribute(I,"")}catch{}},Er=function(I){let pe=null,Oe=null;if(He)I="<remove></remove>"+I;else{let Vt=Pd(I,/^[\r\n\t ]+/);Oe=Vt&&Vt[0]}ue==="application/xhtml+xml"&&Rt===at&&(I='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+I+"</body></html>");let zt=h?h.createHTML(I):I;if(Rt===at)try{pe=new f().parseFromString(zt,ue)}catch{}if(!pe||!pe.documentElement){pe=v.createDocument(Rt,"template",null);try{pe.documentElement.innerHTML=tr?C:zt}catch{}}let st=pe.body||pe.documentElement;return I&&Oe&&st.insertBefore(r.createTextNode(Oe),st.childNodes[0]||null),Rt===at?P.call(pe,ye?"html":"body")[0]:ye?pe.documentElement:st},fn=function(I){return T.call(I.ownerDocument||I,I,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Wt=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")},zr=function(I){return typeof i=="function"&&I instanceof i};function wr(Ge,I,pe){Oi(Ge,Oe=>{Oe.call(e,I,pe,vr)})}let kn=function(I){let pe=null;if(wr(N.beforeSanitizeElements,I,null),Wt(I))return pr(I),!0;let Oe=xt(I.nodeName);if(wr(N.uponSanitizeElement,I,{tagName:Oe,allowedTags:Z}),Re&&I.hasChildNodes()&&!zr(I.firstElementChild)&&rn(/<[/\w!]/g,I.innerHTML)&&rn(/<[/\w!]/g,I.textContent)||I.nodeType===qs.progressingInstruction||Re&&I.nodeType===qs.comment&&rn(/<[/\w]/g,I.data))return pr(I),!0;if(!(Le.tagCheck instanceof Function&&Le.tagCheck(Oe))&&(!Z[Oe]||X[Oe])){if(!X[Oe]&&Lt(Oe)&&(Q.tagNameCheck instanceof RegExp&&rn(Q.tagNameCheck,Oe)||Q.tagNameCheck instanceof Function&&Q.tagNameCheck(Oe)))return!1;if(qe&&!Be[Oe]){let zt=M(I)||I.parentNode,st=E(I)||I.childNodes;if(st&&zt){let Vt=st.length;for(let or=Vt-1;or>=0;--or){let fr=x(st[or],!0);fr.__removalCount=(I.__removalCount||0)+1,zt.insertBefore(fr,k(I))}}}return pr(I),!0}return I instanceof d&&!Cr(I)||(Oe==="noscript"||Oe==="noembed"||Oe==="noframes")&&rn(/<\/no(script|embed|frames)/i,I.innerHTML)?(pr(I),!0):(mt&&I.nodeType===qs.text&&(pe=I.textContent,Oi([j,ce,be],zt=>{pe=Fs(pe,zt," ")}),I.textContent!==pe&&(_s(e.removed,{element:I.cloneNode()}),I.textContent=pe)),wr(N.afterSanitizeElements,I,null),!1)},ln=function(I,pe,Oe){if(fe[pe]||wt&&(pe==="id"||pe==="name")&&(Oe in r||Oe in Dr))return!1;if(!(te&&!fe[pe]&&rn(Ze,pe))){if(!(me&&rn(Se,pe))){if(!(Le.attributeCheck instanceof Function&&Le.attributeCheck(pe,I))){if(!ee[pe]||fe[pe]){if(!(Lt(I)&&(Q.tagNameCheck instanceof RegExp&&rn(Q.tagNameCheck,I)||Q.tagNameCheck instanceof Function&&Q.tagNameCheck(I))&&(Q.attributeNameCheck instanceof RegExp&&rn(Q.attributeNameCheck,pe)||Q.attributeNameCheck instanceof Function&&Q.attributeNameCheck(pe,I))||pe==="is"&&Q.allowCustomizedBuiltInElements&&(Q.tagNameCheck instanceof RegExp&&rn(Q.tagNameCheck,Oe)||Q.tagNameCheck instanceof Function&&Q.tagNameCheck(Oe))))return!1}else if(!De[pe]){if(!rn(We,Fs(Oe,Ce,""))){if(!((pe==="src"||pe==="xlink:href"||pe==="href")&&I!=="script"&&v0(Oe,"data:")===0&&B[I])){if(!(le&&!rn(Ne,Fs(Oe,Ce,"")))){if(Oe)return!1}}}}}}}return!0},Lt=function(I){return I!=="annotation-xml"&&Pd(I,Fe)},Jn=function(I){wr(N.beforeSanitizeAttributes,I,null);let{attributes:pe}=I;if(!pe||Wt(I))return;let Oe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ee,forceKeepAttr:void 0},zt=pe.length;for(;zt--;){let st=pe[zt],{name:Vt,namespaceURI:or,value:fr}=st,Pt=xt(Vt),Vr=fr,Jt=Vt==="value"?Vr:C0(Vr);if(Oe.attrName=Pt,Oe.attrValue=Jt,Oe.keepAttr=!0,Oe.forceKeepAttr=void 0,wr(N.uponSanitizeAttribute,I,Oe),Jt=Oe.attrValue,U&&(Pt==="id"||Pt==="name")&&(xr(Vt,I),Jt=J+Jt),Re&&rn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Jt)){xr(Vt,I);continue}if(Pt==="attributename"&&Pd(Jt,"href")){xr(Vt,I);continue}if(Oe.forceKeepAttr)continue;if(!Oe.keepAttr){xr(Vt,I);continue}if(!ht&&rn(/\/>/i,Jt)){xr(Vt,I);continue}mt&&Oi([j,ce,be],$n=>{Jt=Fs(Jt,$n," ")});let jr=xt(I.nodeName);if(!ln(jr,Pt,Jt)){xr(Vt,I);continue}if(h&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!or)switch(m.getAttributeType(jr,Pt)){case"TrustedHTML":{Jt=h.createHTML(Jt);break}case"TrustedScriptURL":{Jt=h.createScriptURL(Jt);break}}if(Jt!==Vr)try{or?I.setAttributeNS(or,Vt,Jt):I.setAttribute(Vt,Jt),Wt(I)?pr(I):Mh(e.removed)}catch{xr(Vt,I)}}wr(N.afterSanitizeAttributes,I,null)},En=function Ge(I){let pe=null,Oe=fn(I);for(wr(N.beforeSanitizeShadowDOM,I,null);pe=Oe.nextNode();)wr(N.uponSanitizeShadowNode,pe,null),kn(pe),Jn(pe),pe.content instanceof s&&Ge(pe.content);wr(N.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(Ge){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},pe=null,Oe=null,zt=null,st=null;if(tr=!Ge,tr&&(Ge="<!-->"),typeof Ge!="string"&&!zr(Ge))if(typeof Ge.toString=="function"){if(Ge=Ge.toString(),typeof Ge!="string")throw $s("dirty is not a string, aborting")}else throw $s("toString is not a function");if(!e.isSupported)return Ge;if(ot||Dt(I),e.removed=[],typeof Ge=="string"&&(se=!1),se){if(Ge.nodeName){let fr=xt(Ge.nodeName);if(!Z[fr]||X[fr])throw $s("root node is forbidden and cannot be sanitized in-place")}}else if(Ge instanceof i)pe=Er("<!---->"),Oe=pe.ownerDocument.importNode(Ge,!0),Oe.nodeType===qs.element&&Oe.nodeName==="BODY"||Oe.nodeName==="HTML"?pe=Oe:pe.appendChild(Oe);else{if(!G&&!mt&&!ye&&Ge.indexOf("<")===-1)return h&&K?h.createHTML(Ge):Ge;if(pe=Er(Ge),!pe)return G?null:K?C:""}pe&&He&&pr(pe.firstChild);let Vt=fn(se?Ge:pe);for(;zt=Vt.nextNode();)kn(zt),Jn(zt),zt.content instanceof s&&En(zt.content);if(se)return Ge;if(G){if(he)for(st=W.call(pe.ownerDocument);pe.firstChild;)st.appendChild(pe.firstChild);else st=pe;return(ee.shadowroot||ee.shadowrootmode)&&(st=R.call(n,st,!0)),st}let or=ye?pe.outerHTML:pe.innerHTML;return ye&&Z["!doctype"]&&pe.ownerDocument&&pe.ownerDocument.doctype&&pe.ownerDocument.doctype.name&&rn(Bh,pe.ownerDocument.doctype.name)&&(or="<!DOCTYPE "+pe.ownerDocument.doctype.name+`>
51
+ `+or),mt&&Oi([j,ce,be],fr=>{or=Fs(or,fr," ")}),h&&K?h.createHTML(or):or},e.setConfig=function(){let Ge=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Dt(Ge),ot=!0},e.clearConfig=function(){vr=null,ot=!1},e.isValidAttribute=function(Ge,I,pe){vr||Dt({});let Oe=xt(Ge),zt=xt(I);return ln(Oe,zt,pe)},e.addHook=function(Ge,I){typeof I=="function"&&_s(N[Ge],I)},e.removeHook=function(Ge,I){if(I!==void 0){let pe=b0(N[Ge],I);return pe===-1?void 0:w0(N[Ge],pe,1)[0]}return Mh(N[Ge])},e.removeHooks=function(Ge){N[Ge]=[]},e.removeAllHooks=function(){N=Rh()},e}var Oh=Dh();var O0={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"]},N0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Od=()=>{let t=Oh(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:")&&!N0.test(n)&&(r.attrValue="",r.keepAttr=!1)}}),e=>t.sanitize(e,O0)},qa=t=>t===!1?null:typeof t=="function"?t:Od();var Co="webmcp:",Vd=new Map,nx=t=>{var e;Vd.clear();for(let r of t){let n=(e=r.title)==null?void 0:e.trim();n&&Vd.set(r.name,n)}},jd=t=>Vd.get(Xi(t)),Ki={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}};function ax(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}:${Ow(e.join(""))}`}function ox(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 Ow(t){let e=ox(t,0).toString(36),r=ox(t,2654435761).toString(36);return`${e}.${r}`}var ja=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 Ki.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}nx(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=_w(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,r,n){if(await this.ensureReady(),this.config.enabled!==!0)return Kn("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let y=typeof document!="undefined"&&!!document.modelContext;return Kn(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=Xi(e),a;try{a=await o.getTools()}catch(y){let x=y instanceof Error?y.message:String(y);return Kn(`Failed to read WebMCP registry: ${x}`)}nx(a);let i=a.find(y=>y.name===s);if(!i)return Kn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Kn(`WebMCP tool not allowed by client allowlist: ${s}`);if(n!=null&&n.aborted)return Kn("Aborted by cancel()");let d=jd(s),l={toolName:s,args:r,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Kn("User declined the tool call.");if(n!=null&&n.aborted)return Kn("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,qw(r),{signal:p.signal});return Fw(y)}catch(y){if(u)return Kn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return Kn("Aborted by cancel()");let x=y instanceof Error?y.message:String(y);return Kn(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(()=>(rx(),tx))).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Ki.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,Ki.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:$w;try{return await r(e)}catch(o){return Ki.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=>Nw(e,n))}},Xi=t=>t.startsWith(Co)?t.slice(Co.length):t,qo=t=>t.startsWith(Co),Nw=(t,e)=>{if(e==="*")return!0;let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(t)},_w=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Fw=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:zw(e)}]}},Kn=t=>({isError:!0,content:[{type:"text",text:t}]}),$w=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Uw(t.args),r=`Allow the AI to call ${t.toolName}`+(e?`
52
52
 
53
53
  Arguments:
54
54
  ${e}`:"")+(t.description?`
55
55
 
56
- ${t.description}`:"");return window.confirm(r)},tw=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},rw=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},nw=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var fo=ad(qi(),1),zi=t=>t.replace(/\\n/g,`
57
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ra=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},lw=t=>{var a,i;let e=(a=t.completedAt)!=null?a:Date.now(),r=(i=t.startedAt)!=null?i:e,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Rh=t=>t.status==="complete"?lw(t):t.status==="pending"?"Waiting":"",dw=t=>{var o,s,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Wh=t=>t.status==="complete"?dw(t):"Using tool...",Vi=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Is=t=>{var r,n,o;let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((r=t.completedAt)!=null?r:Date.now())-((o=(n=t.startedAt)!=null?n:t.completedAt)!=null?o:Date.now()));return Vi(e)},ji=t=>{var r,n,o;let e=t.durationMs!==void 0?t.durationMs:Math.max(0,((r=t.completedAt)!=null?r:Date.now())-((o=(n=t.startedAt)!=null?n:t.completedAt)!=null?o:Date.now()));return Vi(e)},Wd=(t,e,r)=>{var s;if(!e)return r;let n=((s=t.name)==null?void 0:s.trim())||"tool",o=Is(t);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Gi=(t,e)=>{let r=t.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(r))!==null;)a.index>s&&Ps(n,r.slice(s,a.index),[]),a[1]!==void 0?Ps(n,a[1],["bold"]):a[2]!==void 0?Ps(n,a[2],["italic"]):a[3]!==void 0&&Ps(n,a[3],["dim"]),s=a.index+a[0].length;return s<r.length&&Ps(n,r.slice(s),[]),n},Ps=(t,e,r)=>{let n=e.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&t.push({text:n[o],styles:r}),o<n.length-1&&t.push({text:"{duration}",styles:r,isDuration:!0})},cw=()=>{let t=null,e=0,r=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=n.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
56
+ ${t.description}`:"");return window.confirm(r)},Uw=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)}},qw=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},zw=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var Ao=bd(Yi(),1),Zi=t=>t.replace(/\\n/g,`
57
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ga=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`},ix=t=>t.status==="complete"?Xw(t):t.status==="pending"?"Waiting":"",Jw=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 lx=t=>t.status==="complete"?Jw(t):"Using tool...",el=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Vs=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 el(e)},tl=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 el(e)},Kd=(t,e,r)=>{var s;if(!e)return r;let n=((s=t.name)==null?void 0:s.trim())||"tool",o=Vs(t);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},rl=(t,e)=>{let r=t.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(r))!==null;)a.index>s&&zs(n,r.slice(s,a.index),[]),a[1]!==void 0?zs(n,a[1],["bold"]):a[2]!==void 0?zs(n,a[2],["italic"]):a[3]!==void 0&&zs(n,a[3],["dim"]),s=a.index+a[0].length;return s<r.length&&zs(n,r.slice(s),[]),n},zs=(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})},Qw=()=>{let t=null,e=0,r=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=n.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
58
58
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
59
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async n=>{if(n.length<=e)return t!==null?{text:t,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(n);return s!==null&&(t=s),e=n.length,t!==null?{text:t,raw:n}:null},close:async()=>{}}},aa=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Ki=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Xi=()=>{var e;let t=cw();return{processChunk:async r=>{let n=r.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},Ji=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,fo.parse)(r,fo.STR|fo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?zi(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=zi(o.text)))}catch{}return e=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Bh=t=>{let e=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?zi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let i=(0,fo.parse)(s,fo.STR|fo.OBJ),d=o(i);d!==null&&(e=d)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Qi=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let n=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(t=n[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Yi=class{constructor(e,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=r}push(e,r){var s,a,i;let n=(i=(s=r==null?void 0:r.seq)!=null?s:r==null?void 0:r.sequenceIndex)!=null?i:(a=r==null?void 0:r.agentContext)==null?void 0:a.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(e,r),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(e,r);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:e,payload:r,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((r,n)=>r[0]-n[0]);for(let[r,n]of e)this.buffer.delete(r),this.emitter(n.payloadType,n.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var pw="https://api.runtype.com/v1/dispatch",Zi="https://api.runtype.com";function uw(t){var s,a;let e=t.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(n)return`attachment.${n}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Bd=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function fw(t){switch(t){case"json":return Ji;case"regex-json":return Xi;case"xml":return Qi;default:return Ki}}var Hh=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function mw(t,e){if(!t)return e;let r=t.trim(),n=e.trim();if(r.length===0)return e;if(n.length===0)return t;let o=Hh(r);if(!Hh(n))return t;if(!o||n===r||n.startsWith(r))return e;let a=aa(t);return aa(e)!==null&&a===null?e:t}var sa=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,n,o,s;this.apiUrl=(r=e.apiUrl)!=null?r:pw,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:fw(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Ia(e.webmcp):null}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,r,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,r,n):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Zi}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,this.resetClientToolsFingerprint(),(r=(e=this.config).onSessionInit)==null||r.call(e,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Zi}/v1/client/feedback`}async sendFeedback(e){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:r})}async submitCSATFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:e,comment:r})}async submitNPSFeedback(e,r){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:e,comment:r})}async dispatch(e,r){return this.isAgentMode()?this.dispatchAgent(e,r):this.isClientTokenMode()?this.dispatchClientToken(e,r):this.dispatchProxy(e,r)}async dispatchClientToken(e,r){var o,s,a,i;let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}let l=await this.buildPayload(e.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Bd).map(h=>{var w,y,E;return{id:h.id,role:h.role,content:(E=(y=(w=h.contentParts)!=null?w:h.llmContent)!=null?y:h.rawContent)!=null?E:h.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,f=!!(u&&u.length>0),x=f?Ph(u):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,S=f&&C&&this.lastSentClientToolsFingerprint===x,k=!1,T=null,M;for(let h=0;;h++){let y={...m,...f&&(k||!S)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",y),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y),signal:n.signal}),M.status===409&&h===0&&f){let E=await M.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){k=!0,this.lastSentClientToolsFingerprint=null;continue}T=E!=null?E:{error:"Chat request failed"}}break}if(!M.ok){let h=T!=null?T:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(M.status===429){let y=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let w=new Error(h.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!M.body){let h=new Error("No response body received");throw r({type:"error",error:h}),h}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(M.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(e,r,n){r({type:"status",status:"connected"});try{await this.streamResponse(e,r,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(e,r){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Zi}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(e,r,n){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Zi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:r,streamResponse:(p=n==null?void 0:n.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(e){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Bd).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),n={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}return n}async buildPayload(e){var s;let n={messages:e.slice().filter(Bd).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(n.clientTools=o),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:e,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(n.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...n},config:this.config});if(a&&typeof a=="object"){let i=a;return n.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=n.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return n}async handleCustomSSEEvent(e,r,n,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return n.current=m,o(m),m},l=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),a.current=null,r({type:"status",status:"idle"})),i.error&&(a.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r,n){var fe,pe,Be,Q;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,He=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,Ve=_.tools?_.tools.map(Je=>({...Je,chunks:Je.chunks?[...Je.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:He,tools:Ve}},m=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,He=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||He||!!_.stopReason},u=_=>{m(_)&&r({type:"message",message:p(_)})},f=null,x=null,C={current:null},S={current:null},k=!1,T=new Map,M=new Map,h=new Map,w=new Map,y={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},B=(_,ke,He="")=>`${_}::${ke}::${He}`,P=(_,ke)=>`${_}::${ke}::`,R=(_,ke,He,Ve)=>{let Je=B(_,ke,He),gt=h.get(Je);if(gt)return gt;let at=He?`-${He}`:"",Mt={id:`nested-${_}-${ke}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Ve,parentToolId:_,parentStepId:ke}};return h.set(Je,Mt),u(Mt),Mt},O=_=>{if(_==null)return null;try{return String(_)}catch{return null}},V=_=>{var ke,He,Ve,Je,gt;return O((gt=(Je=(Ve=(He=(ke=_.stepId)!=null?ke:_.step_id)!=null?He:_.step)!=null?Ve:_.parentId)!=null?Je:_.flowStepId)!=null?gt:_.flow_step_id)},ne=_=>{var ke,He,Ve,Je,gt,at,Mt;return O((Mt=(at=(gt=(Je=(Ve=(He=(ke=_.callId)!=null?ke:_.call_id)!=null?He:_.requestId)!=null?Ve:_.request_id)!=null?Je:_.toolCallId)!=null?gt:_.tool_call_id)!=null?at:_.stepId)!=null?Mt:_.step_id)},be=n,Ye=!1,Ge=()=>{if(f)return f;let _;return!Ye&&be?(_=be,Ye=!0):be&&S.current?_=`${be}_${S.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(f),f},ve=(_,ke)=>{y.lastId=ke,_&&y.byStep.set(_,ke)},Ee=(_,ke)=>{var gt;let He=(gt=_.reasoningId)!=null?gt:_.id,Ve=V(_);if(He){let at=String(He);return ve(Ve,at),at}if(Ve){let at=y.byStep.get(Ve);if(at)return y.lastId=at,at}if(y.lastId&&!ke)return y.lastId;if(!ke)return null;let Je=`reason-${l()}`;return ve(Ve,Je),Je},Ke=_=>{let ke=T.get(_);if(ke)return ke;let He={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return T.set(_,He),u(He),He},Ne=(_,ke)=>{E.lastId=ke,_&&E.byCall.set(_,ke)},X=new Set,Ue=new Map,K=new Set,Te=new Map,oe=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},xe=(_,ke)=>{var gt;let He=(gt=_.toolId)!=null?gt:_.id,Ve=ne(_);if(He){let at=String(He);return Ne(Ve,at),at}if(Ve){let at=E.byCall.get(Ve);if(at)return E.lastId=at,at}if(E.lastId&&!ke)return E.lastId;if(!ke)return null;let Je=`tool-${l()}`;return Ne(Ve,Je),Je},Me=_=>{let ke=M.get(_);if(ke)return ke;let He={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return M.set(_,He),u(He),He},Xe=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let He=Date.parse(_);if(!Number.isNaN(He))return He}return Date.now()},ce=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},te=new Map,le=new Map,ut=new Map,Ce=new Map,he=null,rt=(_,ke,He)=>{var Mt;let Ve=ut.get(_);Ve||(Ve=[],ut.set(_,Ve));let Je=0,gt=Ve.length;for(;Je<gt;){let Xt=Je+gt>>>1;Ve[Xt].seq<ke?Je=Xt+1:gt=Xt}((Mt=Ve[Je])==null?void 0:Mt.seq)===ke?Ve[Je]={seq:ke,text:He}:Ve.splice(Je,0,{seq:ke,text:He});let at="";for(let Xt=0;Xt<Ve.length;Xt++)at+=Ve[Xt].text;return at},_e=(_,ke)=>{let He=ce(ke),Ve=le.get(_.id),Je=mw(Ve,He);_.rawContent=Je;let gt=te.get(_.id),at=st=>{var de;let _t=(de=_.content)!=null?de:"";st.trim()!==""&&(_t.trim().length===0||st.startsWith(_t)||st.trimStart().startsWith(_t.trim()))&&(_.content=st)},Mt=()=>{var st;if(gt){let _t=(st=gt.close)==null?void 0:st.call(gt);_t instanceof Promise&&_t.catch(()=>{})}te.delete(_.id),le.delete(_.id),_.streaming=!1,u(_)};if(!gt){at(He),Mt();return}let Xt=aa(Je);if(Xt!==null&&Xt.trim()!==""){at(Xt),Mt();return}let G=st=>{var ye;let _t=typeof st=="string"?st:(ye=st==null?void 0:st.text)!=null?ye:null;if(_t!==null&&_t.trim()!=="")return _t;let de=gt.getExtractedText();return de!==null&&de.trim()!==""?de:He},Jt;try{Jt=gt.processChunk(Je)}catch{at(He),Mt();return}if(Jt instanceof Promise){Jt.then(st=>{at(G(st)),Mt()}).catch(()=>{at(He),Mt()});return}at(G(Jt)),Mt()},me=[],J=!1,ze,Z=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ze()}))},ge=new Yi((_,ke)=>{me.push({payloadType:_,payload:ke}),Z()}),z=null,Re=new Map,Ae=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(ze=()=>{var _,ke,He,Ve,Je,gt,at,Mt,Xt,G,Jt,st,_t,de,ye,Rt,ar,kt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,I,ee,Se,nt,Qt,Ft,tr,Pr,Nr,wn,Vt,$t,Ir,vn,bo,eo,wo,qn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn,W,pn,Bn,to,zn,Ja,Hn,Dn,On,ro,$o,ni,Qa,oi,xa,Lt,Ya,An,tn,ai,si,ya,no,ii,Uo,Za,oo,es,Co,Ao,li,di,nd,qo,So,ci,ts,To,pi,rs,Mo,ns,ui,ao,fi,ko,Kt,ba,wa,os,Vn,mi,as,ss,gi,va,Ca,zo,hi,xi,is,ls,ds,cs,zr,un,so,yt,ps,Vo,Nn,yi;for(let Eo=0;Eo<me.length;Eo++){let it=me[Eo].payloadType,L=me[Eo].payload;if(it==="reason_start"){let q=(_=Ee(L,!0))!=null?_:`reason-${l()}`,N=Ke(q);N.reasoning=(ke=N.reasoning)!=null?ke:{id:q,status:"streaming",chunks:[]},N.reasoning.startedAt=(Ve=N.reasoning.startedAt)!=null?Ve:Xe((He=L.startedAt)!=null?He:L.timestamp),N.reasoning.completedAt=void 0,N.reasoning.durationMs=void 0,N.streaming=!0,N.reasoning.status="streaming",u(N)}else if(it==="reason_delta"||it==="reason_chunk"){let q=(gt=(Je=Ee(L,!1))!=null?Je:Ee(L,!0))!=null?gt:`reason-${l()}`,N=Ke(q);N.reasoning=(at=N.reasoning)!=null?at:{id:q,status:"streaming",chunks:[]},N.reasoning.startedAt=(Xt=N.reasoning.startedAt)!=null?Xt:Xe((Mt=L.startedAt)!=null?Mt:L.timestamp);let ae=(st=(Jt=(G=L.reasoningText)!=null?G:L.text)!=null?Jt:L.delta)!=null?st:"";if(ae&&L.hidden!==!0){let ie=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(ie!==void 0){let Y=rt(q,ie,String(ae));N.reasoning.chunks=[Y]}else N.reasoning.chunks.push(String(ae))}if(N.reasoning.status=L.done?"complete":"streaming",L.done){N.reasoning.completedAt=Xe((_t=L.completedAt)!=null?_t:L.timestamp);let ie=(de=N.reasoning.startedAt)!=null?de:Date.now();N.reasoning.durationMs=Math.max(0,((ye=N.reasoning.completedAt)!=null?ye:Date.now())-ie)}N.streaming=N.reasoning.status!=="complete",u(N)}else if(it==="reason_complete"){let q=(ar=(Rt=Ee(L,!1))!=null?Rt:Ee(L,!0))!=null?ar:`reason-${l()}`,N=T.get(q);if(N!=null&&N.reasoning){N.reasoning.status="complete",N.reasoning.completedAt=Xe((kt=L.completedAt)!=null?kt:L.timestamp);let ie=(mr=N.reasoning.startedAt)!=null?mr:Date.now();N.reasoning.durationMs=Math.max(0,((Ot=N.reasoning.completedAt)!=null?Ot:Date.now())-ie),N.streaming=!1,u(N)}let ae=V(L);ae&&y.byStep.delete(ae)}else if(it==="tool_start"){let q=(Wt=xe(L,!0))!=null?Wt:`tool-${l()}`,N=(St=L.toolName)!=null?St:L.name;if(oe(N)){X.add(q);continue}let ae=Me(q),ie=(Et=ae.toolCall)!=null?Et:{id:q,status:"pending"};ie.name=N!=null?N:ie.name,ie.status="running",L.args!==void 0?ie.args=L.args:L.parameters!==void 0&&(ie.args=L.parameters),ie.startedAt=(ft=ie.startedAt)!=null?ft:Xe((sr=L.startedAt)!=null?sr:L.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,ae.toolCall=ie,ae.streaming=!0;let Y=L.agentContext;(Y||L.executionId)&&(ae.agentMetadata={executionId:(dr=Y==null?void 0:Y.executionId)!=null?dr:L.executionId,iteration:(wr=Y==null?void 0:Y.iteration)!=null?wr:L.iteration}),u(ae)}else if(it==="tool_chunk"||it==="tool_delta"){let q=(Or=(Lr=xe(L,!1))!=null?Lr:xe(L,!0))!=null?Or:`tool-${l()}`;if(X.has(q))continue;let N=Me(q),ae=(xt=N.toolCall)!=null?xt:{id:q,status:"running"};ae.startedAt=(fr=ae.startedAt)!=null?fr:Xe((sn=L.startedAt)!=null?sn:L.timestamp);let ie=(Zn=(Rr=(Un=L.text)!=null?Un:L.delta)!=null?Rr:L.message)!=null?Zn:"";ie&&(ae.chunks=(Pn=ae.chunks)!=null?Pn:[],ae.chunks.push(String(ie))),ae.status="running",N.toolCall=ae,N.streaming=!0;let Y=L.agentContext;(Y||L.executionId)&&(N.agentMetadata=(I=N.agentMetadata)!=null?I:{executionId:(In=Y==null?void 0:Y.executionId)!=null?In:L.executionId,iteration:(ue=Y==null?void 0:Y.iteration)!=null?ue:L.iteration}),u(N)}else if(it==="tool_complete"){let q=(Se=(ee=xe(L,!1))!=null?ee:xe(L,!0))!=null?Se:`tool-${l()}`;if(X.has(q)){X.delete(q);continue}let N=Me(q),ae=(nt=N.toolCall)!=null?nt:{id:q,status:"running"};ae.status="complete",L.result!==void 0&&(ae.result=L.result),typeof L.duration=="number"&&(ae.duration=L.duration),ae.completedAt=Xe((Qt=L.completedAt)!=null?Qt:L.timestamp);let ie=(Ft=L.duration)!=null?Ft:L.executionTime;if(typeof ie=="number")ae.durationMs=ie;else{let tt=(tr=ae.startedAt)!=null?tr:Date.now();ae.durationMs=Math.max(0,((Pr=ae.completedAt)!=null?Pr:Date.now())-tt)}N.toolCall=ae,N.streaming=!1;let Y=L.agentContext;(Y||L.executionId)&&(N.agentMetadata=(Vt=N.agentMetadata)!=null?Vt:{executionId:(Nr=Y==null?void 0:Y.executionId)!=null?Nr:L.executionId,iteration:(wn=Y==null?void 0:Y.iteration)!=null?wn:L.iteration}),u(N);let je=ne(L);je&&E.byCall.delete(je)}else if(it==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let q=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,N=($t=q!=null?q:L.toolId)!=null?$t:`local-${l()}`,ae=Me(N),ie=L.toolName,Y=Io(ie),je=(Ir=ae.toolCall)!=null?Ir:{id:N,status:"pending"};je.name=ie,je.args=L.parameters,je.status=Y?"running":"complete",je.chunks=(vn=je.chunks)!=null?vn:[],je.startedAt=(eo=je.startedAt)!=null?eo:Xe((bo=L.startedAt)!=null?bo:L.timestamp),Y?(je.completedAt=void 0,je.duration=void 0,je.durationMs=void 0):je.completedAt=(wo=je.completedAt)!=null?wo:je.startedAt,ae.toolCall=je,ae.streaming=!1,ae.agentMetadata={...ae.agentMetadata,executionId:(ln=L.executionId)!=null?ln:(qn=ae.agentMetadata)==null?void 0:qn.executionId,awaitingLocalTool:!0,...q?{webMcpToolCallId:q}:{}},u(ae)}else if(it==="text_start"){if((Rn=L.toolContext)!=null&&Rn.toolId)continue;let q=L.partId;if(q!==void 0&&S.current!==null&&q!==S.current){let N=f;N&&(N.streaming=!1,u(N),he=N,f=null,k=!0)}q!==void 0&&(S.current=q)}else if(it==="text_end"){if((Pt=L.toolContext)!=null&&Pt.toolId)continue;let q=f;q&&(q.streaming=!1,u(q),he=q,f=null,k=!0)}else if(it==="step_chunk"||it==="step_delta"){let q=L.stepType,N=L.executionType;if(q==="tool"||N==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let tt=String((hr=(gr=L.id)!=null?gr:ae.stepId)!=null?hr:`step-${l()}`),mt=L.partId!==void 0&&L.partId!==null?String(L.partId):"",Fe=`${ae.toolId}::${tt}`,dt=w.get(Fe);if(mt!==""&&dt!==void 0&&dt!==""&&dt!==mt){let Nt=h.get(B(ae.toolId,tt,dt));Nt&&Nt.streaming!==!1&&(Nt.streaming=!1,u(Nt))}mt!==""&&w.set(Fe,mt);let jt=R(ae.toolId,tt,mt,ae.executionId),Sr=(Wn=(Cn=(vo=(dn=L.text)!=null?dn:L.delta)!=null?vo:L.content)!=null?Cn:L.chunk)!=null?Wn:"";Sr&&(jt.content+=String(Sr),jt.streaming=!0,u(jt)),L.isComplete&&(jt.streaming=!1,u(jt));continue}let ie=L.partId;if(ie!==void 0&&S.current!==null&&ie!==S.current){let tt=f;tt&&(tt.streaming=!1,u(tt),he=tt,f=null,k=!0)}ie!==void 0&&(S.current=ie);let Y=ie!==void 0&&(cn=Ce.get(ie))!=null?cn:Ge();ie!==void 0&&(Y.partId||(Y.partId=ie),Ce.set(ie,Y));let je=(to=(Bn=(pn=(W=L.text)!=null?W:L.delta)!=null?pn:L.content)!=null?Bn:L.chunk)!=null?to:"";if(je){let tt=typeof L.seq=="number"?L.seq:void 0,mt=ie!=null?ie:Y.id,Fe=tt!==void 0?rt(mt,tt,String(je)):((zn=le.get(Y.id))!=null?zn:"")+je;Y.rawContent=Fe,te.has(Y.id)||te.set(Y.id,this.createStreamParser());let dt=te.get(Y.id),jt=Fe.trim().startsWith("{")||Fe.trim().startsWith("[");if(jt&&le.set(Y.id,Fe),dt.__isPlainTextParser===!0){Y.content=tt!==void 0?Fe:Y.content+je,le.delete(Y.id),te.delete(Y.id),Y.rawContent=void 0,u(Y);continue}let Nt=dt.processChunk(Fe);if(Nt instanceof Promise)Nt.then(qt=>{var _r;let Tr=typeof qt=="string"?qt:(_r=qt==null?void 0:qt.text)!=null?_r:null;if(Tr!==null&&Tr.trim()!=="")Y.content=Tr,u(Y);else if(!jt&&!Fe.trim().startsWith("<")){let Vr=f,xr=Vr&&Vr.id===Y.id?Vr:Y;xr.id===Y.id&&(xr.content=tt!==void 0?Fe:xr.content+je,le.delete(xr.id),te.delete(xr.id),xr.rawContent=void 0,u(xr))}}).catch(()=>{Y.content=tt!==void 0?Fe:Y.content+je,le.delete(Y.id),te.delete(Y.id),Y.rawContent=void 0,u(Y)});else{let qt=typeof Nt=="string"?Nt:(Ja=Nt==null?void 0:Nt.text)!=null?Ja:null;qt!==null&&qt.trim()!==""?(Y.content=qt,u(Y)):!jt&&!Fe.trim().startsWith("<")&&(Y.content=tt!==void 0?Fe:Y.content+je,le.delete(Y.id),te.delete(Y.id),Y.rawContent=void 0,u(Y))}}if(L.isComplete){let tt=(Dn=(Hn=L.result)==null?void 0:Hn.response)!=null?Dn:Y.content;if(tt){let mt=le.get(Y.id),Fe=mt!=null?mt:ce(tt);Y.rawContent=Fe;let dt=te.get(Y.id),jt=null,Sr=!1;if(dt&&(jt=dt.getExtractedText(),jt===null&&(jt=aa(Fe)),jt===null)){let Nt=dt.processChunk(Fe);Nt instanceof Promise?(Sr=!0,Nt.then(qt=>{var _r;let Tr=typeof qt=="string"?qt:(_r=qt==null?void 0:qt.text)!=null?_r:null;if(Tr!==null){let Vr=f;Vr&&Vr.id===Y.id&&(Vr.content=Tr,Vr.streaming=!1,te.delete(Vr.id),le.delete(Vr.id),u(Vr))}})):jt=typeof Nt=="string"?Nt:(On=Nt==null?void 0:Nt.text)!=null?On:null}if(!Sr){jt!==null&&jt.trim()!==""?Y.content=jt:le.has(Y.id)||(Y.content=ce(tt));let Nt=te.get(Y.id);if(Nt){let qt=(ro=Nt.close)==null?void 0:ro.call(Nt);qt instanceof Promise&&qt.catch(()=>{}),te.delete(Y.id)}le.delete(Y.id),Y.streaming=!1,u(Y)}}}}else if(it==="step_complete"){let q=L.stepType,N=L.executionType;if(q==="tool"||N==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let tt=String((ni=($o=L.id)!=null?$o:ae.stepId)!=null?ni:"");if(tt){let mt=P(ae.toolId,tt);for(let[Fe,dt]of h)Fe.startsWith(mt)&&dt.streaming!==!1&&(dt.streaming=!1,u(dt));w.delete(`${ae.toolId}::${tt}`)}continue}let ie=L.stopReason;if(k){if(f!==null){let Fe=f;ie&&(Fe.stopReason=ie),te.delete(Fe.id),le.delete(Fe.id),Fe.streaming!==!1&&(Fe.streaming=!1,u(Fe))}let tt=(Qa=L.result)==null?void 0:Qa.response,mt=he;mt&&(ie&&(mt.stopReason=ie),tt!=null?_e(mt,tt):(te.delete(mt.id),le.delete(mt.id))),he=null;continue}let Y=(oi=L.result)==null?void 0:oi.response,je=Ge();if(ie&&(je.stopReason=ie),Y!=null){let tt=te.get(je.id),mt=!1,Fe=!1;if(tt){let dt=tt.getExtractedText(),jt=le.get(je.id),Sr=jt!=null?jt:ce(Y);if(je.rawContent=Sr,dt!==null&&dt.trim()!=="")je.content=dt,mt=!0;else{let Nt=aa(Sr);if(Nt!==null)je.content=Nt,mt=!0;else{let qt=tt.processChunk(Sr);if(qt instanceof Promise)Fe=!0,qt.then(Tr=>{var Vr;let _r=typeof Tr=="string"?Tr:(Vr=Tr==null?void 0:Tr.text)!=null?Vr:null;if(_r!==null&&_r.trim()!==""){let xr=f;xr&&xr.id===je.id&&(xr.content=_r,xr.streaming=!1,te.delete(xr.id),le.delete(xr.id),u(xr))}else{let xr=tt.getExtractedText(),Sn=f;Sn&&Sn.id===je.id&&(xr!==null&&xr.trim()!==""?Sn.content=xr:le.has(Sn.id)||(Sn.content=ce(Y)),Sn.streaming=!1,te.delete(Sn.id),le.delete(Sn.id),u(Sn))}});else{let Tr=typeof qt=="string"?qt:(xa=qt==null?void 0:qt.text)!=null?xa:null;if(Tr!==null&&Tr.trim()!=="")je.content=Tr,mt=!0;else{let _r=tt.getExtractedText();_r!==null&&_r.trim()!==""&&(je.content=_r,mt=!0)}}}}}if(!Fe){if(!je.rawContent){let dt=le.get(je.id);je.rawContent=dt!=null?dt:ce(Y)}if(!mt&&!le.has(je.id)&&(je.content=ce(Y)),tt){let dt=(Lt=tt.close)==null?void 0:Lt.call(tt);dt instanceof Promise&&dt.catch(()=>{})}te.delete(je.id),le.delete(je.id),je.streaming=!1,u(je)}}else te.delete(je.id),le.delete(je.id),je.streaming=!1,u(je)}else if(it==="flow_complete"){let q=(Ya=L.result)==null?void 0:Ya.response;if(k){if(f!==null){let N=f;te.delete(N.id),le.delete(N.id),N.streaming!==!1&&(N.streaming=!1,u(N))}}else if(q!=null){let N=Ge(),ae=le.get(N.id),ie=ae!=null?ae:ce(q);N.rawContent=ie;let Y=ce(q),je=te.get(N.id);if(je){let Fe=aa(ie);if(Fe!==null)Y=Fe;else{let dt=je.processChunk(ie);dt instanceof Promise&&dt.then(Sr=>{var qt;let Nt=typeof Sr=="string"?Sr:(qt=Sr==null?void 0:Sr.text)!=null?qt:null;Nt!==null&&(N.content=Nt,N.streaming=!1,u(N))});let jt=je.getExtractedText();jt!==null&&(Y=jt)}}te.delete(N.id),le.delete(N.id);let tt=Y!==N.content,mt=N.streaming!==!1;tt&&(N.content=Y),N.streaming=!1,(tt||mt)&&u(N)}else if(f!==null){let N=f;te.delete(N.id),le.delete(N.id),N.streaming!==!1&&(N.streaming=!1,u(N))}r({type:"status",status:"idle"})}else if(it==="agent_start")z={executionId:L.executionId,agentId:(An=L.agentId)!=null?An:"virtual",agentName:(tn=L.agentName)!=null?tn:"",status:"running",currentIteration:0,maxTurns:(ai=L.maxTurns)!=null?ai:1,startedAt:Xe(L.startedAt)};else if(it==="agent_iteration_start"){if(z&&(z.currentIteration=L.iteration),Ae==="separate"&&L.iteration>1){let q=f;q&&(q.streaming=!1,u(q),Re.set(L.iteration-1,q),f=null)}}else if(it==="agent_turn_start")x=null;else if(it==="agent_turn_delta"){if(L.contentType==="text"){let q=Ge();q.content+=(si=L.delta)!=null?si:"",q.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:z==null?void 0:z.agentName},x=q,u(q)}else if(L.contentType==="thinking"){let q=(ya=L.turnId)!=null?ya:`agent-think-${L.iteration}`,N=Ke(q);N.reasoning=(no=N.reasoning)!=null?no:{id:q,status:"streaming",chunks:[]},N.reasoning.chunks.push((ii=L.delta)!=null?ii:""),N.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},u(N)}else if(L.contentType==="tool_input"){let q=(Uo=L.toolCallId)!=null?Uo:E.lastId;if(q){let N=M.get(q);N!=null&&N.toolCall&&(N.toolCall.chunks=(Za=N.toolCall.chunks)!=null?Za:[],N.toolCall.chunks.push((oo=L.delta)!=null?oo:""),u(N))}}}else if(it==="agent_turn_complete"){let q=L.turnId;if(q){let ie=T.get(q);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Xe(L.completedAt);let Y=(es=ie.reasoning.startedAt)!=null?es:Date.now();ie.reasoning.durationMs=Math.max(0,((Co=ie.reasoning.completedAt)!=null?Co:Date.now())-Y),ie.streaming=!1,u(ie)}}let N=L.stopReason,ae=f!=null?f:x;if(N&&ae!==null){let ie=L.turnId;(!ie||((Ao=ae.agentMetadata)==null?void 0:Ao.turnId)===ie)&&(ae.stopReason=N,u(ae))}}else if(it==="agent_tool_start"){f&&(f.streaming=!1,u(f),f=null);let q=(li=L.toolCallId)!=null?li:`agent-tool-${l()}`;Ne(ne(L),q);let N=Me(q),ae=(di=N.toolCall)!=null?di:{id:q,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};ae.name=(qo=(nd=L.toolName)!=null?nd:L.name)!=null?qo:ae.name,ae.status="running",L.parameters!==void 0&&(ae.args=L.parameters),ae.startedAt=Xe((So=L.startedAt)!=null?So:L.timestamp),N.toolCall=ae,N.streaming=!0,N.agentMetadata={executionId:L.executionId,iteration:L.iteration},u(N)}else if(it==="agent_tool_delta"){let q=(ci=L.toolCallId)!=null?ci:E.lastId;if(q){let N=(ts=M.get(q))!=null?ts:Me(q);N.toolCall&&(N.toolCall.chunks=(To=N.toolCall.chunks)!=null?To:[],N.toolCall.chunks.push((pi=L.delta)!=null?pi:""),N.toolCall.status="running",N.streaming=!0,u(N))}}else if(it==="agent_tool_complete"){let q=(rs=L.toolCallId)!=null?rs:E.lastId;if(q){let N=(Mo=M.get(q))!=null?Mo:Me(q);if(N.toolCall){N.toolCall.status="complete",L.result!==void 0&&(N.toolCall.result=L.result),typeof L.executionTime=="number"&&(N.toolCall.durationMs=L.executionTime),N.toolCall.completedAt=Xe((ns=L.completedAt)!=null?ns:L.timestamp),N.streaming=!1,u(N);let ae=ne(L);ae&&E.byCall.delete(ae)}}}else if(it==="agent_media"){let q=Array.isArray(L.media)?L.media:[],N=[];for(let ae of q){if(!ae||typeof ae!="object")continue;let ie=ae,Y=typeof ie.type=="string"?ie.type:void 0,je=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",tt=null,mt="";if(Y==="media"){let Fe=typeof ie.data=="string"?ie.data:void 0;if(!Fe)continue;mt=je.length>0?je:"application/octet-stream",tt=`data:${mt};base64,${Fe}`}else if(Y==="image-url"){let Fe=typeof ie.url=="string"?ie.url:void 0;if(!Fe)continue;mt=je,tt=Fe}else if(Y==="file-url"){let Fe=typeof ie.url=="string"?ie.url:void 0;if(!Fe)continue;mt=je,tt=Fe}else continue;if(tt)if(Y==="image-url"||mt.startsWith("image/"))N.push({type:"image",image:tt,...mt?{mimeType:mt}:{}});else if(mt.startsWith("audio/"))N.push({type:"audio",audio:tt,mimeType:mt});else if(mt.startsWith("video/"))N.push({type:"video",video:tt,mimeType:mt});else{let Fe=mt||"application/octet-stream";N.push({type:"file",data:tt,mimeType:Fe,filename:uw(Fe)})}}if(N.length>0){let ae=l(),ie=L.toolCallId,je={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${ae}`:String(ae)}`,role:"assistant",content:"",contentParts:N,createdAt:new Date().toISOString(),streaming:!1,sequence:ae,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(je);let tt=f;tt&&(tt.streaming=!1,u(tt)),f=null,C.current=null}}else if(it!=="agent_iteration_complete"){if(it==="agent_reflection"||it==="agent_reflect"){let q=`agent-reflection-${L.executionId}-${L.iteration}`,N={id:q,role:"assistant",content:(ui=L.reflection)!=null?ui:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:q,status:"complete",chunks:[(ao=L.reflection)!=null?ao:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};u(N)}else if(it==="agent_complete"){z&&(z.status=L.success?"complete":"error",z.completedAt=Xe(L.completedAt),z.stopReason=L.stopReason);let q=f;q&&(q.streaming=!1,u(q)),r({type:"status",status:"idle"})}else if(it==="agent_error"){let q=typeof L.error=="string"?L.error:(ko=(fi=L.error)==null?void 0:fi.message)!=null?ko:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",q):r({type:"error",error:new Error(q)})}else if(it!=="agent_ping"){if(it==="agent_approval_start"){let q=(Kt=L.approvalId)!=null?Kt:`approval-${l()}`,N={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(ba=z==null?void 0:z.agentId)!=null?ba:"virtual",executionId:(os=(wa=L.executionId)!=null?wa:z==null?void 0:z.executionId)!=null?os:"",toolName:(Vn=L.toolName)!=null?Vn:"",toolType:L.toolType,description:(as=L.description)!=null?as:`Execute ${(mi=L.toolName)!=null?mi:"tool"}`,parameters:L.parameters}};u(N)}else if(it==="step_await"&&L.awaitReason==="approval_required"){let q=(ss=L.approvalId)!=null?ss:`approval-${l()}`,N={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(gi=z==null?void 0:z.agentId)!=null?gi:"virtual",executionId:(Ca=(va=L.executionId)!=null?va:z==null?void 0:z.executionId)!=null?Ca:"",toolName:(zo=L.toolName)!=null?zo:"",toolType:L.toolType,description:(xi=L.description)!=null?xi:`Execute ${(hi=L.toolName)!=null?hi:"tool"}`,parameters:L.parameters}};u(N)}else if(it==="agent_approval_complete"){let q=L.approvalId;if(q){let ae={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:(is=L.decision)!=null?is:"approved",agentId:(ls=z==null?void 0:z.agentId)!=null?ls:"virtual",executionId:(cs=(ds=L.executionId)!=null?ds:z==null?void 0:z.executionId)!=null?cs:"",toolName:(zr=L.toolName)!=null?zr:"",description:(un=L.description)!=null?un:"",resolvedAt:Date.now()}};u(ae)}}else if(it==="artifact_start"||it==="artifact_delta"||it==="artifact_update"||it==="artifact_complete"){if(it==="artifact_start"){let q=L.artifactType,N=String(L.id),ae=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:N,artifactType:q,title:ae,component:typeof L.component=="string"?L.component:void 0}),Te.set(N,{markdown:"",title:ae}),!K.has(N)){K.add(N);let ie={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:N,title:ae,artifactType:q,status:"streaming"}})};Ue.set(N,ie),u(ie)}}else if(it==="artifact_delta"){let q=String(L.id),N=typeof L.delta=="string"?L.delta:String((so=L.delta)!=null?so:"");r({type:"artifact_delta",id:q,artDelta:N});let ae=Te.get(q);ae&&(ae.markdown+=N)}else if(it==="artifact_update"){let q=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:q,component:typeof L.component=="string"?L.component:void 0})}else if(it==="artifact_complete"){let q=String(L.id);r({type:"artifact_complete",id:q});let N=Ue.get(q);if(N){N.streaming=!1;try{let ae=JSON.parse((yt=N.rawContent)!=null?yt:"{}");if(ae.props){ae.props.status="complete";let ie=Te.get(q);ie!=null&&ie.markdown&&(ae.props.markdown=ie.markdown)}N.rawContent=JSON.stringify(ae)}catch{}Te.delete(q),u(N),Ue.delete(q)}}}else if(it==="transcript_insert"){let q=L.message;if(!q||typeof q!="object")continue;let N=String((ps=q.id)!=null?ps:`msg-${l()}`),ae=q.role,Y={id:N,role:ae==="user"?"user":ae==="system"?"system":"assistant",content:typeof q.content=="string"?q.content:"",rawContent:typeof q.rawContent=="string"?q.rawContent:void 0,createdAt:typeof q.createdAt=="string"?q.createdAt:new Date().toISOString(),streaming:q.streaming===!0,...typeof q.variant=="string"?{variant:q.variant}:{},sequence:l()};if(u(Y),Y.rawContent)try{let je=JSON.parse(Y.rawContent),tt=(Vo=je==null?void 0:je.props)==null?void 0:Vo.artifactId;typeof tt=="string"&&K.add(tt)}catch{}f=null,C.current=null,te.delete(N),le.delete(N)}else if(it==="error"||it==="step_error"||it==="dispatch_error"||it==="flow_error"){let q=null;if(L.error instanceof Error)q=L.error;else if(it==="dispatch_error"){let N=(Nn=L.message)!=null?Nn:L.error;N!=null&&N!==""&&(q=new Error(String(N)))}else if(it==="step_error"||it==="flow_error"){let N=L.error;typeof N=="string"&&N!==""?q=new Error(N):N!=null&&typeof N=="object"&&"message"in N&&(q=new Error(String((yi=N.message)!=null?yi:N)))}else it==="error"&&L.error!=null&&L.error!==""&&(q=new Error(String(L.error)));if(q){r({type:"error",error:q});let N=f;N&&N.streaming&&(N.streaming=!1,u(N)),r({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:_,value:ke}=await o.read();if(_)break;a+=s.decode(ke,{stream:!0});let He=a.split(`
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()=>{}}},ha=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},nl=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},ol=()=>{var e;let t=Qw();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)}},al=()=>{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,Ao.parse)(r,Ao.STR|Ao.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?Zi(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=Zi(o.text)))}catch{}return e=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},dx=t=>{let e=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Zi(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Zi(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let i=(0,Ao.parse)(s,Ao.STR|Ao.OBJ),d=o(i);d!==null&&(e=d)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},sl=()=>{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 il=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 Yw="https://api.runtype.com/v1/dispatch",ll="https://api.runtype.com";function Zw(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 Xd=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 ev(t){switch(t){case"json":return al;case"regex-json":return ol;case"xml":return sl;default:return nl}}var cx=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function tv(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=cx(r);if(!cx(n))return t;if(!o||n===r||n.startsWith(r))return e;let a=ha(t);return ha(e)!==null&&a===null?e:t}var xa=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:Yw,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:ev(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 ja(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$/,""))||ll}/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$/,""))||ll}/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(Xd).map(h=>{var C,v,T;return{id:h.id,role:h.role,content:(T=(v=(C=h.contentParts)!=null?C:h.llmContent)!=null?v: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}},f=l.clientTools,m=!!(f&&f.length>0),y=m?ax(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,S=m&&x&&this.lastSentClientToolsFingerprint===y,k=!1,E=null,M;for(let h=0;;h++){let v={...u,...m&&(k||!S)&&f?{clientTools:f}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:n.signal}),M.status===409&&h===0&&m){let T=await M.json().catch(()=>null);if((T==null?void 0:T.error)==="client_tools_resend_required"){k=!0,this.lastSentClientToolsFingerprint=null;continue}E=T!=null?T:{error:"Chat request failed"}}break}if(!M.ok){let h=E!=null?E:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(M.status===429){let v=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let C=new Error(h.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!M.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(M.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(e,r){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,e.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(e,r,n){r({type:"status",status:"connected"});try{await this.streamResponse(e,r,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(e,r){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ll}/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(/\/+$/,""))||ll}/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(Xd).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(Xd).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 se,ie,Be,Xe;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=B=>{let xe=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,De=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,rt=B.tools?B.tools.map(ze=>({...ze,chunks:ze.chunks?[...ze.chunks]:void 0})):void 0;return{...B,reasoning:xe,toolCall:De,tools:rt}},u=B=>{if(B.role!=="assistant"||B.variant)return!0;let xe=Array.isArray(B.contentParts)&&B.contentParts.length>0,De=typeof B.rawContent=="string"&&B.rawContent.trim()!=="";return typeof B.content=="string"&&B.content.trim()!==""||xe||De||!!B.stopReason},f=B=>{u(B)&&r({type:"message",message:p(B)})},m=null,y=null,x={current:null},S={current:null},k=!1,E=new Map,M=new Map,h=new Map,C=new Map,v={lastId:null,byStep:new Map},T={lastId:null,byCall:new Map},W=(B,xe,De="")=>`${B}::${xe}::${De}`,P=(B,xe)=>`${B}::${xe}::`,R=(B,xe,De,rt)=>{let ze=W(B,xe,De),je=h.get(ze);if(je)return je;let at=De?`-${De}`:"",Rt={id:`nested-${B}-${xe}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:rt,parentToolId:B,parentStepId:xe}};return h.set(ze,Rt),f(Rt),Rt},N=B=>{if(B==null)return null;try{return String(B)}catch{return null}},j=B=>{var xe,De,rt,ze,je;return N((je=(ze=(rt=(De=(xe=B.stepId)!=null?xe:B.step_id)!=null?De:B.step)!=null?rt:B.parentId)!=null?ze:B.flowStepId)!=null?je:B.flow_step_id)},ce=B=>{var xe,De,rt,ze,je,at,Rt;return N((Rt=(at=(je=(ze=(rt=(De=(xe=B.callId)!=null?xe:B.call_id)!=null?De:B.requestId)!=null?rt:B.request_id)!=null?ze:B.toolCallId)!=null?je:B.tool_call_id)!=null?at:B.stepId)!=null?Rt:B.step_id)},be=n,Ze=!1,Se=()=>{if(m)return m;let B;return!Ze&&be?(B=be,Ze=!0):be&&S.current?B=`${be}_${S.current}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:B,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},Ne=(B,xe)=>{v.lastId=xe,B&&v.byStep.set(B,xe)},Ce=(B,xe)=>{var je;let De=(je=B.reasoningId)!=null?je:B.id,rt=j(B);if(De){let at=String(De);return Ne(rt,at),at}if(rt){let at=v.byStep.get(rt);if(at)return v.lastId=at,at}if(v.lastId&&!xe)return v.lastId;if(!xe)return null;let ze=`reason-${l()}`;return Ne(rt,ze),ze},Fe=B=>{let xe=E.get(B);if(xe)return xe;let De={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:B,status:"streaming",chunks:[]}};return E.set(B,De),f(De),De},We=(B,xe)=>{T.lastId=xe,B&&T.byCall.set(B,xe)},Z=new Set,ne=new Map,ee=new Set,we=new Map,Q=B=>{if(!B)return!1;let xe=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return xe==="emit_artifact_markdown"||xe==="emit_artifact_component"},X=(B,xe)=>{var je;let De=(je=B.toolId)!=null?je:B.id,rt=ce(B);if(De){let at=String(De);return We(rt,at),at}if(rt){let at=T.byCall.get(rt);if(at)return T.lastId=at,at}if(T.lastId&&!xe)return T.lastId;if(!xe)return null;let ze=`tool-${l()}`;return We(rt,ze),ze},fe=B=>{let xe=M.get(B);if(xe)return xe;let De={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:B,status:"pending"}};return M.set(B,De),f(De),De},Le=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let xe=Number(B);if(!Number.isNaN(xe)&&Number.isFinite(xe))return xe;let De=Date.parse(B);if(!Number.isNaN(De))return De}return Date.now()},me=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},te=new Map,le=new Map,ht=new Map,mt=new Map,Re=null,ye=(B,xe,De)=>{var Rt;let rt=ht.get(B);rt||(rt=[],ht.set(B,rt));let ze=0,je=rt.length;for(;ze<je;){let tr=ze+je>>>1;rt[tr].seq<xe?ze=tr+1:je=tr}((Rt=rt[ze])==null?void 0:Rt.seq)===xe?rt[ze]={seq:xe,text:De}:rt.splice(ze,0,{seq:xe,text:De});let at="";for(let tr=0;tr<rt.length;tr++)at+=rt[tr].text;return at},ot=(B,xe)=>{let De=me(xe),rt=le.get(B.id),ze=tv(rt,De);B.rawContent=ze;let je=te.get(B.id),at=vt=>{var Te;let ut=(Te=B.content)!=null?Te:"";vt.trim()!==""&&(ut.trim().length===0||vt.startsWith(ut)||vt.trimStart().startsWith(ut.trim()))&&(B.content=vt)},Rt=()=>{var vt;if(je){let ut=(vt=je.close)==null?void 0:vt.call(je);ut instanceof Promise&&ut.catch(()=>{})}te.delete(B.id),le.delete(B.id),B.streaming=!1,f(B)};if(!je){at(De),Rt();return}let tr=ha(ze);if(tr!==null&&tr.trim()!==""){at(tr),Rt();return}let cr=vt=>{var ue;let ut=typeof vt=="string"?vt:(ue=vt==null?void 0:vt.text)!=null?ue:null;if(ut!==null&&ut.trim()!=="")return ut;let Te=je.getExtractedText();return Te!==null&&Te.trim()!==""?Te:De},Y;try{Y=je.processChunk(ze)}catch{at(De),Rt();return}if(Y instanceof Promise){Y.then(vt=>{at(cr(vt)),Rt()}).catch(()=>{at(De),Rt()});return}at(cr(Y)),Rt()},He=[],G=!1,he,K=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,he()}))},wt=new il((B,xe)=>{He.push({payloadType:B,payload:xe}),K()}),U=null,J=new Map,qe=(se=this.config.iterationDisplay)!=null?se:"separate";for(he=()=>{var B,xe,De,rt,ze,je,at,Rt,tr,cr,Y,vt,ut,Te,ue,pt,hr,xt,vr,Dr,yt,Dt,it,Xt,Cr,pr,xr,Er,fn,Wt,zr,wr,kn,ln,Lt,Jn,En,Ge,I,pe,Oe,zt,st,Vt,or,fr,Pt,Vr,Jt,jr,$n,po,Po,mn,Qt,Yr,Ln,Io,uo,Ro,Qn,gn,Un,Ht,Ar,Sr,hn,Wo,Me,Pn,In,q,Yn,fo,mo,Zn,qn,ps,xn,yn,zn,Vn,Zo,go,Gr,eo,La,ea,Pa,gi,Ia,hi,Ra,Ot,us,Rn,dn,xi,yi,Wa,ho,fs,Ho,ms,gs,hs,xs,cn,Ha,to,ro,ys,bi,bs,ws,ta,wi,vi,Ci,Ai,md,ra,Bo,Si,vs,Do,Ti,Cs,Oo,As,Mi,xo,ki,No,Yt,Ba,Da,Ss;for(let Wn=0;Wn<He.length;Wn++){let lt=He[Wn].payloadType,L=He[Wn].payload;if(lt==="reason_start"){let z=(B=Ce(L,!0))!=null?B:`reason-${l()}`,D=Fe(z);D.reasoning=(xe=D.reasoning)!=null?xe:{id:z,status:"streaming",chunks:[]},D.reasoning.startedAt=(rt=D.reasoning.startedAt)!=null?rt:Le((De=L.startedAt)!=null?De:L.timestamp),D.reasoning.completedAt=void 0,D.reasoning.durationMs=void 0,D.streaming=!0,D.reasoning.status="streaming",f(D)}else if(lt==="reason_delta"||lt==="reason_chunk"){let z=(je=(ze=Ce(L,!1))!=null?ze:Ce(L,!0))!=null?je:`reason-${l()}`,D=Fe(z);D.reasoning=(at=D.reasoning)!=null?at:{id:z,status:"streaming",chunks:[]},D.reasoning.startedAt=(tr=D.reasoning.startedAt)!=null?tr:Le((Rt=L.startedAt)!=null?Rt:L.timestamp);let ae=(vt=(Y=(cr=L.reasoningText)!=null?cr:L.text)!=null?Y:L.delta)!=null?vt:"";if(ae&&L.hidden!==!0){let ge=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(ge!==void 0){let re=ye(z,ge,String(ae));D.reasoning.chunks=[re]}else D.reasoning.chunks.push(String(ae))}if(D.reasoning.status=L.done?"complete":"streaming",L.done){D.reasoning.completedAt=Le((ut=L.completedAt)!=null?ut:L.timestamp);let ge=(Te=D.reasoning.startedAt)!=null?Te:Date.now();D.reasoning.durationMs=Math.max(0,((ue=D.reasoning.completedAt)!=null?ue:Date.now())-ge)}D.streaming=D.reasoning.status!=="complete",f(D)}else if(lt==="reason_complete"){let z=(hr=(pt=Ce(L,!1))!=null?pt:Ce(L,!0))!=null?hr:`reason-${l()}`,D=E.get(z);if(D!=null&&D.reasoning){D.reasoning.status="complete",D.reasoning.completedAt=Le((xt=L.completedAt)!=null?xt:L.timestamp);let ge=(vr=D.reasoning.startedAt)!=null?vr:Date.now();D.reasoning.durationMs=Math.max(0,((Dr=D.reasoning.completedAt)!=null?Dr:Date.now())-ge),D.streaming=!1,f(D)}let ae=j(L);ae&&v.byStep.delete(ae)}else if(lt==="tool_start"){let z=(yt=X(L,!0))!=null?yt:`tool-${l()}`,D=(Dt=L.toolName)!=null?Dt:L.name;if(Q(D)){Z.add(z);continue}let ae=fe(z),ge=(it=ae.toolCall)!=null?it:{id:z,status:"pending"};ge.name=D!=null?D:ge.name,ge.status="running",L.args!==void 0?ge.args=L.args:L.parameters!==void 0&&(ge.args=L.parameters),ge.startedAt=(Cr=ge.startedAt)!=null?Cr:Le((Xt=L.startedAt)!=null?Xt:L.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,ae.toolCall=ge,ae.streaming=!0;let re=L.agentContext;(re||L.executionId)&&(ae.agentMetadata={executionId:(pr=re==null?void 0:re.executionId)!=null?pr:L.executionId,iteration:(xr=re==null?void 0:re.iteration)!=null?xr:L.iteration}),f(ae)}else if(lt==="tool_chunk"||lt==="tool_delta"){let z=(fn=(Er=X(L,!1))!=null?Er:X(L,!0))!=null?fn:`tool-${l()}`;if(Z.has(z))continue;let D=fe(z),ae=(Wt=D.toolCall)!=null?Wt:{id:z,status:"running"};ae.startedAt=(wr=ae.startedAt)!=null?wr:Le((zr=L.startedAt)!=null?zr:L.timestamp);let ge=(Lt=(ln=(kn=L.text)!=null?kn:L.delta)!=null?ln:L.message)!=null?Lt:"";ge&&(ae.chunks=(Jn=ae.chunks)!=null?Jn:[],ae.chunks.push(String(ge))),ae.status="running",D.toolCall=ae,D.streaming=!0;let re=L.agentContext;(re||L.executionId)&&(D.agentMetadata=(I=D.agentMetadata)!=null?I:{executionId:(En=re==null?void 0:re.executionId)!=null?En:L.executionId,iteration:(Ge=re==null?void 0:re.iteration)!=null?Ge:L.iteration}),f(D)}else if(lt==="tool_complete"){let z=(Oe=(pe=X(L,!1))!=null?pe:X(L,!0))!=null?Oe:`tool-${l()}`;if(Z.has(z)){Z.delete(z);continue}let D=fe(z),ae=(zt=D.toolCall)!=null?zt:{id:z,status:"running"};ae.status="complete",L.result!==void 0&&(ae.result=L.result),typeof L.duration=="number"&&(ae.duration=L.duration),ae.completedAt=Le((st=L.completedAt)!=null?st:L.timestamp);let ge=(Vt=L.duration)!=null?Vt:L.executionTime;if(typeof ge=="number")ae.durationMs=ge;else{let Qe=(or=ae.startedAt)!=null?or:Date.now();ae.durationMs=Math.max(0,((fr=ae.completedAt)!=null?fr:Date.now())-Qe)}D.toolCall=ae,D.streaming=!1;let re=L.agentContext;(re||L.executionId)&&(D.agentMetadata=(Jt=D.agentMetadata)!=null?Jt:{executionId:(Pt=re==null?void 0:re.executionId)!=null?Pt:L.executionId,iteration:(Vr=re==null?void 0:re.iteration)!=null?Vr:L.iteration}),f(D);let $e=ce(L);$e&&T.byCall.delete($e)}else if(lt==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let z=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,D=(jr=z!=null?z:L.toolId)!=null?jr:`local-${l()}`,ae=fe(D),ge=L.toolName,re=qo(ge),$e=($n=ae.toolCall)!=null?$n:{id:D,status:"pending"};$e.name=ge,$e.args=L.parameters,$e.status=re?"running":"complete",$e.chunks=(po=$e.chunks)!=null?po:[],$e.startedAt=(mn=$e.startedAt)!=null?mn:Le((Po=L.startedAt)!=null?Po:L.timestamp),re?($e.completedAt=void 0,$e.duration=void 0,$e.durationMs=void 0):$e.completedAt=(Qt=$e.completedAt)!=null?Qt:$e.startedAt,ae.toolCall=$e,ae.streaming=!1,ae.agentMetadata={...ae.agentMetadata,executionId:(Ln=L.executionId)!=null?Ln:(Yr=ae.agentMetadata)==null?void 0:Yr.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},f(ae)}else if(lt==="text_start"){if((Io=L.toolContext)!=null&&Io.toolId)continue;let z=L.partId;if(z!==void 0&&S.current!==null&&z!==S.current){let D=m;D&&(D.streaming=!1,f(D),Re=D,m=null,k=!0)}z!==void 0&&(S.current=z)}else if(lt==="text_end"){if((uo=L.toolContext)!=null&&uo.toolId)continue;let z=m;z&&(z.streaming=!1,f(z),Re=z,m=null,k=!0)}else if(lt==="step_chunk"||lt==="step_delta"){let z=L.stepType,D=L.executionType;if(z==="tool"||D==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let Qe=String((Qn=(Ro=L.id)!=null?Ro:ae.stepId)!=null?Qn:`step-${l()}`),Ct=L.partId!==void 0&&L.partId!==null?String(L.partId):"",ft=`${ae.toolId}::${Qe}`,Kt=C.get(ft);if(Ct!==""&&Kt!==void 0&&Kt!==""&&Kt!==Ct){let At=h.get(W(ae.toolId,Qe,Kt));At&&At.streaming!==!1&&(At.streaming=!1,f(At))}Ct!==""&&C.set(ft,Ct);let ar=R(ae.toolId,Qe,Ct,ae.executionId),rr=(Ar=(Ht=(Un=(gn=L.text)!=null?gn:L.delta)!=null?Un:L.content)!=null?Ht:L.chunk)!=null?Ar:"";rr&&(ar.content+=String(rr),ar.streaming=!0,f(ar)),L.isComplete&&(ar.streaming=!1,f(ar));continue}let ge=L.partId;if(ge!==void 0&&S.current!==null&&ge!==S.current){let Qe=m;Qe&&(Qe.streaming=!1,f(Qe),Re=Qe,m=null,k=!0)}ge!==void 0&&(S.current=ge);let re=ge!==void 0&&(Sr=mt.get(ge))!=null?Sr:Se();ge!==void 0&&(re.partId||(re.partId=ge),mt.set(ge,re));let $e=(Pn=(Me=(Wo=(hn=L.text)!=null?hn:L.delta)!=null?Wo:L.content)!=null?Me:L.chunk)!=null?Pn:"";if($e){let Qe=typeof L.seq=="number"?L.seq:void 0,Ct=ge!=null?ge:re.id,ft=Qe!==void 0?ye(Ct,Qe,String($e)):((In=le.get(re.id))!=null?In:"")+$e;re.rawContent=ft,te.has(re.id)||te.set(re.id,this.createStreamParser());let Kt=te.get(re.id),ar=ft.trim().startsWith("{")||ft.trim().startsWith("[");if(ar&&le.set(re.id,ft),Kt.__isPlainTextParser===!0){re.content=Qe!==void 0?ft:re.content+$e,le.delete(re.id),te.delete(re.id),re.rawContent=void 0,f(re);continue}let At=Kt.processChunk(ft);if(At instanceof Promise)At.then(Ut=>{var Kr;let et=typeof Ut=="string"?Ut:(Kr=Ut==null?void 0:Ut.text)!=null?Kr:null;if(et!==null&&et.trim()!=="")re.content=et,f(re);else if(!ar&&!ft.trim().startsWith("<")){let Or=m,sr=Or&&Or.id===re.id?Or:re;sr.id===re.id&&(sr.content=Qe!==void 0?ft:sr.content+$e,le.delete(sr.id),te.delete(sr.id),sr.rawContent=void 0,f(sr))}}).catch(()=>{re.content=Qe!==void 0?ft:re.content+$e,le.delete(re.id),te.delete(re.id),re.rawContent=void 0,f(re)});else{let Ut=typeof At=="string"?At:(q=At==null?void 0:At.text)!=null?q:null;Ut!==null&&Ut.trim()!==""?(re.content=Ut,f(re)):!ar&&!ft.trim().startsWith("<")&&(re.content=Qe!==void 0?ft:re.content+$e,le.delete(re.id),te.delete(re.id),re.rawContent=void 0,f(re))}}if(L.isComplete){let Qe=(fo=(Yn=L.result)==null?void 0:Yn.response)!=null?fo:re.content;if(Qe){let Ct=le.get(re.id),ft=Ct!=null?Ct:me(Qe);re.rawContent=ft;let Kt=te.get(re.id),ar=null,rr=!1;if(Kt&&(ar=Kt.getExtractedText(),ar===null&&(ar=ha(ft)),ar===null)){let At=Kt.processChunk(ft);At instanceof Promise?(rr=!0,At.then(Ut=>{var Kr;let et=typeof Ut=="string"?Ut:(Kr=Ut==null?void 0:Ut.text)!=null?Kr:null;if(et!==null){let Or=m;Or&&Or.id===re.id&&(Or.content=et,Or.streaming=!1,te.delete(Or.id),le.delete(Or.id),f(Or))}})):ar=typeof At=="string"?At:(mo=At==null?void 0:At.text)!=null?mo:null}if(!rr){ar!==null&&ar.trim()!==""?re.content=ar:le.has(re.id)||(re.content=me(Qe));let At=te.get(re.id);if(At){let Ut=(Zn=At.close)==null?void 0:Zn.call(At);Ut instanceof Promise&&Ut.catch(()=>{}),te.delete(re.id)}le.delete(re.id),re.streaming=!1,f(re)}}}}else if(lt==="step_complete"){let z=L.stepType,D=L.executionType;if(z==="tool"||D==="context")continue;let ae=L.toolContext;if(ae!=null&&ae.toolId){let Qe=String((ps=(qn=L.id)!=null?qn:ae.stepId)!=null?ps:"");if(Qe){let Ct=P(ae.toolId,Qe);for(let[ft,Kt]of h)ft.startsWith(Ct)&&Kt.streaming!==!1&&(Kt.streaming=!1,f(Kt));C.delete(`${ae.toolId}::${Qe}`)}continue}let ge=L.stopReason;if(k){if(m!==null){let ft=m;ge&&(ft.stopReason=ge),te.delete(ft.id),le.delete(ft.id),ft.streaming!==!1&&(ft.streaming=!1,f(ft))}let Qe=(xn=L.result)==null?void 0:xn.response,Ct=Re;Ct&&(ge&&(Ct.stopReason=ge),Qe!=null?ot(Ct,Qe):(te.delete(Ct.id),le.delete(Ct.id))),Re=null;continue}let re=(yn=L.result)==null?void 0:yn.response,$e=Se();if(ge&&($e.stopReason=ge),re!=null){let Qe=te.get($e.id),Ct=!1,ft=!1;if(Qe){let Kt=Qe.getExtractedText(),ar=le.get($e.id),rr=ar!=null?ar:me(re);if($e.rawContent=rr,Kt!==null&&Kt.trim()!=="")$e.content=Kt,Ct=!0;else{let At=ha(rr);if(At!==null)$e.content=At,Ct=!0;else{let Ut=Qe.processChunk(rr);if(Ut instanceof Promise)ft=!0,Ut.then(et=>{var Or;let Kr=typeof et=="string"?et:(Or=et==null?void 0:et.text)!=null?Or:null;if(Kr!==null&&Kr.trim()!==""){let sr=m;sr&&sr.id===$e.id&&(sr.content=Kr,sr.streaming=!1,te.delete(sr.id),le.delete(sr.id),f(sr))}else{let sr=Qe.getExtractedText(),jn=m;jn&&jn.id===$e.id&&(sr!==null&&sr.trim()!==""?jn.content=sr:le.has(jn.id)||(jn.content=me(re)),jn.streaming=!1,te.delete(jn.id),le.delete(jn.id),f(jn))}});else{let et=typeof Ut=="string"?Ut:(zn=Ut==null?void 0:Ut.text)!=null?zn:null;if(et!==null&&et.trim()!=="")$e.content=et,Ct=!0;else{let Kr=Qe.getExtractedText();Kr!==null&&Kr.trim()!==""&&($e.content=Kr,Ct=!0)}}}}}if(!ft){if(!$e.rawContent){let Kt=le.get($e.id);$e.rawContent=Kt!=null?Kt:me(re)}if(!Ct&&!le.has($e.id)&&($e.content=me(re)),Qe){let Kt=(Vn=Qe.close)==null?void 0:Vn.call(Qe);Kt instanceof Promise&&Kt.catch(()=>{})}te.delete($e.id),le.delete($e.id),$e.streaming=!1,f($e)}}else te.delete($e.id),le.delete($e.id),$e.streaming=!1,f($e)}else if(lt==="flow_complete"){let z=(Zo=L.result)==null?void 0:Zo.response;if(k){if(m!==null){let D=m;te.delete(D.id),le.delete(D.id),D.streaming!==!1&&(D.streaming=!1,f(D))}}else if(z!=null){let D=Se(),ae=le.get(D.id),ge=ae!=null?ae:me(z);D.rawContent=ge;let re=me(z),$e=te.get(D.id);if($e){let ft=ha(ge);if(ft!==null)re=ft;else{let Kt=$e.processChunk(ge);Kt instanceof Promise&&Kt.then(rr=>{var Ut;let At=typeof rr=="string"?rr:(Ut=rr==null?void 0:rr.text)!=null?Ut:null;At!==null&&(D.content=At,D.streaming=!1,f(D))});let ar=$e.getExtractedText();ar!==null&&(re=ar)}}te.delete(D.id),le.delete(D.id);let Qe=re!==D.content,Ct=D.streaming!==!1;Qe&&(D.content=re),D.streaming=!1,(Qe||Ct)&&f(D)}else if(m!==null){let D=m;te.delete(D.id),le.delete(D.id),D.streaming!==!1&&(D.streaming=!1,f(D))}r({type:"status",status:"idle"})}else if(lt==="agent_start")U={executionId:L.executionId,agentId:(go=L.agentId)!=null?go:"virtual",agentName:(Gr=L.agentName)!=null?Gr:"",status:"running",currentIteration:0,maxTurns:(eo=L.maxTurns)!=null?eo:1,startedAt:Le(L.startedAt)};else if(lt==="agent_iteration_start"){if(U&&(U.currentIteration=L.iteration),qe==="separate"&&L.iteration>1){let z=m;z&&(z.streaming=!1,f(z),J.set(L.iteration-1,z),m=null)}}else if(lt==="agent_turn_start")y=null;else if(lt==="agent_turn_delta"){if(L.contentType==="text"){let z=Se();z.content+=(La=L.delta)!=null?La:"",z.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:U==null?void 0:U.agentName},y=z,f(z)}else if(L.contentType==="thinking"){let z=(ea=L.turnId)!=null?ea:`agent-think-${L.iteration}`,D=Fe(z);D.reasoning=(Pa=D.reasoning)!=null?Pa:{id:z,status:"streaming",chunks:[]},D.reasoning.chunks.push((gi=L.delta)!=null?gi:""),D.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},f(D)}else if(L.contentType==="tool_input"){let z=(Ia=L.toolCallId)!=null?Ia:T.lastId;if(z){let D=M.get(z);D!=null&&D.toolCall&&(D.toolCall.chunks=(hi=D.toolCall.chunks)!=null?hi:[],D.toolCall.chunks.push((Ra=L.delta)!=null?Ra:""),f(D))}}}else if(lt==="agent_turn_complete"){let z=L.turnId;if(z){let ge=E.get(z);if(ge!=null&&ge.reasoning){ge.reasoning.status="complete",ge.reasoning.completedAt=Le(L.completedAt);let re=(Ot=ge.reasoning.startedAt)!=null?Ot:Date.now();ge.reasoning.durationMs=Math.max(0,((us=ge.reasoning.completedAt)!=null?us:Date.now())-re),ge.streaming=!1,f(ge)}}let D=L.stopReason,ae=m!=null?m:y;if(D&&ae!==null){let ge=L.turnId;(!ge||((Rn=ae.agentMetadata)==null?void 0:Rn.turnId)===ge)&&(ae.stopReason=D,f(ae))}}else if(lt==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let z=(dn=L.toolCallId)!=null?dn:`agent-tool-${l()}`;We(ce(L),z);let D=fe(z),ae=(xi=D.toolCall)!=null?xi:{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};ae.name=(Wa=(yi=L.toolName)!=null?yi:L.name)!=null?Wa:ae.name,ae.status="running",L.parameters!==void 0&&(ae.args=L.parameters),ae.startedAt=Le((ho=L.startedAt)!=null?ho:L.timestamp),D.toolCall=ae,D.streaming=!0,D.agentMetadata={executionId:L.executionId,iteration:L.iteration},f(D)}else if(lt==="agent_tool_delta"){let z=(fs=L.toolCallId)!=null?fs:T.lastId;if(z){let D=(Ho=M.get(z))!=null?Ho:fe(z);D.toolCall&&(D.toolCall.chunks=(ms=D.toolCall.chunks)!=null?ms:[],D.toolCall.chunks.push((gs=L.delta)!=null?gs:""),D.toolCall.status="running",D.streaming=!0,f(D))}}else if(lt==="agent_tool_complete"){let z=(hs=L.toolCallId)!=null?hs:T.lastId;if(z){let D=(xs=M.get(z))!=null?xs:fe(z);if(D.toolCall){D.toolCall.status="complete",L.result!==void 0&&(D.toolCall.result=L.result),typeof L.executionTime=="number"&&(D.toolCall.durationMs=L.executionTime),D.toolCall.completedAt=Le((cn=L.completedAt)!=null?cn:L.timestamp),D.streaming=!1,f(D);let ae=ce(L);ae&&T.byCall.delete(ae)}}}else if(lt==="agent_media"){let z=Array.isArray(L.media)?L.media:[],D=[];for(let ae of z){if(!ae||typeof ae!="object")continue;let ge=ae,re=typeof ge.type=="string"?ge.type:void 0,$e=typeof ge.mediaType=="string"?ge.mediaType.toLowerCase():"",Qe=null,Ct="";if(re==="media"){let ft=typeof ge.data=="string"?ge.data:void 0;if(!ft)continue;Ct=$e.length>0?$e:"application/octet-stream",Qe=`data:${Ct};base64,${ft}`}else if(re==="image-url"){let ft=typeof ge.url=="string"?ge.url:void 0;if(!ft)continue;Ct=$e,Qe=ft}else if(re==="file-url"){let ft=typeof ge.url=="string"?ge.url:void 0;if(!ft)continue;Ct=$e,Qe=ft}else continue;if(Qe)if(re==="image-url"||Ct.startsWith("image/"))D.push({type:"image",image:Qe,...Ct?{mimeType:Ct}:{}});else if(Ct.startsWith("audio/"))D.push({type:"audio",audio:Qe,mimeType:Ct});else if(Ct.startsWith("video/"))D.push({type:"video",video:Qe,mimeType:Ct});else{let ft=Ct||"application/octet-stream";D.push({type:"file",data:Qe,mimeType:ft,filename:Zw(ft)})}}if(D.length>0){let ae=l(),ge=L.toolCallId,$e={id:`agent-media-${typeof ge=="string"&&ge.length>0?`${ge}-${ae}`:String(ae)}`,role:"assistant",content:"",contentParts:D,createdAt:new Date().toISOString(),streaming:!1,sequence:ae,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};f($e);let Qe=m;Qe&&(Qe.streaming=!1,f(Qe)),m=null,x.current=null}}else if(lt!=="agent_iteration_complete"){if(lt==="agent_reflection"||lt==="agent_reflect"){let z=`agent-reflection-${L.executionId}-${L.iteration}`,D={id:z,role:"assistant",content:(Ha=L.reflection)!=null?Ha:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(to=L.reflection)!=null?to:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};f(D)}else if(lt==="agent_complete"){U&&(U.status=L.success?"complete":"error",U.completedAt=Le(L.completedAt),U.stopReason=L.stopReason);let z=m;z&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}else if(lt==="agent_error"){let z=typeof L.error=="string"?L.error:(ys=(ro=L.error)==null?void 0:ro.message)!=null?ys:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):r({type:"error",error:new Error(z)})}else if(lt!=="agent_ping"){if(lt==="agent_approval_start"){let z=(bi=L.approvalId)!=null?bi:`approval-${l()}`,D={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(bs=U==null?void 0:U.agentId)!=null?bs:"virtual",executionId:(ta=(ws=L.executionId)!=null?ws:U==null?void 0:U.executionId)!=null?ta:"",toolName:(wi=L.toolName)!=null?wi:"",toolType:L.toolType,description:(Ci=L.description)!=null?Ci:`Execute ${(vi=L.toolName)!=null?vi:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(D)}else if(lt==="step_await"&&L.awaitReason==="approval_required"){let z=(Ai=L.approvalId)!=null?Ai:`approval-${l()}`,D={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(md=U==null?void 0:U.agentId)!=null?md:"virtual",executionId:(Bo=(ra=L.executionId)!=null?ra:U==null?void 0:U.executionId)!=null?Bo:"",toolName:(Si=L.toolName)!=null?Si:"",toolType:L.toolType,description:(Do=L.description)!=null?Do:`Execute ${(vs=L.toolName)!=null?vs:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(D)}else if(lt==="agent_approval_complete"){let z=L.approvalId;if(z){let ae={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(Ti=L.decision)!=null?Ti:"approved",agentId:(Cs=U==null?void 0:U.agentId)!=null?Cs:"virtual",executionId:(As=(Oo=L.executionId)!=null?Oo:U==null?void 0:U.executionId)!=null?As:"",toolName:(Mi=L.toolName)!=null?Mi:"",description:(xo=L.description)!=null?xo:"",resolvedAt:Date.now()}};f(ae)}}else if(lt==="artifact_start"||lt==="artifact_delta"||lt==="artifact_update"||lt==="artifact_complete"){if(lt==="artifact_start"){let z=L.artifactType,D=String(L.id),ae=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:D,artifactType:z,title:ae,component:typeof L.component=="string"?L.component:void 0}),we.set(D,{markdown:"",title:ae}),!ee.has(D)){ee.add(D);let ge={id:`artifact-ref-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:D,title:ae,artifactType:z,status:"streaming"}})};ne.set(D,ge),f(ge)}}else if(lt==="artifact_delta"){let z=String(L.id),D=typeof L.delta=="string"?L.delta:String((ki=L.delta)!=null?ki:"");r({type:"artifact_delta",id:z,artDelta:D});let ae=we.get(z);ae&&(ae.markdown+=D)}else if(lt==="artifact_update"){let z=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:z,component:typeof L.component=="string"?L.component:void 0})}else if(lt==="artifact_complete"){let z=String(L.id);r({type:"artifact_complete",id:z});let D=ne.get(z);if(D){D.streaming=!1;try{let ae=JSON.parse((No=D.rawContent)!=null?No:"{}");if(ae.props){ae.props.status="complete";let ge=we.get(z);ge!=null&&ge.markdown&&(ae.props.markdown=ge.markdown)}D.rawContent=JSON.stringify(ae)}catch{}we.delete(z),f(D),ne.delete(z)}}}else if(lt==="transcript_insert"){let z=L.message;if(!z||typeof z!="object")continue;let D=String((Yt=z.id)!=null?Yt:`msg-${l()}`),ae=z.role,re={id:D,role:ae==="user"?"user":ae==="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(f(re),re.rawContent)try{let $e=JSON.parse(re.rawContent),Qe=(Ba=$e==null?void 0:$e.props)==null?void 0:Ba.artifactId;typeof Qe=="string"&&ee.add(Qe)}catch{}m=null,x.current=null,te.delete(D),le.delete(D)}else if(lt==="error"||lt==="step_error"||lt==="dispatch_error"||lt==="flow_error"){let z=null;if(L.error instanceof Error)z=L.error;else if(lt==="dispatch_error"){let D=(Da=L.message)!=null?Da:L.error;D!=null&&D!==""&&(z=new Error(String(D)))}else if(lt==="step_error"||lt==="flow_error"){let D=L.error;typeof D=="string"&&D!==""?z=new Error(D):D!=null&&typeof D=="object"&&"message"in D&&(z=new Error(String((Ss=D.message)!=null?Ss:D)))}else lt==="error"&&L.error!=null&&L.error!==""&&(z=new Error(String(L.error)));if(z){r({type:"error",error:z});let D=m;D&&D.streaming&&(D.streaming=!1,f(D)),r({type:"status",status:"idle"})}}}}}He.length=0};;){let{done:B,value:xe}=await o.read();if(B)break;a+=s.decode(xe,{stream:!0});let De=a.split(`
60
60
 
61
- `);a=(pe=He.pop())!=null?pe:"";for(let Ve of He){let Je=Ve.split(`
62
- `),gt="message",at="";for(let G of Je)G.startsWith("event:")?gt=G.replace("event:","").trim():G.startsWith("data:")&&(at+=G.replace("data:","").trim());if(!at)continue;let Mt;try{Mt=JSON.parse(at)}catch(G){r({type:"error",error:G instanceof Error?G:new Error("Failed to parse chat stream payload")});continue}let Xt=gt!=="message"?gt:(Be=Mt.type)!=null?Be:"message";if((Q=this.onSSEEvent)==null||Q.call(this,Xt,Mt),this.parseSSEEvent){C.current=f;let G=await this.handleCustomSSEEvent(Mt,r,C,u,l,S);if(C.current&&C.current!==f&&(f=C.current),G)continue}ge.push(Xt,Mt),ze()}}ge.flushPending(),ze(),ge.destroy()}};function Dh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${t}_${e}`}function Wa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ia(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var el="[Image]";function Oh(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Nh(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function _h(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Fh(t){return typeof t=="string"?[]:t.filter(e=>e.type==="image")}function Rs(t){return{type:"text",text:t}}function $h(t,e){return{type:"image",image:t,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function Uh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;e({type:"image",image:o,mimeType:t.type,alt:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function qh(t,e=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var zh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gw=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],mo=[...zh,...gw];function hw(t){return zh.includes(t)||t.startsWith("image/")}function tl(t){return hw(t.type)}async function Vh(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;tl(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(t)})}function jh(t,e=mo,r=10*1024*1024){return e.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function xw(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Gh(t,e){let r=xw(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var rl=class{constructor(e=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=e}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let n=r.AudioContext||r.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let r=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(r),s=n.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=n.createBufferSource();a.buffer=s,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of e)r()}}pcmToFloat32(e){let r=Math.floor(e.length/2),n=new Float32Array(r),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<r;s++){let a=o.getInt16(s*2,!0);n[s]=a/32768}return n}};var nl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,r,n,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(r),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ws=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new nl;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,r,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(e=this.config)==null?void 0:e.host,i=(r=this.config)==null?void 0:r.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((u,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let x=!1,C=k=>{x||(x=!0,clearTimeout(S),f(new Error(k)))},S=setTimeout(()=>C("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(S),u())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",k=>{if(!k.wasClean&&!x){let T=k.code!==1006?` (code ${k.code})`:"";C("WebSocket connection failed"+T+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let r=JSON.parse(e.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var r,n;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(r=e.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(e.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(n=e.response.audio)!=null&&n.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(e.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new rl(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var e,r,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(r=(e=this.config)==null?void 0:e.pauseDuration)!=null?r:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(u=>u("processing")),this.processingStartCallbacks.forEach(u=>u());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,n=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(r=>r(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(e),o=this.getFormatFromMimeType(e.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((r,n)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];r(a)},o.onerror=n,o.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let r=atob(e.base64),n=new Uint8Array(r.length);for(let l=0;l<r.length;l++)n[l]=r.charCodeAt(l);let o=e.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([n],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var la=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function da(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Ws(t.runtype);case"browser":if(!la.isSupported())throw new Error("Browser speech recognition not supported");return new la(t.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function ol(t){if((t==null?void 0:t.type)==="runtype"&&t.runtype)return da({type:"runtype",runtype:t.runtype});if(la.isSupported())return da({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Bs(t){try{return ol(t),!0}catch{return!1}}function Kh(t,e){let r=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(r);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}
61
+ `);a=(ie=De.pop())!=null?ie:"";for(let rt of De){let ze=rt.split(`
62
+ `),je="message",at="";for(let cr of ze)cr.startsWith("event:")?je=cr.replace("event:","").trim():cr.startsWith("data:")&&(at+=cr.replace("data:","").trim());if(!at)continue;let Rt;try{Rt=JSON.parse(at)}catch(cr){r({type:"error",error:cr instanceof Error?cr:new Error("Failed to parse chat stream payload")});continue}let tr=je!=="message"?je:(Be=Rt.type)!=null?Be:"message";if((Xe=this.onSSEEvent)==null||Xe.call(this,tr,Rt),this.parseSSEEvent){x.current=m;let cr=await this.handleCustomSSEEvent(Rt,r,x,f,l,S);if(x.current&&x.current!==m&&(m=x.current),cr)continue}wt.push(tr,Rt),he()}}wt.flushPending(),he(),wt.destroy()}};function px(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${t}_${e}`}function Ka(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ya(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var dl="[Image]";function ux(t){return typeof t=="string"?[{type:"text",text:t}]:t}function fx(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function mx(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function gx(t){return typeof t=="string"?[]:t.filter(e=>e.type==="image")}function js(t){return{type:"text",text:t}}function hx(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 xx(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 yx(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 bx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],rv=["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"],So=[...bx,...rv];function nv(t){return bx.includes(t)||t.startsWith("image/")}function cl(t){return nv(t.type)}async function wx(t){return new Promise((e,r)=>{let n=new FileReader;n.onload=()=>{let o=n.result;cl(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 vx(t,e=So,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 ov(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Cx(t,e){let r=ov(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 pl=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 ul=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 Gs=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 ul;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=k=>{y||(y=!0,clearTimeout(S),m(new Error(k)))},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",k=>{if(!k.wasClean&&!y){let E=k.code!==1006?` (code ${k.code})`:"";x("WebSocket connection failed"+E+"."+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 pl(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 ba=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 wa(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Gs(t.runtype);case"browser":if(!ba.isSupported())throw new Error("Browser speech recognition not supported");return new ba(t.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function fl(t){if((t==null?void 0:t.type)==="runtype"&&t.runtype)return wa({type:"runtype",runtype:t.runtype});if(ba.isSupported())return wa({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ks(t){try{return fl(t),!0}catch{return!1}}function Ax(t,e){let r=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(r);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}
63
63
 
64
- _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]}),Xh=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Ba=class t{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=e=>{var r,n,o,s,a,i,d,l;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall;((r=e.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Io(p.name)&&this.enqueueWebMcpAwait(e.message),(n=e.message.agentMetadata)!=null&&n.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(o=e.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=e.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var n,o;this.messages=[...(n=e.initialMessages)!=null?n:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new sa(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Bs((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,r,n;return(n=(r=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:r.call(e))!=null?n:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var r,n,o;try{let s=e||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=da(s);let a=(r=this.config.voiceRecognition)!=null?r:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,u,f,x,C;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((u=l.text)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.text)!=null&&f.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(C=this.pendingVoiceAssistantMessageId)!=null?C:(x=[...this.messages].reverse().find(k=>k.role==="assistant"))==null?void 0:x.id;S&&this.ttsSpokenMessageIds.add(S)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,n,o,s,a,i,d,l,p;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=e.runtype)==null?void 0:n.agentId)||"",clientToken:((o=e.runtype)==null?void 0:o.clientToken)||"",host:(s=e.runtype)==null?void 0:s.host,voiceId:(a=e.runtype)==null?void 0:a.voiceId,pauseDuration:(i=e.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=e.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=e.browser)==null?void 0:l.language)||"en-US",continuous:(p=e.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var e,r;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(r=(e=this.callbacks).onError)==null||r.call(e,n instanceof Error?n:new Error(String(n))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,r){return this.client.submitMessageFeedback(e,r)}async submitCSATFeedback(e,r){return this.client.submitCSATFeedback(e,r)}async submitNPSFeedback(e,r){return this.client.submitNPSFeedback(e,r)}updateConfig(e){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config={...this.config,...e},this.client=new sa(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:r,content:n,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=e,f={id:a!=null?a:r==="user"?Wa():r==="assistant"?ia():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let r=[];for(let n of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:u,rawContent:f}=n,C={id:d!=null?d:o==="user"?Wa():o==="assistant"?ia():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(e){let{component:r,props:n={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,l={text:o,component:r,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,r){var l,p,m,u,f;let n=e.trim();if(!n&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Wa(),s=ia(),a={id:o,role:"user",content:n||el,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let S=Kh(x,this.config.errorMessage);if(S){let k={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(k)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(f=(u=this.callbacks).onError)==null||f.call(u,new Error(String(x))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=ia();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:r.signal,assistantMessageId:e},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Kh(l,this.config.errorMessage);if(m){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,r){var o,s,a;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(e,r){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:r,resolvedAt:Date.now()}}),n(r==="approved")}async resolveApproval(e,r){var d,l,p,m;let n=`approval-${e.id}`,o={...e,status:r,resolvedAt:Date.now()},s={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},r):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},r),u){let f=null;if(u instanceof Response){if(!u.ok){let x=await u.json().catch(()=>null);throw new Error((l=x==null?void 0:x.error)!=null?l:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let f=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||(m=(p=this.callbacks).onError)==null||m.call(p,u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(e,r){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(e,r){var p,m,u,f,x,C,S,k,T,M,h,w;let n=this.messages.find(y=>y.id===e.id);if(((p=n==null?void 0:n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(x=(f=this.callbacks).onError)==null||x.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof r=="string"?void 0:r;if(a===void 0&&typeof r=="string"){let y=(C=e.toolCall)==null?void 0:C.args,E=Array.isArray(y==null?void 0:y.questions)?y.questions:[];if(E.length===1){let B=typeof((S=E[0])==null?void 0:S.question)=="string"?E[0].question:"";B&&(a={[B]:r})}}this.markAskUserQuestionResolved(e,a),(k=this.abortController)==null||k.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let y=typeof r=="string"?r:Object.entries(r).map(([E,B])=>`${E}: ${Array.isArray(B)?B.join(", "):B}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let y=a!=null?a:{};l.forEach((E,B)=>{let P=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!P)return;let R=y[P],O=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${B}`,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${B}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let y=await this.client.resumeFlow(o,{[s]:r});if(!y.ok){let E=await y.json().catch(()=>null);throw new Error((M=E==null?void 0:E.error)!=null?M:`Resume failed: ${y.status}`)}y.body?await this.connectStream(y.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(y){let E=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(w=(h=this.callbacks).onError)==null||w.call(h,y instanceof Error?y:new Error(String(y)))}}enqueueWebMcpAwait(e){var s,a;let r=(s=e.agentMetadata)==null?void 0:s.executionId,n=(a=e.toolCall)==null?void 0:a.id;if(!r||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(r);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,o)),!o.seen.has(n)&&(o.seen.add(n),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(e){let r=this.webMcpAwaitBatches.get(e);if(!r)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=r;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(e,n)}resolveWebMcpToolStartedAt(e){var o,s;let r=this.messages.find(a=>a.id===e.id),n=[(o=r==null?void 0:r.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of n)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(e){let r=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),r}markWebMcpToolComplete(e,r,n,o=Date.now()){this.messages.some(s=>s.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:r,startedAt:n,completedAt:o,duration:void 0,durationMs:Math.max(0,o-n)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,r){var d,l,p;let n=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(r.map(async m=>{var h,w,y,E,B,P,R;let u=(h=m.toolCall)==null?void 0:h.name,f=(w=m.toolCall)==null?void 0:w.id;if(!u||!f)return null;let x=`${e}:${f}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x))return null;this.webMcpInflightKeys.add(x),n.push(x);let C=this.markWebMcpToolRunning(m),S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let k=(E=(y=m.agentMetadata)==null?void 0:y.webMcpToolCallId)!=null?E:u,T=this.client.executeWebMcpToolCall(u,(B=m.toolCall)==null?void 0:B.args,S.signal),M;if(!T)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await T}catch(O){let V=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return V||(R=(P=this.callbacks).onError)==null||R.call(P,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(m,Hs(V?"Aborted by cancel()":Xh(O)),C),this.webMcpInflightKeys.delete(x),null}return S.signal.aborted?(this.markWebMcpToolComplete(m,Hs("Aborted by cancel()"),C),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:k,output:M,toolMessage:m,startedAt:C,completedAt:Date.now()}})),i=[];try{if(i=a.filter(f=>f!==null),i.length===0)return;let m={};for(let f of i)m[f.resumeKey]=f.output;let u=await this.client.resumeFlow(e,m,{signal:s.signal});if(!u.ok){let f=await u.json().catch(()=>null);throw new Error((d=f==null?void 0:f.error)!=null?d:`Resume failed: ${u.status}`)}for(let f of i)this.webMcpResolvedKeys.add(f.dedupeKey),this.markWebMcpToolComplete(f.toolMessage,f.output,f.startedAt,f.completedAt);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(m){if(!(m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,m instanceof Error?m:new Error(String(m)));else for(let f of i)this.markWebMcpToolComplete(f.toolMessage,Hs("Aborted by cancel()"),f.startedAt)}finally{for(let m of n)this.webMcpInflightKeys.delete(m);for(let m of o)this.webMcpResolveControllers.delete(m);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var f,x,C,S,k,T,M,h,w,y,E,B;let r=(f=e.agentMetadata)==null?void 0:f.executionId,n=(x=e.toolCall)==null?void 0:x.name,o=(C=e.toolCall)==null?void 0:C.id;if(!r){(k=(S=this.callbacks).onError)==null||k.call(S,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let P=`${r}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);try{await this.resumeWithToolOutput(r,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(P)}catch(R){(M=(T=this.callbacks).onError)==null||M.call(T,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(P)}return}let s=`${r}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(h=e.toolCall)==null?void 0:h.args,p=this.client.executeWebMcpToolCall(n,l,d),m="execute",u=a;try{let P;if(p?P=await p:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Hs("Aborted by cancel()"),a);return}let R=(y=(w=e.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?y:n;m="resume",await this.resumeWithToolOutput(r,R,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,P,a,u)},signal:d})}catch(P){let R=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(m==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(e,Hs(R||d.aborted?"Aborted by cancel()":Xh(P)),a),R||(B=(E=this.callbacks).onError)==null||B.call(E,P instanceof Error?P:new Error(String(P)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,r,n,o){var a,i;let s=await this.client.resumeFlow(e,{[r]:n},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let r=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:r,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(r,s),this.selectedArtifactId=r,this.emitArtifactsState(),s}let n={id:r,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(r,n),this.selectedArtifactId=r,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,r;(r=(e=this.callbacks).onArtifactsState)==null||r.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var r,n;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(r=e.component)!=null?r:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,r=null){this.artifacts.clear();for(let n of e)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let r=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),r&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let n=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,e)}speak(e,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(e),s=n.getVoices();if(r.voice){let a=s.find(i=>i.name===r.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):t.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(e){var n;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=e.find(a=>a.name===o);if(s)return s}return(n=e.find(o=>o.lang.startsWith("en")))!=null?n:e[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),n=this.messages.findIndex(o=>o.id===r.id);if(n===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>{var p,m,u,f,x,C,S,k,T,M;if(s!==n)return o;let a={...o,...r};((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(a.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=r.toolCall)==null?void 0:m.name,d=(u=r.agentMetadata)==null?void 0:u.executionId,l=(f=r.toolCall)==null?void 0:f.id;if(i&&Io(i)&&d&&l&&((x=r.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let h=`${d}:${l}`,w=this.webMcpInflightKeys.has(h),y=this.webMcpResolvedKeys.has(h),E=(C=o.toolCall)==null?void 0:C.name,B=((S=o.agentMetadata)==null?void 0:S.executionId)===d&&((k=o.toolCall)==null?void 0:k.id)===l&&E!==void 0&&Io(E)&&((T=o.toolCall)==null?void 0:T.status)==="complete";(w||y||B)&&(a.agentMetadata={...(M=a.agentMetadata)!=null?M:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,n)=>{var d,l;let o=new Date(r.createdAt).getTime(),s=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=r.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return a!==i?a-i:r.id.localeCompare(n.id)})}};var v=(t,e)=>{let r=document.createElement(t);return e&&(r.className=e),r},Qn=(t,e,r)=>{let n=t.createElement(e);return r&&(n.className=r),n};var Hd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Dd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Od=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Nd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var _d=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Fd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var $d=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Ud=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var qd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var zd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var Vd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var jd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var Gd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Kd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Xd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Jd=[["path",{d:"M20 6 9 17l-5-5"}]];var Qd=[["path",{d:"m6 9 6 6 6-6"}]];var Yd=[["path",{d:"m15 18-6-6 6-6"}]];var Zd=[["path",{d:"m9 18 6-6-6-6"}]];var ec=[["path",{d:"m18 15-6-6-6 6"}]];var al=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var sl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var tc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var rc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var nc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var oc=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var ac=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var sc=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var ic=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var il=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var ll=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var lc=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var dc=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var cc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var pc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var uc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var fc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var mc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var gc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var xc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var yc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var bc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var dl=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var wc=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1"}],["path",{d:"M12 8v13"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"}]];var vc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Cc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Ac=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Sc=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Tc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var cl=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Mc=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var kc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Ec=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Lc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Pc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var pl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Ic=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Rc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Wc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Bc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Hc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Dc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Oc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Nc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var _c=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Fc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var $c=[["path",{d:"M5 12h14"}]];var Uc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var qc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var zc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Vc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var jc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Gc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Kc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Xc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Jc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Qc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Yc=[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}],["path",{d:"M12 17.5v-11"}]];var Zc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var ep=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var tp=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var rp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var np=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var op=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var ap=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var sp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var ip=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var ul=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var lp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var dp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var cp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var pp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var fl=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var up=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var fp=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var mp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var gp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var hp=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var xp=[["path",{d:"M17 14V2"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}]];var yp=[["path",{d:"M7 10v12"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}]];var bp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var wp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var vp=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var ml=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Cp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Ap=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Sp=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Tp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Mp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var kp=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Ep=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Lp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var yw={activity:Hd,"arrow-down":Dd,"arrow-up":Fd,"arrow-up-right":_d,bot:Vd,"chevron-down":Qd,"chevron-up":ec,"chevron-right":Zd,"chevron-left":Yd,check:Jd,clipboard:rc,"clipboard-copy":tc,copy:oc,file:mc,"file-code":pc,"file-spreadsheet":uc,"file-text":fc,"image-plus":Mc,loader:Ic,"loader-circle":pl,mic:_c,paperclip:Vc,"refresh-cw":Zc,search:rp,send:np,"shield-alert":sp,"shield-check":ip,"shield-x":ul,square:up,"thumbs-down":xp,"thumbs-up":yp,upload:Ap,"volume-2":Tp,x:Ep,user:Sp,mail:Wc,phone:Xc,calendar:Kd,clock:nc,building:jd,"map-pin":Bc,lock:Rc,key:Lc,"credit-card":ac,"at-sign":$d,hash:Cc,globe:vc,link:Pc,"circle-check":al,"circle-x":sl,"triangle-alert":ml,info:Ec,ban:Ud,shield:lp,"arrow-left":Od,"arrow-right":Nd,"external-link":lc,ellipsis:ll,"ellipsis-vertical":il,menu:Dc,house:cl,plus:Qc,minus:$c,pencil:Gc,trash:vp,"trash-2":wp,save:tp,download:ic,share:ap,funnel:dl,settings:op,"rotate-cw":ep,maximize:Hc,minimize:Fc,"shopping-cart":cp,"shopping-bag":dp,package:zc,truck:Cp,tag:hp,gift:wc,receipt:Yc,wallet:kp,store:mp,"dollar-sign":sc,percent:Kc,play:Jc,pause:jc,"volume-x":Mp,camera:Xd,image:kc,film:hc,headphones:Ac,"message-circle":Oc,"message-square":Nc,bell:qd,heart:Sc,star:fp,eye:cc,"eye-off":dc,bookmark:zd,"calendar-days":Gd,history:Tc,timer:bp,folder:bc,"folder-open":yc,files:gc,sparkles:fl,zap:Lp,sun:gp,moon:qc,flag:xc,monitor:Uc,smartphone:pp},Ie=(t,e=24,r="currentColor",n=2)=>{let o=yw[t];return o?bw(o,e,r,n):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function bw(t,e,r,n){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var gl={allowedTypes:mo,maxFileSize:10*1024*1024,maxFiles:4};function ww(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vw(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var ca=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=e.allowedTypes)!=null?r:gl.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:gl.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:gl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:gl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var r,n,o,s,a,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(n=(r=this.config).onFileRejected)==null||n.call(r,l,"count");continue}let p=jh(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await Vh(l),u=tl(l)?URL.createObjectURL(l):null,f={id:ww(),file:l,previewUrl:u,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let r=this.attachments.findIndex(d=>d.id===e);if(r===-1)return;let n=this.attachments[r];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,r;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(e=this.config).onAttachmentsChange)==null||r.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let r=tl(e.file),n=v("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",e.id),n.style.width="48px",n.style.height="48px",r&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=vw(e.file.type),d=Ie(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=v("span");l.textContent=Gh(e.file.type,e.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),n.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,r){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:r})}};var Jh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ds(t,e){if(!t)return e;if(!e)return t;let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];Jh(s)&&Jh(o)?r[n]=Ds(s,o):r[n]=o}return r}var yn="min(440px, calc(100vw - 24px))",hl="440px",er={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:yn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Qh(t,e){if(!(!t&&!e))return t?e?Ds(t,e):t:e}function xl(t){var e,r,n,o,s,a,i,d,l,p,m,u,f,x,C,S,k,T,M,h,w;return t?{...er,...t,theme:Qh(er.theme,t.theme),darkTheme:Qh(er.darkTheme,t.darkTheme),launcher:{...er.launcher,...t.launcher,dock:{...(e=er.launcher)==null?void 0:e.dock,...(r=t.launcher)==null?void 0:r.dock},clearChat:{...(n=er.launcher)==null?void 0:n.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...er.copy,...t.copy},sendButton:{...er.sendButton,...t.sendButton},statusIndicator:{...er.statusIndicator,...t.statusIndicator},voiceRecognition:{...er.voiceRecognition,...t.voiceRecognition},features:(()=>{var Ee,Ke,Ne,X,Ue,K,Te,oe;let y=(Ee=er.features)==null?void 0:Ee.artifacts,E=(Ke=t.features)==null?void 0:Ke.artifacts,B=(Ne=er.features)==null?void 0:Ne.scrollToBottom,P=(X=t.features)==null?void 0:X.scrollToBottom,R=(Ue=er.features)==null?void 0:Ue.streamAnimation,O=(K=t.features)==null?void 0:K.streamAnimation,V=(Te=er.features)==null?void 0:Te.askUserQuestion,ne=(oe=t.features)==null?void 0:oe.askUserQuestion,be=y===void 0&&E===void 0?void 0:{...y,...E,layout:{...y==null?void 0:y.layout,...E==null?void 0:E.layout}},Ye=B===void 0&&P===void 0?void 0:{...B,...P},Ge=R===void 0&&O===void 0?void 0:{...R,...O},ve=V===void 0&&ne===void 0?void 0:{...V,...ne,styles:{...V==null?void 0:V.styles,...ne==null?void 0:ne.styles}};return{...er.features,...t.features,...Ye!==void 0?{scrollToBottom:Ye}:{},...be!==void 0?{artifacts:be}:{},...Ge!==void 0?{streamAnimation:Ge}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:er.suggestionChips,suggestionChipsConfig:{...er.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...er.layout,...t.layout,header:{...(a=er.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=er.layout)==null?void 0:d.messages,...(l=t.layout)==null?void 0:l.messages,avatar:{...(m=(p=er.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(f=(u=t.layout)==null?void 0:u.messages)==null?void 0:f.avatar},timestamp:{...(C=(x=er.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(k=(S=t.layout)==null?void 0:S.messages)==null?void 0:k.timestamp}},slots:{...(T=er.layout)==null?void 0:T.slots,...(M=t.layout)==null?void 0:M.slots}},markdown:{...er.markdown,...t.markdown,options:{...(h=er.markdown)==null?void 0:h.options,...(w=t.markdown)==null?void 0:w.options}},messageActions:{...er.messageActions,...t.messageActions}}:er}var Pp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ip={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Rp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:yn,maxWidth:hl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ha(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let r=e.split("."),n=t;for(let o of r){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ha(t,n):n}function yl(t){let e={};function r(n,o){for(let[s,a]of Object.entries(n)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ha(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&r(a,i)}}return r(t.palette,"palette"),r(t.semantic,"semantic"),r(t.components,"components"),e}function Wp(t){let e=[],r=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:r}}function Yh(t,e){let r={...t};for(let[n,o]of Object.entries(e)){let s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?r[n]=Yh(s,o):r[n]=o}return r}function Cw(t,e){return e?Yh(t,e):t}function Da(t,e={}){var o,s,a,i,d,l,p,m,u,f,x,C,S;let r={palette:Pp,semantic:Ip,components:Rp},n={palette:{...r.palette,...t==null?void 0:t.palette,colors:{...r.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...r.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...r.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...r.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...r.palette.radius,...(l=t==null?void 0:t.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...t==null?void 0:t.semantic,colors:{...r.semantic.colors,...(p=t==null?void 0:t.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(x=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=t==null?void 0:t.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(S=t==null?void 0:t.semantic)==null?void 0:S.typography}},components:Cw(r.components,t==null?void 0:t.components)};if(e.validate!==!1){let k=Wp(n);if(!k.valid)throw new Error(`Theme validation failed: ${k.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let k of e.plugins)n=k.transform(n);return n}function bl(t){var C,S,k,T,M,h,w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve,Ee,Ke,Ne,X,Ue,K,Te,oe,xe,Me,Xe,ce,te,le,ut,Ce,he,rt,_e,me,J,ze,Z,ge,z,Re,Ae,fe,pe,Be,Q,_,ke,He,Ve,Je,gt,at,Mt,Xt,G,Jt,st,_t,de,ye,Rt,ar,kt,mr,Ot,Wt,St,Et,sr,ft,dr,wr,Lr,Or,xt,sn,fr,Un,Rr,Zn,Pn,In,ue,I,ee,Se,nt,Qt,Ft,tr,Pr,Nr,wn,Vt,$t,Ir,vn,bo,eo,wo,qn,ln,Rn,Pt,gr,hr,dn,vo,Cn,Wn,cn;let e=yl(t),r={};for(let[W,pn]of Object.entries(e)){let Bn=W.replace(/\./g,"-");r[`--persona-${Bn}`]=pn.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(S=r["--persona-semantic-colors-secondary"])!=null?S:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(k=r["--persona-semantic-colors-accent"])!=null?k:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(T=r["--persona-semantic-colors-surface"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(M=r["--persona-semantic-colors-background"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(h=r["--persona-semantic-colors-container"])!=null?h:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(y=r["--persona-semantic-colors-text-muted"])!=null?y:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(E=r["--persona-semantic-colors-text-inverse"])!=null?E:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(B=r["--persona-semantic-colors-border"])!=null?B:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(P=r["--persona-semantic-colors-divider"])!=null?P:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(R=r["--persona-components-voice-recording-indicator"])!=null?R:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(O=r["--persona-components-voice-recording-background"])!=null?O:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(V=r["--persona-components-voice-processing-icon"])!=null?V:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(ne=r["--persona-components-voice-speaking-icon"])!=null?ne:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(be=r["--persona-components-approval-requested-background"])!=null?be:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ye=r["--persona-components-approval-requested-border"])!=null?Ye:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ge=r["--persona-components-approval-requested-text"])!=null?Ge:r["--persona-palette-colors-gray-900"],r["--persona-approval-approve-bg"]=(ve=r["--persona-components-approval-approve-background"])!=null?ve:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Ee=r["--persona-components-approval-deny-background"])!=null?Ee:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(Ke=r["--persona-components-attachment-image-background"])!=null?Ke:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(Ne=r["--persona-components-attachment-image-border"])!=null?Ne:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(X=r["--persona-semantic-typography-fontFamily"])!=null?X:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(Ue=r["--persona-semantic-typography-fontSize"])!=null?Ue:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(K=r["--persona-semantic-typography-fontWeight"])!=null?K:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Te=r["--persona-semantic-typography-lineHeight"])!=null?Te:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(oe=r["--persona-palette-radius-sm"])!=null?oe:"0.125rem",r["--persona-radius-md"]=(xe=r["--persona-palette-radius-md"])!=null?xe:"0.375rem",r["--persona-radius-lg"]=(Me=r["--persona-palette-radius-lg"])!=null?Me:"0.5rem",r["--persona-radius-xl"]=(Xe=r["--persona-palette-radius-xl"])!=null?Xe:"0.75rem",r["--persona-radius-full"]=(ce=r["--persona-palette-radius-full"])!=null?ce:"9999px",r["--persona-launcher-radius"]=(le=(te=r["--persona-components-launcher-borderRadius"])!=null?te:r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-bg"]=(ut=r["--persona-components-launcher-background"])!=null?ut:r["--persona-primary"],r["--persona-launcher-fg"]=(Ce=r["--persona-components-launcher-foreground"])!=null?Ce:r["--persona-text-inverse"],r["--persona-launcher-border"]=(he=r["--persona-components-launcher-border"])!=null?he:r["--persona-border"],r["--persona-button-primary-bg"]=(rt=r["--persona-components-button-primary-background"])!=null?rt:r["--persona-primary"],r["--persona-button-primary-fg"]=(_e=r["--persona-components-button-primary-foreground"])!=null?_e:r["--persona-text-inverse"],r["--persona-button-radius"]=(J=(me=r["--persona-components-button-primary-borderRadius"])!=null?me:r["--persona-palette-radius-full"])!=null?J:"9999px",r["--persona-panel-radius"]=(Z=(ze=r["--persona-components-panel-borderRadius"])!=null?ze:r["--persona-radius-xl"])!=null?Z:"0.75rem",r["--persona-panel-border"]=(ge=r["--persona-components-panel-border"])!=null?ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Re=(z=r["--persona-components-panel-shadow"])!=null?z:r["--persona-palette-shadows-xl"])!=null?Re:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-input-radius"]=(fe=(Ae=r["--persona-components-input-borderRadius"])!=null?Ae:r["--persona-radius-lg"])!=null?fe:"0.5rem",r["--persona-message-user-radius"]=(Be=(pe=r["--persona-components-message-user-borderRadius"])!=null?pe:r["--persona-radius-lg"])!=null?Be:"0.5rem",r["--persona-message-assistant-radius"]=(_=(Q=r["--persona-components-message-assistant-borderRadius"])!=null?Q:r["--persona-radius-lg"])!=null?_:"0.5rem",r["--persona-header-bg"]=(ke=r["--persona-components-header-background"])!=null?ke:r["--persona-surface"],r["--persona-header-border"]=(He=r["--persona-components-header-border"])!=null?He:r["--persona-divider"],r["--persona-header-icon-bg"]=(Ve=r["--persona-components-header-iconBackground"])!=null?Ve:r["--persona-primary"],r["--persona-header-icon-fg"]=(Je=r["--persona-components-header-iconForeground"])!=null?Je:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(gt=r["--persona-components-header-titleForeground"])!=null?gt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(at=r["--persona-components-header-subtitleForeground"])!=null?at:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Mt=r["--persona-components-header-actionIconForeground"])!=null?Mt:r["--persona-muted"];let n=(Xt=t.components)==null?void 0:Xt.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(G=t.components)==null?void 0:G.introCard;r["--persona-intro-card-bg"]=(Jt=r["--persona-components-introCard-background"])!=null?Jt:r["--persona-surface"],r["--persona-intro-card-radius"]=(st=r["--persona-components-introCard-borderRadius"])!=null?st:"1rem",r["--persona-intro-card-padding"]=(_t=r["--persona-components-introCard-padding"])!=null?_t:"1.5rem",r["--persona-intro-card-shadow"]=(ye=(de=o==null?void 0:o.shadow)!=null?de:r["--persona-components-introCard-shadow"])!=null?ye:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Rt=r["--persona-components-input-background"])!=null?Rt:r["--persona-surface"],r["--persona-input-placeholder"]=(ar=r["--persona-components-input-placeholder"])!=null?ar:r["--persona-text-muted"],r["--persona-message-user-bg"]=(kt=r["--persona-components-message-user-background"])!=null?kt:r["--persona-accent"],r["--persona-message-user-text"]=(mr=r["--persona-components-message-user-text"])!=null?mr:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Ot=r["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Wt=r["--persona-components-message-assistant-background"])!=null?Wt:r["--persona-surface"],r["--persona-message-assistant-text"]=(St=r["--persona-components-message-assistant-text"])!=null?St:r["--persona-text"],r["--persona-message-assistant-border"]=(Et=r["--persona-components-message-assistant-border"])!=null?Et:r["--persona-border"],r["--persona-message-assistant-shadow"]=(sr=r["--persona-components-message-assistant-shadow"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(dr=(ft=r["--persona-components-scrollToBottom-background"])!=null?ft:r["--persona-button-primary-bg"])!=null?dr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Lr=(wr=r["--persona-components-scrollToBottom-foreground"])!=null?wr:r["--persona-button-primary-fg"])!=null?Lr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(Or=r["--persona-components-scrollToBottom-border"])!=null?Or:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(xt=r["--persona-components-scrollToBottom-size"])!=null?xt:"40px",r["--persona-scroll-to-bottom-radius"]=(Un=(fr=(sn=r["--persona-components-scrollToBottom-borderRadius"])!=null?sn:r["--persona-button-radius"])!=null?fr:r["--persona-radius-full"])!=null?Un:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Zn=(Rr=r["--persona-components-scrollToBottom-shadow"])!=null?Rr:r["--persona-palette-shadows-sm"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Pn=r["--persona-components-scrollToBottom-padding"])!=null?Pn:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(In=r["--persona-components-scrollToBottom-gap"])!=null?In:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(I=(ue=r["--persona-components-scrollToBottom-fontSize"])!=null?ue:r["--persona-palette-typography-fontSize-sm"])!=null?I:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(ee=r["--persona-components-scrollToBottom-iconSize"])!=null?ee:"14px",r["--persona-tool-bubble-shadow"]=(Se=r["--persona-components-toolBubble-shadow"])!=null?Se:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(nt=r["--persona-components-reasoningBubble-shadow"])!=null?nt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Qt=r["--persona-components-composer-shadow"])!=null?Qt:"none",r["--persona-md-inline-code-bg"]=(Ft=r["--persona-components-markdown-inlineCode-background"])!=null?Ft:r["--persona-container"],r["--persona-md-inline-code-color"]=(tr=r["--persona-components-markdown-inlineCode-foreground"])!=null?tr:r["--persona-text"],r["--persona-md-link-color"]=(Nr=(Pr=r["--persona-components-markdown-link-foreground"])!=null?Pr:r["--persona-accent"])!=null?Nr:"#0f0f0f";let s=r["--persona-components-markdown-heading-h1-fontSize"];s&&(r["--persona-md-h1-size"]=s);let a=r["--persona-components-markdown-heading-h1-fontWeight"];a&&(r["--persona-md-h1-weight"]=a);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let d=r["--persona-components-markdown-heading-h2-fontWeight"];d&&(r["--persona-md-h2-weight"]=d);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(wn=r["--persona-components-markdown-codeBlock-background"])!=null?wn:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Vt=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Vt:r["--persona-border"],r["--persona-md-code-block-text-color"]=($t=r["--persona-components-markdown-codeBlock-textColor"])!=null?$t:"inherit",r["--persona-md-table-header-bg"]=(Ir=r["--persona-components-markdown-table-headerBackground"])!=null?Ir:r["--persona-container"],r["--persona-md-table-border-color"]=(vn=r["--persona-components-markdown-table-borderColor"])!=null?vn:r["--persona-border"],r["--persona-md-hr-color"]=(bo=r["--persona-components-markdown-hr-color"])!=null?bo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(eo=r["--persona-components-markdown-blockquote-borderColor"])!=null?eo:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(wo=r["--persona-components-markdown-blockquote-background"])!=null?wo:"transparent",r["--persona-md-blockquote-text-color"]=(qn=r["--persona-components-markdown-blockquote-textColor"])!=null?qn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(ln=r["--persona-components-collapsibleWidget-container"])!=null?ln:r["--persona-surface"],r["--cw-surface"]=(Rn=r["--persona-components-collapsibleWidget-surface"])!=null?Rn:r["--persona-surface"],r["--cw-border"]=(Pt=r["--persona-components-collapsibleWidget-border"])!=null?Pt:r["--persona-border"],r["--persona-message-border"]=(gr=r["--persona-components-message-border"])!=null?gr:r["--persona-border"];let p=t.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(r["--persona-icon-btn-bg"]=m.background),m.border&&(r["--persona-icon-btn-border"]=m.border),m.color&&(r["--persona-icon-btn-color"]=m.color),m.padding&&(r["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(r["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(r["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(r["--persona-icon-btn-active-border"]=m.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let W=x.toolbar;W.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=W.iconHoverColor),W.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=W.iconHoverBackground),W.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=W.iconPadding),W.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=W.iconBorderRadius),W.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=W.iconBorder),W.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=W.toggleGroupGap),W.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=W.toggleBorderRadius),W.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=W.copyBackground),W.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=W.copyBorder),W.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=W.copyColor),W.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=W.copyBorderRadius),W.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=W.copyPadding),W.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=W.copyMenuBackground,r["--persona-dropdown-bg"]=(hr=r["--persona-dropdown-bg"])!=null?hr:W.copyMenuBackground),W.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=W.copyMenuBorder,r["--persona-dropdown-border"]=(dn=r["--persona-dropdown-border"])!=null?dn:W.copyMenuBorder),W.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=W.copyMenuShadow,r["--persona-dropdown-shadow"]=(vo=r["--persona-dropdown-shadow"])!=null?vo:W.copyMenuShadow),W.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=W.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Cn=r["--persona-dropdown-radius"])!=null?Cn:W.copyMenuBorderRadius),W.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=W.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Wn=r["--persona-dropdown-item-hover-bg"])!=null?Wn:W.copyMenuItemHoverBackground),W.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=W.iconBackground),W.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=W.toolbarBorder)}if(x!=null&&x.tab){let W=x.tab;W.background&&(r["--persona-artifact-tab-bg"]=W.background),W.activeBackground&&(r["--persona-artifact-tab-active-bg"]=W.activeBackground),W.activeBorder&&(r["--persona-artifact-tab-active-border"]=W.activeBorder),W.borderRadius&&(r["--persona-artifact-tab-radius"]=W.borderRadius),W.textColor&&(r["--persona-artifact-tab-color"]=W.textColor),W.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=W.hoverBackground),W.listBackground&&(r["--persona-artifact-tab-list-bg"]=W.listBackground),W.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=W.listBorderColor),W.listPadding&&(r["--persona-artifact-tab-list-padding"]=W.listPadding)}if(x!=null&&x.pane){let W=x.pane;if(W.toolbarBackground){let pn=(cn=Ha(t,W.toolbarBackground))!=null?cn:W.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pn}}return r}var Zh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Aw={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},ex=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Os=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Sw=t=>{var r;let e=(r=t==null?void 0:t.colorScheme)!=null?r:"light";return e==="light"?"light":e==="dark"?"dark":Os()},Bp=t=>Sw(t),Tw=t=>Da(t),Mw=t=>{var r;let e=Da(void 0,{validate:!1});return Da({...t,palette:{...e.palette,colors:{...Aw.colors,...(r=t==null?void 0:t.palette)==null?void 0:r.colors}}},{validate:!1})},Oa=t=>{let e=Bp(t),r=ex(t==null?void 0:t.theme),n=ex(t==null?void 0:t.darkTheme);return e==="dark"?Mw(Ds(r!=null?r:{},n!=null?n:{})):Tw(r)},kw=t=>bl(t),Ro=(t,e)=>{var s;let r=Oa(e),n=kw(r);for(let[a,i]of Object.entries(n))t.style.setProperty(a,i);let o=(s=e==null?void 0:e.toolCall)==null?void 0:s.shadow;o!==void 0&&t.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},wl=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Os())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>t(Os());r.addEventListener?(r.addEventListener("change",n),e.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),e.push(()=>r.removeListener(n)))}return()=>{e.forEach(r=>r())}};var tx=(function(){"use strict";let t=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:t,afterNodeAdded:t,beforeNodeMorphed:t,afterNodeMorphed:t,beforeNodeRemoved:t,afterNodeRemoved:t,beforeAttributeUpdated:t},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:t,afterHeadMorphed:t},restoreFocus:!0};function r(u,f,x={}){u=p(u);let C=m(f),S=l(u,C,x),k=o(S,()=>i(S,u,C,T=>T.morphStyle==="innerHTML"?(s(T,u,C),Array.from(u.childNodes)):n(T,u,C)));return S.pantry.remove(),k}function n(u,f,x){let C=m(f);return s(u,C,x,f,f.nextSibling),Array.from(C.childNodes)}function o(u,f){var M;if(!u.config.restoreFocus)return f();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return f();let{id:C,selectionStart:S,selectionEnd:k}=x,T=f();return C&&C!==((M=document.activeElement)==null?void 0:M.getAttribute("id"))&&(x=u.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&k&&x.setSelectionRange(S,k),T}let s=(function(){function u(h,w,y,E=null,B=null){w instanceof HTMLTemplateElement&&y instanceof HTMLTemplateElement&&(w=w.content,y=y.content),E||(E=w.firstChild);for(let P of y.childNodes){if(E&&E!=B){let O=x(h,P,E,B);if(O){O!==E&&S(h,E,O),a(O,P,h),E=O.nextSibling;continue}}if(P instanceof Element){let O=P.getAttribute("id");if(h.persistentIds.has(O)){let V=k(w,O,E,h);a(V,P,h),E=V.nextSibling;continue}}let R=f(w,P,E,h);R&&(E=R.nextSibling)}for(;E&&E!=B;){let P=E;E=E.nextSibling,C(h,P)}}function f(h,w,y,E){if(E.callbacks.beforeNodeAdded(w)===!1)return null;if(E.idMap.has(w)){let B=document.createElement(w.tagName);return h.insertBefore(B,y),a(B,w,E),E.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(w,!0);return h.insertBefore(B,y),E.callbacks.afterNodeAdded(B),B}}let x=(function(){function h(E,B,P,R){let O=null,V=B.nextSibling,ne=0,be=P;for(;be&&be!=R;){if(y(be,B)){if(w(E,be,B))return be;O===null&&(E.idMap.has(be)||(O=be))}if(O===null&&V&&y(be,V)&&(ne++,V=V.nextSibling,ne>=2&&(O=void 0)),E.activeElementAndParents.includes(be))break;be=be.nextSibling}return O||null}function w(E,B,P){let R=E.idMap.get(B),O=E.idMap.get(P);if(!O||!R)return!1;for(let V of R)if(O.has(V))return!0;return!1}function y(E,B){var O,V,ne;let P=E,R=B;return P.nodeType===R.nodeType&&P.tagName===R.tagName&&(!((O=P.getAttribute)!=null&&O.call(P,"id"))||((V=P.getAttribute)==null?void 0:V.call(P,"id"))===((ne=R.getAttribute)==null?void 0:ne.call(R,"id")))}return h})();function C(h,w){var y;if(h.idMap.has(w))M(h.pantry,w,null);else{if(h.callbacks.beforeNodeRemoved(w)===!1)return;(y=w.parentNode)==null||y.removeChild(w),h.callbacks.afterNodeRemoved(w)}}function S(h,w,y){let E=w;for(;E&&E!==y;){let B=E;E=E.nextSibling,C(h,B)}return E}function k(h,w,y,E){var P,R;let B=((R=(P=E.target).getAttribute)==null?void 0:R.call(P,"id"))===w&&E.target||E.target.querySelector(`[id="${w}"]`)||E.pantry.querySelector(`[id="${w}"]`);return T(B,E),M(h,B,y),B}function T(h,w){let y=h.getAttribute("id");for(;h=h.parentNode;){let E=w.idMap.get(h);E&&(E.delete(y),E.size||w.idMap.delete(h))}}function M(h,w,y){if(h.moveBefore)try{h.moveBefore(w,y)}catch{h.insertBefore(w,y)}else h.insertBefore(w,y)}return u})(),a=(function(){function u(T,M,h){return h.ignoreActive&&T===document.activeElement?null:(h.callbacks.beforeNodeMorphed(T,M)===!1||(T instanceof HTMLHeadElement&&h.head.ignore||(T instanceof HTMLHeadElement&&h.head.style!=="morph"?d(T,M,h):(f(T,M,h),k(T,h)||s(h,T,M))),h.callbacks.afterNodeMorphed(T,M)),T)}function f(T,M,h){let w=M.nodeType;if(w===1){let y=T,E=M,B=y.attributes,P=E.attributes;for(let R of P)S(R.name,y,"update",h)||y.getAttribute(R.name)!==R.value&&y.setAttribute(R.name,R.value);for(let R=B.length-1;0<=R;R--){let O=B[R];if(O&&!E.hasAttribute(O.name)){if(S(O.name,y,"remove",h))continue;y.removeAttribute(O.name)}}k(y,h)||x(y,E,h)}(w===8||w===3)&&T.nodeValue!==M.nodeValue&&(T.nodeValue=M.nodeValue)}function x(T,M,h){if(T instanceof HTMLInputElement&&M instanceof HTMLInputElement&&M.type!=="file"){let w=M.value,y=T.value;C(T,M,"checked",h),C(T,M,"disabled",h),M.hasAttribute("value")?y!==w&&(S("value",T,"update",h)||(T.setAttribute("value",w),T.value=w)):S("value",T,"remove",h)||(T.value="",T.removeAttribute("value"))}else if(T instanceof HTMLOptionElement&&M instanceof HTMLOptionElement)C(T,M,"selected",h);else if(T instanceof HTMLTextAreaElement&&M instanceof HTMLTextAreaElement){let w=M.value,y=T.value;if(S("value",T,"update",h))return;w!==y&&(T.value=w),T.firstChild&&T.firstChild.nodeValue!==w&&(T.firstChild.nodeValue=w)}}function C(T,M,h,w){let y=M[h],E=T[h];if(y!==E){let B=S(h,T,"update",w);B||(T[h]=M[h]),y?B||T.setAttribute(h,""):S(h,T,"remove",w)||T.removeAttribute(h)}}function S(T,M,h,w){return T==="value"&&w.ignoreActiveValue&&M===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(T,M,h)===!1}function k(T,M){return!!M.ignoreActiveValue&&T===document.activeElement&&T!==document.body}return u})();function i(u,f,x,C){if(u.head.block){let S=f.querySelector("head"),k=x.querySelector("head");if(S&&k){let T=d(S,k,u);return Promise.all(T).then(()=>{let M=Object.assign(u,{head:{block:!1,ignore:!0}});return C(M)})}}return C(u)}function d(u,f,x){let C=[],S=[],k=[],T=[],M=new Map;for(let w of f.children)M.set(w.outerHTML,w);for(let w of u.children){let y=M.has(w.outerHTML),E=x.head.shouldReAppend(w),B=x.head.shouldPreserve(w);y||B?E?S.push(w):(M.delete(w.outerHTML),k.push(w)):x.head.style==="append"?E&&(S.push(w),T.push(w)):x.head.shouldRemove(w)!==!1&&S.push(w)}T.push(...M.values());let h=[];for(let w of T){let y=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(y)!==!1){if("href"in y&&y.href||"src"in y&&y.src){let E,B=new Promise(function(P){E=P});y.addEventListener("load",function(){E()}),h.push(B)}u.appendChild(y),x.callbacks.afterNodeAdded(y),C.push(y)}}for(let w of S)x.callbacks.beforeNodeRemoved(w)!==!1&&(u.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(u,{added:C,kept:k,removed:S}),h}let l=(function(){function u(h,w,y){let{persistentIds:E,idMap:B}=T(h,w),P=f(y),R=P.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:h,newContent:w,config:P,morphStyle:R,ignoreActive:P.ignoreActive,ignoreActiveValue:P.ignoreActiveValue,restoreFocus:P.restoreFocus,idMap:B,persistentIds:E,pantry:x(),activeElementAndParents:C(h),callbacks:P.callbacks,head:P.head}}function f(h){let w=Object.assign({},e);return Object.assign(w,h),w.callbacks=Object.assign({},e.callbacks,h.callbacks),w.head=Object.assign({},e.head,h.head),w}function x(){let h=document.createElement("div");return h.hidden=!0,document.body.insertAdjacentElement("afterend",h),h}function C(h){let w=[],y=document.activeElement;if((y==null?void 0:y.tagName)!=="BODY"&&h.contains(y))for(;y&&(w.push(y),y!==h);)y=y.parentElement;return w}function S(h){var y;let w=Array.from(h.querySelectorAll("[id]"));return(y=h.getAttribute)!=null&&y.call(h,"id")&&w.push(h),w}function k(h,w,y,E){for(let B of E){let P=B.getAttribute("id");if(w.has(P)){let R=B;for(;R;){let O=h.get(R);if(O==null&&(O=new Set,h.set(R,O)),O.add(P),R===y)break;R=R.parentElement}}}}function T(h,w){let y=S(h),E=S(w),B=M(y,E),P=new Map;k(P,B,h,y);let R=w.__idiomorphRoot||w;return k(P,B,R,E),{persistentIds:B,idMap:P}}function M(h,w){let y=new Set,E=new Map;for(let{id:P,tagName:R}of h)E.has(P)?y.add(P):E.set(P,R);let B=new Set;for(let{id:P,tagName:R}of w)B.has(P)?y.add(P):E.get(P)===R&&B.add(P);for(let P of y)B.delete(P);return B}return u})(),{normalizeElement:p,normalizeParent:m}=(function(){let u=new WeakSet;function f(k){return k instanceof Document?k.documentElement:k}function x(k){if(k==null)return document.createElement("div");if(typeof k=="string")return x(S(k));if(u.has(k))return k;if(k instanceof Node){if(k.parentNode)return new C(k);{let T=document.createElement("div");return T.append(k),T}}else{let T=document.createElement("div");for(let M of[...k])T.append(M);return T}}class C{constructor(T){this.originalNode=T,this.realParentNode=T.parentNode,this.previousSibling=T.previousSibling,this.nextSibling=T.nextSibling}get childNodes(){let T=[],M=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;M&&M!=this.nextSibling;)T.push(M),M=M.nextSibling;return T}querySelectorAll(T){return this.childNodes.reduce((M,h)=>{if(h instanceof Element){h.matches(T)&&M.push(h);let w=h.querySelectorAll(T);for(let y=0;y<w.length;y++)M.push(w[y])}return M},[])}insertBefore(T,M){return this.realParentNode.insertBefore(T,M)}moveBefore(T,M){return this.realParentNode.moveBefore(T,M)}get __idiomorphRoot(){return this.originalNode}}function S(k){let T=new DOMParser,M=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(M.match(/<\/html>/)||M.match(/<\/head>/)||M.match(/<\/body>/)){let h=T.parseFromString(k,"text/html");if(M.match(/<\/html>/))return u.add(h),h;{let w=h.firstChild;return w&&u.add(w),w}}else{let w=T.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return u.add(w),w}}return{normalizeElement:f,normalizeParent:x}})();return{morph:r,defaults:e}})();var vl=(t,e,r={})=>{let{preserveTypingAnimation:n=!0}=r;tx.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Cl={index:-1,draft:""};function rx(t){let{direction:e,history:r,currentValue:n,atStart:o,state:s}=t,a=s.index!==-1;if(r.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:n}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<r.length-1){let i=s.index+1;return{handled:!0,value:r[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Cl}}}function nx(t,e){var r,n,o,s,a,i,d,l,p,m,u,f,x,C,S,k,T,M,h,w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve,Ee,Ke,Ne,X,Ue,K;return[t.id,t.role,(n=(r=t.content)==null?void 0:r.length)!=null?n:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=t.llmContent)==null?void 0:l.length)!=null?p:0,(u=(m=t.approval)==null?void 0:m.status)!=null?u:"",(x=(f=t.toolCall)==null?void 0:f.status)!=null?x:"",(S=(C=t.toolCall)==null?void 0:C.name)!=null?S:"",(M=(T=(k=t.toolCall)==null?void 0:k.chunks)==null?void 0:T.length)!=null?M:0,(E=(y=(w=(h=t.toolCall)==null?void 0:h.chunks)==null?void 0:w[t.toolCall.chunks.length-1])==null?void 0:y.slice(-32))!=null?E:"",typeof((B=t.toolCall)==null?void 0:B.args)=="string"?t.toolCall.args.length:(P=t.toolCall)!=null&&P.args?JSON.stringify(t.toolCall.args).length:0,(V=(O=(R=t.reasoning)==null?void 0:R.chunks)==null?void 0:O.length)!=null?V:0,(Ge=(Ye=(be=(ne=t.reasoning)==null?void 0:ne.chunks)==null?void 0:be[t.reasoning.chunks.length-1])==null?void 0:Ye.length)!=null?Ge:0,(Ne=(Ke=(Ee=(ve=t.reasoning)==null?void 0:ve.chunks)==null?void 0:Ee[t.reasoning.chunks.length-1])==null?void 0:Ke.slice(-32))!=null?Ne:"",(Ue=(X=t.contentParts)==null?void 0:X.length)!=null?Ue:0,(K=t.stopReason)!=null?K:"",e].join("\0")}function ox(){return new Map}function ax(t,e,r){let n=t.get(e);return n&&n.fingerprint===r?n.wrapper:null}function sx(t,e,r,n){t.set(e,{fingerprint:r,wrapper:n})}function ix(t,e){for(let r of t.keys())e.has(r)||t.delete(r)}function Al(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ns(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function _s(t,e){return Ns(t)-t.scrollTop<=e}function Sl(t){let{following:e,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=t,p=r-n;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:r}:!e&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Tl(t){let{following:e,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=t;return e&&r<0?"pause":!e&&o&&r>0&&n?"resume":"none"}var Ur={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},qr=1e5,Wo=qr+1;var Fs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ew=["pre","code","a","script","style"],Ml=t=>{var e,r,n,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Fs.type,placeholder:(r=t==null?void 0:t.placeholder)!=null?r:Fs.placeholder,speed:(n=t==null?void 0:t.speed)!=null?n:Fs.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Fs.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Fs.buffer}},dx=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],$s=new Map;for(let t of dx)$s.set(t.name,t);var pa=t=>{$s.set(t.name,t)},Op=t=>{dx.some(e=>e.name===t)||$s.delete(t)},Np=()=>Array.from($s.keys()),Us=(t,e)=>{var r,n;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(r=e[t])!=null?r:null:(n=$s.get(t))!=null?n:null},kl=(t,e,r,n,o)=>{if(!o)return t;if(r!=null&&r.bufferContent)return r.bufferContent(t,n);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
65
- `);return s<0?"":t.slice(0,s)}return t},Lw=(t,e,r,n)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=e,o},Pw=(t,e,r,n)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=e,o},Hp=/\s/,Iw=(t,e)=>{let r=t.parentNode;for(;r;){if(r.nodeType===1){let n=r;if(e.has(n.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Rw=(t,e,r)=>{var d;let n=t.ownerDocument,o=t.parentNode;if(!n||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=0;for(;i<s.length;)if(Hp.test(s[i])){let l=i;for(;l<s.length&&Hp.test(s[l]);)l+=1;a.appendChild(n.createTextNode(s.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Hp.test(s[p]);)l.appendChild(Lw(n,s[p],e,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,t)},Ww=(t,e,r)=>{var d;let n=t.ownerDocument,o=t.parentNode;if(!n||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=n.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(n.createTextNode(l)):(a.appendChild(Pw(n,l,e,r.value)),r.value+=1));o.replaceChild(a,t)},qs=(t,e,r,n)=>{var m,u;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((m=n==null?void 0:n.skipTags)!=null?m:Ew).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Iw(d,s)||i.push(d),d=a.nextNode();let l={value:(u=n==null?void 0:n.startIndex)!=null?u:0},p=e==="char"?Rw:Ww;for(let f of i)p(f,r,l);return o.innerHTML},El=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},zs=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let r=t.createElement("div");return r.className="persona-stream-skeleton-line",e.appendChild(r),e},lx=new WeakMap,Bw=(t,e)=>{var s;if(!t.styles)return;let r=lx.get(e);if(r||(r=new Set,lx.set(e,r)),r.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;r.delete(t.name)}r.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Dp=new WeakMap,Hw=(t,e)=>{if(!t.onAttach)return;let r=Dp.get(e);if(r||(r=new Map,Dp.set(e,r)),r.has(t.name))return;let n=t.onAttach(e);r.set(t.name,n)},cx=t=>{let e=Dp.get(t);if(e){for(let r of e.values())typeof r=="function"&&r();e.clear()}},_p=(t,e)=>{Bw(t,e),Hw(t,e)};function Fp(t,e=qr){let r=t.style.position,n=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=r),t.style.zIndex=n,t.style.isolation=o}}var Vs=0,Bo=null;function $p(t=document){var r;if(Vs++,Vs===1){let n=t.body,s=((r=t.defaultView)!=null?r:window).scrollY||t.documentElement.scrollTop;Bo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{var n;if(!e&&(e=!0,Vs=Math.max(0,Vs-1),Vs===0&&Bo)){let o=t.body,s=(n=t.defaultView)!=null?n:window;o.style.overflow=Bo.originalOverflow,o.style.position=Bo.originalPosition,o.style.top=Bo.originalTop,o.style.width=Bo.originalWidth,s.scrollTo(0,Bo.scrollY),Bo=null}}}var Ll={side:"right",width:"420px",animate:!0,reveal:"resize"},Ar=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="docked"},Ho=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="composer-bar"},kn=t=>{var r,n,o,s,a;let e=(r=t==null?void 0:t.launcher)==null?void 0:r.dock;return{side:(n=e==null?void 0:e.side)!=null?n:Ll.side,width:(o=e==null?void 0:e.width)!=null?o:Ll.width,animate:(s=e==null?void 0:e.animate)!=null?s:Ll.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Ll.reveal}};var $n={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var js=(t,e)=>{let r=v("button");r.type="button",r.innerHTML=`
64
+ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]}),Sx=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Xa=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)&&qo(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 xa(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 Ks((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=wa(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(k=>k.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 xa(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"?Ka():r==="assistant"?ya():`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"?Ka():o==="assistant"?ya():`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=Ka(),s=ya(),a={id:o,role:"user",content:n||dl,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=Ax(y,this.config.errorMessage);if(S){let k={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(k)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,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=ya();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=Ax(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 k=await x.json().catch(()=>null);throw new Error((f=k==null?void 0:k.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,k,E,M,h,C;let n=this.messages.find(v=>v.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 v=(x=e.toolCall)==null?void 0:x.args,T=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(T.length===1){let W=typeof((S=T[0])==null?void 0:S.question)=="string"?T[0].question:"";W&&(a={[W]:r})}}this.markAskUserQuestionResolved(e,a),(k=this.abortController)==null||k.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 v=typeof r=="string"?r:Object.entries(r).map(([T,W])=>`${T}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((T,W)=>{let P=typeof(T==null?void 0:T.question)=="string"?T.question:"";if(!P)return;let R=v[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 v=await this.client.resumeFlow(o,{[s]:r});if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((M=T==null?void 0:T.error)!=null?M:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let T=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(C=(h=this.callbacks).onError)==null||C.call(h,v instanceof Error?v:new Error(String(v)))}}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,v,T,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 k=(T=(v=u.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?T:f,E=this.client.executeWebMcpToolCall(f,(W=u.toolCall)==null?void 0:W.args,S.signal),M;if(!E)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await E}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,Xs(j?"Aborted by cancel()":Sx(N)),x),this.webMcpInflightKeys.delete(y),null}return S.signal.aborted?(this.markWebMcpToolComplete(u,Xs("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(y),null):{dedupeKey:y,resumeKey:k,output:M,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,Xs("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,k,E,M,h,C,v,T,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){(k=(S=this.callbacks).onError)==null||k.call(S,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let P=`${r}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);try{await this.resumeWithToolOutput(r,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(P)}catch(R){(M=(E=this.callbacks).onError)==null||M.call(E,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,Xs("Aborted by cancel()"),a);return}let R=(v=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?v: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,Xs(R||d.aborted?"Aborted by cancel()":Sx(P)),a),R||(W=(T=this.callbacks).onError)==null||W.call(T,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,k,E,M,h,C,v;if(s!==n)return o;let a={...o,...r};if(((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}),o.approval&&r.approval&&o.approval.id===r.approval.id){let T=o.approval,W=r.approval;a.approval={...T,...W,executionId:W.executionId||T.executionId,toolName:W.toolName||T.toolName,description:W.description||T.description,toolType:(u=W.toolType)!=null?u:T.toolType,reason:(f=W.reason)!=null?f:T.reason,parameters:(m=W.parameters)!=null?m:T.parameters}}let i=(y=r.toolCall)==null?void 0:y.name,d=(x=r.agentMetadata)==null?void 0:x.executionId,l=(S=r.toolCall)==null?void 0:S.id;if(i&&qo(i)&&d&&l&&((k=r.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let T=`${d}:${l}`,W=this.webMcpInflightKeys.has(T),P=this.webMcpResolvedKeys.has(T),R=(E=o.toolCall)==null?void 0:E.name,N=((M=o.agentMetadata)==null?void 0:M.executionId)===d&&((h=o.toolCall)==null?void 0:h.id)===l&&R!==void 0&&qo(R)&&((C=o.toolCall)==null?void 0:C.status)==="complete";(W||P||N)&&(a.agentMetadata={...(v=a.agentMetadata)!=null?v:{},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 w=(t,e)=>{let r=document.createElement(t);return e&&(r.className=e),r},lo=(t,e,r)=>{let n=t.createElement(e);return r&&(n.className=r),n};var Jd=[["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 Qd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Yd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Zd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var ec=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var tc=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var rc=[["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 nc=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var oc=[["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 ac=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var sc=[["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 ic=[["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 lc=[["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 dc=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var cc=[["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 pc=[["path",{d:"M20 6 9 17l-5-5"}]];var uc=[["path",{d:"m6 9 6 6 6-6"}]];var fc=[["path",{d:"m15 18-6-6 6-6"}]];var mc=[["path",{d:"m9 18 6-6-6-6"}]];var gc=[["path",{d:"m18 15-6-6-6 6"}]];var ml=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var gl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var hc=[["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 xc=[["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 yc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var bc=[["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 wc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var vc=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Cc=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var hl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var xl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ac=[["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 Sc=[["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 Tc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Mc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var kc=[["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 Ec=[["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 Lc=[["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 Pc=[["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 Ic=[["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 Rc=[["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 Wc=[["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 Hc=[["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 yl=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Bc=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1"}],["path",{d:"M12 8v13"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"}]];var Dc=[["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 Oc=[["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 Nc=[["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 _c=[["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 Fc=[["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 bl=[["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 $c=[["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 Uc=[["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 qc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var zc=[["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 Vc=[["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 wl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var jc=[["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 Gc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Kc=[["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 Xc=[["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 Jc=[["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 Qc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Yc=[["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 Zc=[["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 ep=[["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 tp=[["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 rp=[["path",{d:"M5 12h14"}]];var np=[["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 op=[["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 ap=[["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 sp=[["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 ip=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var lp=[["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 dp=[["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 cp=[["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 pp=[["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 up=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var fp=[["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 mp=[["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 gp=[["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 hp=[["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 xp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var yp=[["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 bp=[["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 wp=[["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 vp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Cp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var vl=[["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 Ap=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Sp=[["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 Tp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Mp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Cl=[["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 kp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Ep=[["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 Lp=[["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 Pp=[["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 Ip=[["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 Rp=[["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 Wp=[["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 Hp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Bp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Dp=[["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 Al=[["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 Op=[["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 Np=[["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 _p=[["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 Fp=[["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 $p=[["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 Up=[["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 qp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var zp=[["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 av={activity:Jd,"arrow-down":Qd,"arrow-up":tc,"arrow-up-right":ec,bot:sc,"chevron-down":uc,"chevron-up":gc,"chevron-right":mc,"chevron-left":fc,check:pc,clipboard:xc,"clipboard-copy":hc,copy:bc,file:Lc,"file-code":Mc,"file-spreadsheet":kc,"file-text":Ec,"image-plus":$c,loader:jc,"loader-circle":wl,mic:ep,paperclip:sp,"refresh-cw":mp,search:xp,send:yp,"shield-alert":vp,"shield-check":Cp,"shield-x":vl,square:kp,"thumbs-down":Rp,"thumbs-up":Wp,upload:Np,"volume-2":Fp,x:qp,user:_p,mail:Kc,phone:cp,calendar:dc,clock:yc,building:ic,"map-pin":Xc,lock:Gc,key:zc,"credit-card":wc,"at-sign":rc,hash:Oc,globe:Dc,link:Vc,"circle-check":ml,"circle-x":gl,"triangle-alert":Al,info:qc,ban:nc,shield:Ap,"arrow-left":Yd,"arrow-right":Zd,"external-link":Ac,ellipsis:xl,"ellipsis-vertical":hl,menu:Qc,house:bl,plus:up,minus:rp,pencil:lp,trash:Dp,"trash-2":Bp,save:hp,download:Cc,share:wp,funnel:yl,settings:bp,"rotate-cw":gp,maximize:Jc,minimize:tp,"shopping-cart":Tp,"shopping-bag":Sp,package:ap,truck:Op,tag:Ip,gift:Bc,receipt:fp,wallet:Up,store:Lp,"dollar-sign":vc,percent:dp,play:pp,pause:ip,"volume-x":$p,camera:cc,image:Uc,film:Ic,headphones:Nc,"message-circle":Yc,"message-square":Zc,bell:oc,heart:_c,star:Ep,eye:Tc,"eye-off":Sc,bookmark:ac,"calendar-days":lc,history:Fc,timer:Hp,folder:Hc,"folder-open":Wc,files:Pc,sparkles:Cl,zap:zp,sun:Pp,moon:op,flag:Rc,monitor:np,smartphone:Mp},Ie=(t,e=24,r="currentColor",n=2)=>{let o=av[t];return o?sv(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 sv(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 Sl={allowedTypes:So,maxFileSize:10*1024*1024,maxFiles:4};function iv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function lv(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 va=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var r,n,o;this.config={allowedTypes:(r=e.allowedTypes)!=null?r:Sl.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:Sl.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Sl.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:Sl.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=vx(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 wx(l),f=cl(l)?URL.createObjectURL(l):null,m={id:iv(),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=cl(e.file),n=w("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=w("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=w("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=lv(e.file.type),d=Ie(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=w("span");l.textContent=Cx(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=w("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,r){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:r})}};var Tx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Js(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]=Js(s,o):r[n]=o}return r}var Tn="min(440px, calc(100vw - 24px))",Tl="440px",er={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Tn,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 Mx(t,e){if(!(!t&&!e))return t?e?Js(t,e):t:e}function Ml(t){var e,r,n,o,s,a,i,d,l,p,u,f,m,y,x,S,k,E,M,h,C;return t?{...er,...t,theme:Mx(er.theme,t.theme),darkTheme:Mx(er.darkTheme,t.darkTheme),launcher:{...er.launcher,...t.launcher,dock:{...(e=er.launcher)==null?void 0:e.dock,...(r=t.launcher)==null?void 0:r.dock},clearChat:{...(n=er.launcher)==null?void 0:n.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...er.copy,...t.copy},sendButton:{...er.sendButton,...t.sendButton},statusIndicator:{...er.statusIndicator,...t.statusIndicator},voiceRecognition:{...er.voiceRecognition,...t.voiceRecognition},features:(()=>{var Z,ne,ee,we,Q,X,fe,Le,me,te;let v=(Z=er.features)==null?void 0:Z.artifacts,T=(ne=t.features)==null?void 0:ne.artifacts,W=(ee=er.features)==null?void 0:ee.scrollToBottom,P=(we=t.features)==null?void 0:we.scrollToBottom,R=(Q=er.features)==null?void 0:Q.scrollBehavior,N=(X=t.features)==null?void 0:X.scrollBehavior,j=(fe=er.features)==null?void 0:fe.streamAnimation,ce=(Le=t.features)==null?void 0:Le.streamAnimation,be=(me=er.features)==null?void 0:me.askUserQuestion,Ze=(te=t.features)==null?void 0:te.askUserQuestion,Se=v===void 0&&T===void 0?void 0:{...v,...T,layout:{...v==null?void 0:v.layout,...T==null?void 0:T.layout}},Ne=W===void 0&&P===void 0?void 0:{...W,...P},Ce=R===void 0&&N===void 0?void 0:{...R,...N},Fe=j===void 0&&ce===void 0?void 0:{...j,...ce},We=be===void 0&&Ze===void 0?void 0:{...be,...Ze,styles:{...be==null?void 0:be.styles,...Ze==null?void 0:Ze.styles}};return{...er.features,...t.features,...Ne!==void 0?{scrollToBottom:Ne}:{},...Ce!==void 0?{scrollBehavior:Ce}:{},...Se!==void 0?{artifacts:Se}:{},...Fe!==void 0?{streamAnimation:Fe}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:er.suggestionChips,suggestionChipsConfig:{...er.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...er.layout,...t.layout,header:{...(a=er.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=er.layout)==null?void 0:d.messages,...(l=t.layout)==null?void 0:l.messages,avatar:{...(u=(p=er.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=er.layout)==null?void 0:y.messages)==null?void 0:x.timestamp,...(k=(S=t.layout)==null?void 0:S.messages)==null?void 0:k.timestamp}},slots:{...(E=er.layout)==null?void 0:E.slots,...(M=t.layout)==null?void 0:M.slots}},markdown:{...er.markdown,...t.markdown,options:{...(h=er.markdown)==null?void 0:h.options,...(C=t.markdown)==null?void 0:C.options}},messageActions:{...er.messageActions,...t.messageActions}}:er}var Vp={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"}},jp={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"}},Gp={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:Tn,maxWidth:Tl,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 Ja(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."))?Ja(t,n):n}function kl(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=Ja(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 Kp(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 kx(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]=kx(s,o):r[n]=o}return r}function dv(t,e){return e?kx(t,e):t}function Qa(t,e={}){var o,s,a,i,d,l,p,u,f,m,y,x,S;let r={palette:Vp,semantic:jp,components:Gp},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:dv(r.components,t==null?void 0:t.components)};if(e.validate!==!1){let k=Kp(n);if(!k.valid)throw new Error(`Theme validation failed: ${k.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let k of e.plugins)n=k.transform(n);return n}function El(t){var x,S,k,E,M,h,C,v,T,W,P,R,N,j,ce,be,Ze,Se,Ne,Ce,Fe,We,Z,ne,ee,we,Q,X,fe,Le,me,te,le,ht,mt,Re,ye,ot,He,G,he,K,wt,U,J,qe,se,ie,Be,Xe,B,xe,De,rt,ze,je,at,Rt,tr,cr,Y,vt,ut,Te,ue,pt,hr,xt,vr,Dr,yt,Dt,it,Xt,Cr,pr,xr,Er,fn,Wt,zr,wr,kn,ln,Lt,Jn,En,Ge,I,pe,Oe,zt,st,Vt,or,fr,Pt,Vr,Jt,jr,$n,po,Po,mn,Qt,Yr,Ln,Io,uo,Ro,Qn,gn,Un,Ht,Ar,Sr,hn,Wo;let e=kl(t),r={};for(let[Me,Pn]of Object.entries(e)){let In=Me.replace(/\./g,"-");r[`--persona-${In}`]=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"]=(k=r["--persona-semantic-colors-accent"])!=null?k:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(E=r["--persona-semantic-colors-surface"])!=null?E:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(M=r["--persona-semantic-colors-background"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(h=r["--persona-semantic-colors-container"])!=null?h:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(C=r["--persona-semantic-colors-text"])!=null?C:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(T=r["--persona-semantic-colors-text-inverse"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(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"]=(ce=r["--persona-components-voice-speaking-icon"])!=null?ce:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(be=r["--persona-components-approval-requested-background"])!=null?be:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ze=r["--persona-components-approval-requested-border"])!=null?Ze:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Se=r["--persona-components-approval-requested-text"])!=null?Se:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ne=r["--persona-components-approval-requested-shadow"])!=null?Ne:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-approval-approve-bg"]=(Ce=r["--persona-components-approval-approve-background"])!=null?Ce:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Fe=r["--persona-components-approval-deny-background"])!=null?Fe:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(We=r["--persona-components-attachment-image-background"])!=null?We:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(Z=r["--persona-components-attachment-image-border"])!=null?Z:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(ne=r["--persona-semantic-typography-fontFamily"])!=null?ne:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(ee=r["--persona-semantic-typography-fontSize"])!=null?ee:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(we=r["--persona-semantic-typography-fontWeight"])!=null?we:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Q=r["--persona-semantic-typography-lineHeight"])!=null?Q: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"]=(X=r["--persona-palette-radius-sm"])!=null?X:"0.125rem",r["--persona-radius-md"]=(fe=r["--persona-palette-radius-md"])!=null?fe:"0.375rem",r["--persona-radius-lg"]=(Le=r["--persona-palette-radius-lg"])!=null?Le:"0.5rem",r["--persona-radius-xl"]=(me=r["--persona-palette-radius-xl"])!=null?me:"0.75rem",r["--persona-radius-full"]=(te=r["--persona-palette-radius-full"])!=null?te:"9999px",r["--persona-launcher-radius"]=(ht=(le=r["--persona-components-launcher-borderRadius"])!=null?le:r["--persona-palette-radius-full"])!=null?ht:"9999px",r["--persona-launcher-bg"]=(mt=r["--persona-components-launcher-background"])!=null?mt:r["--persona-primary"],r["--persona-launcher-fg"]=(Re=r["--persona-components-launcher-foreground"])!=null?Re:r["--persona-text-inverse"],r["--persona-launcher-border"]=(ye=r["--persona-components-launcher-border"])!=null?ye:r["--persona-border"],r["--persona-button-primary-bg"]=(ot=r["--persona-components-button-primary-background"])!=null?ot: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"]=(he=(G=r["--persona-components-button-primary-borderRadius"])!=null?G:r["--persona-palette-radius-full"])!=null?he:"9999px",r["--persona-panel-radius"]=(wt=(K=r["--persona-components-panel-borderRadius"])!=null?K:r["--persona-radius-xl"])!=null?wt:"0.75rem",r["--persona-panel-border"]=(U=r["--persona-components-panel-border"])!=null?U:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(qe=(J=r["--persona-components-panel-shadow"])!=null?J:r["--persona-palette-shadows-xl"])!=null?qe:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(se=r["--persona-components-launcher-shadow"])!=null?se:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Be=(ie=r["--persona-components-input-borderRadius"])!=null?ie:r["--persona-radius-lg"])!=null?Be:"0.5rem",r["--persona-message-user-radius"]=(B=(Xe=r["--persona-components-message-user-borderRadius"])!=null?Xe:r["--persona-radius-lg"])!=null?B:"0.5rem",r["--persona-message-assistant-radius"]=(De=(xe=r["--persona-components-message-assistant-borderRadius"])!=null?xe:r["--persona-radius-lg"])!=null?De:"0.5rem",r["--persona-header-bg"]=(rt=r["--persona-components-header-background"])!=null?rt:r["--persona-surface"],r["--persona-header-border"]=(ze=r["--persona-components-header-border"])!=null?ze:r["--persona-divider"],r["--persona-header-icon-bg"]=(je=r["--persona-components-header-iconBackground"])!=null?je:r["--persona-primary"],r["--persona-header-icon-fg"]=(at=r["--persona-components-header-iconForeground"])!=null?at:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Rt=r["--persona-components-header-titleForeground"])!=null?Rt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(tr=r["--persona-components-header-subtitleForeground"])!=null?tr:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(cr=r["--persona-components-header-actionIconForeground"])!=null?cr:r["--persona-muted"];let n=(Y=t.components)==null?void 0:Y.header;n!=null&&n.shadow&&(r["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(r["--persona-header-border-bottom"]=n.borderBottom);let o=(vt=t.components)==null?void 0:vt.introCard;r["--persona-intro-card-bg"]=(ut=r["--persona-components-introCard-background"])!=null?ut:r["--persona-surface"],r["--persona-intro-card-radius"]=(Te=r["--persona-components-introCard-borderRadius"])!=null?Te:"1rem",r["--persona-intro-card-padding"]=(ue=r["--persona-components-introCard-padding"])!=null?ue:"1.5rem",r["--persona-intro-card-shadow"]=(hr=(pt=o==null?void 0:o.shadow)!=null?pt:r["--persona-components-introCard-shadow"])!=null?hr:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(xt=r["--persona-components-input-background"])!=null?xt:r["--persona-surface"],r["--persona-input-placeholder"]=(vr=r["--persona-components-input-placeholder"])!=null?vr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Dr=r["--persona-components-message-user-background"])!=null?Dr:r["--persona-accent"],r["--persona-message-user-text"]=(yt=r["--persona-components-message-user-text"])!=null?yt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Dt=r["--persona-components-message-user-shadow"])!=null?Dt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(it=r["--persona-components-message-assistant-background"])!=null?it:r["--persona-surface"],r["--persona-message-assistant-text"]=(Xt=r["--persona-components-message-assistant-text"])!=null?Xt:r["--persona-text"],r["--persona-message-assistant-border"]=(Cr=r["--persona-components-message-assistant-border"])!=null?Cr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(pr=r["--persona-components-message-assistant-shadow"])!=null?pr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(Er=(xr=r["--persona-components-scrollToBottom-background"])!=null?xr:r["--persona-button-primary-bg"])!=null?Er:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Wt=(fn=r["--persona-components-scrollToBottom-foreground"])!=null?fn:r["--persona-button-primary-fg"])!=null?Wt:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(zr=r["--persona-components-scrollToBottom-border"])!=null?zr:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(wr=r["--persona-components-scrollToBottom-size"])!=null?wr:"40px",r["--persona-scroll-to-bottom-radius"]=(Lt=(ln=(kn=r["--persona-components-scrollToBottom-borderRadius"])!=null?kn:r["--persona-button-radius"])!=null?ln:r["--persona-radius-full"])!=null?Lt:"9999px",r["--persona-scroll-to-bottom-shadow"]=(En=(Jn=r["--persona-components-scrollToBottom-shadow"])!=null?Jn:r["--persona-palette-shadows-sm"])!=null?En:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Ge=r["--persona-components-scrollToBottom-padding"])!=null?Ge:"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"]=(Oe=(pe=r["--persona-components-scrollToBottom-fontSize"])!=null?pe:r["--persona-palette-typography-fontSize-sm"])!=null?Oe:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(zt=r["--persona-components-scrollToBottom-iconSize"])!=null?zt:"14px",r["--persona-tool-bubble-shadow"]=(st=r["--persona-components-toolBubble-shadow"])!=null?st:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(Vt=r["--persona-components-reasoningBubble-shadow"])!=null?Vt:"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"]=(fr=r["--persona-components-markdown-inlineCode-background"])!=null?fr:r["--persona-container"],r["--persona-md-inline-code-color"]=(Pt=r["--persona-components-markdown-inlineCode-foreground"])!=null?Pt:r["--persona-text"],r["--persona-md-link-color"]=(Jt=(Vr=r["--persona-components-markdown-link-foreground"])!=null?Vr: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"]=(jr=r["--persona-components-markdown-codeBlock-background"])!=null?jr:r["--persona-container"],r["--persona-md-code-block-border-color"]=($n=r["--persona-components-markdown-codeBlock-borderColor"])!=null?$n:r["--persona-border"],r["--persona-md-code-block-text-color"]=(po=r["--persona-components-markdown-codeBlock-textColor"])!=null?po:"inherit",r["--persona-md-table-header-bg"]=(Po=r["--persona-components-markdown-table-headerBackground"])!=null?Po:r["--persona-container"],r["--persona-md-table-border-color"]=(mn=r["--persona-components-markdown-table-borderColor"])!=null?mn:r["--persona-border"],r["--persona-md-hr-color"]=(Qt=r["--persona-components-markdown-hr-color"])!=null?Qt:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(Yr=r["--persona-components-markdown-blockquote-borderColor"])!=null?Yr: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"]=(Io=r["--persona-components-markdown-blockquote-textColor"])!=null?Io:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(uo=r["--persona-components-collapsibleWidget-container"])!=null?uo:r["--persona-surface"],r["--cw-surface"]=(Ro=r["--persona-components-collapsibleWidget-surface"])!=null?Ro:r["--persona-surface"],r["--cw-border"]=(Qn=r["--persona-components-collapsibleWidget-border"])!=null?Qn:r["--persona-border"],r["--persona-message-border"]=(gn=r["--persona-components-message-border"])!=null?gn: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 Me=y.toolbar;Me.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=Me.iconHoverColor),Me.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=Me.iconHoverBackground),Me.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=Me.iconPadding),Me.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=Me.iconBorderRadius),Me.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=Me.iconBorder),Me.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=Me.toggleGroupGap),Me.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=Me.toggleBorderRadius),Me.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=Me.copyBackground),Me.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=Me.copyBorder),Me.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=Me.copyColor),Me.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=Me.copyBorderRadius),Me.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=Me.copyPadding),Me.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=Me.copyMenuBackground,r["--persona-dropdown-bg"]=(Un=r["--persona-dropdown-bg"])!=null?Un:Me.copyMenuBackground),Me.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=Me.copyMenuBorder,r["--persona-dropdown-border"]=(Ht=r["--persona-dropdown-border"])!=null?Ht:Me.copyMenuBorder),Me.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=Me.copyMenuShadow,r["--persona-dropdown-shadow"]=(Ar=r["--persona-dropdown-shadow"])!=null?Ar:Me.copyMenuShadow),Me.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=Me.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Sr=r["--persona-dropdown-radius"])!=null?Sr:Me.copyMenuBorderRadius),Me.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Me.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(hn=r["--persona-dropdown-item-hover-bg"])!=null?hn:Me.copyMenuItemHoverBackground),Me.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=Me.iconBackground),Me.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=Me.toolbarBorder)}if(y!=null&&y.tab){let Me=y.tab;Me.background&&(r["--persona-artifact-tab-bg"]=Me.background),Me.activeBackground&&(r["--persona-artifact-tab-active-bg"]=Me.activeBackground),Me.activeBorder&&(r["--persona-artifact-tab-active-border"]=Me.activeBorder),Me.borderRadius&&(r["--persona-artifact-tab-radius"]=Me.borderRadius),Me.textColor&&(r["--persona-artifact-tab-color"]=Me.textColor),Me.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=Me.hoverBackground),Me.listBackground&&(r["--persona-artifact-tab-list-bg"]=Me.listBackground),Me.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=Me.listBorderColor),Me.listPadding&&(r["--persona-artifact-tab-list-padding"]=Me.listPadding)}if(y!=null&&y.pane){let Me=y.pane;if(Me.toolbarBackground){let Pn=(Wo=Ja(t,Me.toolbarBackground))!=null?Wo:Me.toolbarBackground;r["--persona-artifact-toolbar-bg"]=Pn}}return r}var Ex={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var cv={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"}}},Lx=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Qs=()=>{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"},pv=t=>{var r;let e=(r=t==null?void 0:t.colorScheme)!=null?r:"light";return e==="light"?"light":e==="dark"?"dark":Qs()},Xp=t=>pv(t),uv=t=>Qa(t),fv=t=>{var r;let e=Qa(void 0,{validate:!1});return Qa({...t,palette:{...e.palette,colors:{...cv.colors,...(r=t==null?void 0:t.palette)==null?void 0:r.colors}}},{validate:!1})},Ya=t=>{let e=Xp(t),r=Lx(t==null?void 0:t.theme),n=Lx(t==null?void 0:t.darkTheme);return e==="dark"?fv(Js(r!=null?r:{},n!=null?n:{})):uv(r)},mv=t=>El(t),zo=(t,e)=>{let r=Ya(e),n=mv(r);for(let[o,s]of Object.entries(n))t.style.setProperty(o,s)},Ll=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Qs())});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(Qs());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 Px=(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),k=o(S,()=>i(S,f,x,E=>E.morphStyle==="innerHTML"?(s(E,f,x),Array.from(f.childNodes)):n(E,f,x)));return S.pantry.remove(),k}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 M;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:k}=y,E=m();return x&&x!==((M=document.activeElement)==null?void 0:M.getAttribute("id"))&&(y=f.target.querySelector(`[id="${x}"]`),y==null||y.focus()),y&&!y.selectionEnd&&k&&y.setSelectionRange(S,k),E}let s=(function(){function f(h,C,v,T=null,W=null){C instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(C=C.content,v=v.content),T||(T=C.firstChild);for(let P of v.childNodes){if(T&&T!=W){let N=y(h,P,T,W);if(N){N!==T&&S(h,T,N),a(N,P,h),T=N.nextSibling;continue}}if(P instanceof Element){let N=P.getAttribute("id");if(h.persistentIds.has(N)){let j=k(C,N,T,h);a(j,P,h),T=j.nextSibling;continue}}let R=m(C,P,T,h);R&&(T=R.nextSibling)}for(;T&&T!=W;){let P=T;T=T.nextSibling,x(h,P)}}function m(h,C,v,T){if(T.callbacks.beforeNodeAdded(C)===!1)return null;if(T.idMap.has(C)){let W=document.createElement(C.tagName);return h.insertBefore(W,v),a(W,C,T),T.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(C,!0);return h.insertBefore(W,v),T.callbacks.afterNodeAdded(W),W}}let y=(function(){function h(T,W,P,R){let N=null,j=W.nextSibling,ce=0,be=P;for(;be&&be!=R;){if(v(be,W)){if(C(T,be,W))return be;N===null&&(T.idMap.has(be)||(N=be))}if(N===null&&j&&v(be,j)&&(ce++,j=j.nextSibling,ce>=2&&(N=void 0)),T.activeElementAndParents.includes(be))break;be=be.nextSibling}return N||null}function C(T,W,P){let R=T.idMap.get(W),N=T.idMap.get(P);if(!N||!R)return!1;for(let j of R)if(N.has(j))return!0;return!1}function v(T,W){var N,j,ce;let P=T,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"))===((ce=R.getAttribute)==null?void 0:ce.call(R,"id")))}return h})();function x(h,C){var v;if(h.idMap.has(C))M(h.pantry,C,null);else{if(h.callbacks.beforeNodeRemoved(C)===!1)return;(v=C.parentNode)==null||v.removeChild(C),h.callbacks.afterNodeRemoved(C)}}function S(h,C,v){let T=C;for(;T&&T!==v;){let W=T;T=T.nextSibling,x(h,W)}return T}function k(h,C,v,T){var P,R;let W=((R=(P=T.target).getAttribute)==null?void 0:R.call(P,"id"))===C&&T.target||T.target.querySelector(`[id="${C}"]`)||T.pantry.querySelector(`[id="${C}"]`);return E(W,T),M(h,W,v),W}function E(h,C){let v=h.getAttribute("id");for(;h=h.parentNode;){let T=C.idMap.get(h);T&&(T.delete(v),T.size||C.idMap.delete(h))}}function M(h,C,v){if(h.moveBefore)try{h.moveBefore(C,v)}catch{h.insertBefore(C,v)}else h.insertBefore(C,v)}return f})(),a=(function(){function f(E,M,h){return h.ignoreActive&&E===document.activeElement?null:(h.callbacks.beforeNodeMorphed(E,M)===!1||(E instanceof HTMLHeadElement&&h.head.ignore||(E instanceof HTMLHeadElement&&h.head.style!=="morph"?d(E,M,h):(m(E,M,h),k(E,h)||s(h,E,M))),h.callbacks.afterNodeMorphed(E,M)),E)}function m(E,M,h){let C=M.nodeType;if(C===1){let v=E,T=M,W=v.attributes,P=T.attributes;for(let R of P)S(R.name,v,"update",h)||v.getAttribute(R.name)!==R.value&&v.setAttribute(R.name,R.value);for(let R=W.length-1;0<=R;R--){let N=W[R];if(N&&!T.hasAttribute(N.name)){if(S(N.name,v,"remove",h))continue;v.removeAttribute(N.name)}}k(v,h)||y(v,T,h)}(C===8||C===3)&&E.nodeValue!==M.nodeValue&&(E.nodeValue=M.nodeValue)}function y(E,M,h){if(E instanceof HTMLInputElement&&M instanceof HTMLInputElement&&M.type!=="file"){let C=M.value,v=E.value;x(E,M,"checked",h),x(E,M,"disabled",h),M.hasAttribute("value")?v!==C&&(S("value",E,"update",h)||(E.setAttribute("value",C),E.value=C)):S("value",E,"remove",h)||(E.value="",E.removeAttribute("value"))}else if(E instanceof HTMLOptionElement&&M instanceof HTMLOptionElement)x(E,M,"selected",h);else if(E instanceof HTMLTextAreaElement&&M instanceof HTMLTextAreaElement){let C=M.value,v=E.value;if(S("value",E,"update",h))return;C!==v&&(E.value=C),E.firstChild&&E.firstChild.nodeValue!==C&&(E.firstChild.nodeValue=C)}}function x(E,M,h,C){let v=M[h],T=E[h];if(v!==T){let W=S(h,E,"update",C);W||(E[h]=M[h]),v?W||E.setAttribute(h,""):S(h,E,"remove",C)||E.removeAttribute(h)}}function S(E,M,h,C){return E==="value"&&C.ignoreActiveValue&&M===document.activeElement?!0:C.callbacks.beforeAttributeUpdated(E,M,h)===!1}function k(E,M){return!!M.ignoreActiveValue&&E===document.activeElement&&E!==document.body}return f})();function i(f,m,y,x){if(f.head.block){let S=m.querySelector("head"),k=y.querySelector("head");if(S&&k){let E=d(S,k,f);return Promise.all(E).then(()=>{let M=Object.assign(f,{head:{block:!1,ignore:!0}});return x(M)})}}return x(f)}function d(f,m,y){let x=[],S=[],k=[],E=[],M=new Map;for(let C of m.children)M.set(C.outerHTML,C);for(let C of f.children){let v=M.has(C.outerHTML),T=y.head.shouldReAppend(C),W=y.head.shouldPreserve(C);v||W?T?S.push(C):(M.delete(C.outerHTML),k.push(C)):y.head.style==="append"?T&&(S.push(C),E.push(C)):y.head.shouldRemove(C)!==!1&&S.push(C)}E.push(...M.values());let h=[];for(let C of E){let v=document.createRange().createContextualFragment(C.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let T,W=new Promise(function(P){T=P});v.addEventListener("load",function(){T()}),h.push(W)}f.appendChild(v),y.callbacks.afterNodeAdded(v),x.push(v)}}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:k,removed:S}),h}let l=(function(){function f(h,C,v){let{persistentIds:T,idMap:W}=E(h,C),P=m(v),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:T,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=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&h.contains(v))for(;v&&(C.push(v),v!==h);)v=v.parentElement;return C}function S(h){var v;let C=Array.from(h.querySelectorAll("[id]"));return(v=h.getAttribute)!=null&&v.call(h,"id")&&C.push(h),C}function k(h,C,v,T){for(let W of T){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===v)break;R=R.parentElement}}}}function E(h,C){let v=S(h),T=S(C),W=M(v,T),P=new Map;k(P,W,h,v);let R=C.__idiomorphRoot||C;return k(P,W,R,T),{persistentIds:W,idMap:P}}function M(h,C){let v=new Set,T=new Map;for(let{id:P,tagName:R}of h)T.has(P)?v.add(P):T.set(P,R);let W=new Set;for(let{id:P,tagName:R}of C)W.has(P)?v.add(P):T.get(P)===R&&W.add(P);for(let P of v)W.delete(P);return W}return f})(),{normalizeElement:p,normalizeParent:u}=(function(){let f=new WeakSet;function m(k){return k instanceof Document?k.documentElement:k}function y(k){if(k==null)return document.createElement("div");if(typeof k=="string")return y(S(k));if(f.has(k))return k;if(k instanceof Node){if(k.parentNode)return new x(k);{let E=document.createElement("div");return E.append(k),E}}else{let E=document.createElement("div");for(let M of[...k])E.append(M);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=[],M=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;M&&M!=this.nextSibling;)E.push(M),M=M.nextSibling;return E}querySelectorAll(E){return this.childNodes.reduce((M,h)=>{if(h instanceof Element){h.matches(E)&&M.push(h);let C=h.querySelectorAll(E);for(let v=0;v<C.length;v++)M.push(C[v])}return M},[])}insertBefore(E,M){return this.realParentNode.insertBefore(E,M)}moveBefore(E,M){return this.realParentNode.moveBefore(E,M)}get __idiomorphRoot(){return this.originalNode}}function S(k){let E=new DOMParser,M=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(M.match(/<\/html>/)||M.match(/<\/head>/)||M.match(/<\/body>/)){let h=E.parseFromString(k,"text/html");if(M.match(/<\/html>/))return f.add(h),h;{let C=h.firstChild;return C&&f.add(C),C}}else{let C=E.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return f.add(C),C}}return{normalizeElement:m,normalizeParent:y}})();return{morph:r,defaults:e}})();var Pl=(t,e,r={})=>{let{preserveTypingAnimation:n=!0}=r;Px.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 Il={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:{...Il}}}function Rx(t,e){var r,n,o,s,a,i,d,l,p,u,f,m,y,x,S,k,E,M,h,C,v,T,W,P,R,N,j,ce,be,Ze,Se,Ne,Ce,Fe,We,Z,ne,ee;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:"",(M=(E=(k=t.toolCall)==null?void 0:k.chunks)==null?void 0:E.length)!=null?M:0,(T=(v=(C=(h=t.toolCall)==null?void 0:h.chunks)==null?void 0:C[t.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?T:"",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,(Se=(Ze=(be=(ce=t.reasoning)==null?void 0:ce.chunks)==null?void 0:be[t.reasoning.chunks.length-1])==null?void 0:Ze.length)!=null?Se:0,(We=(Fe=(Ce=(Ne=t.reasoning)==null?void 0:Ne.chunks)==null?void 0:Ce[t.reasoning.chunks.length-1])==null?void 0:Fe.slice(-32))!=null?We:"",(ne=(Z=t.contentParts)==null?void 0:Z.length)!=null?ne:0,(ee=t.stopReason)!=null?ee:"",e].join("\0")}function Wx(){return new Map}function Hx(t,e,r){let n=t.get(e);return n&&n.fingerprint===r?n.wrapper:null}function Bx(t,e,r,n){t.set(e,{fingerprint:r,wrapper:n})}function Dx(t,e){for(let r of t.keys())e.has(r)||t.delete(r)}function Rl(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function To(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Ca(t,e){return To(t)-t.scrollTop<=e}function Wl(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 Hl(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"}function Ox(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Nx(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),r=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:r}}function _x(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Jr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Qr=1e5,Vo=Qr+1;var Ys={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gv=["pre","code","a","script","style"],Bl=t=>{var e,r,n,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Ys.type,placeholder:(r=t==null?void 0:t.placeholder)!=null?r:Ys.placeholder,speed:(n=t==null?void 0:t.speed)!=null?n:Ys.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Ys.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Ys.buffer}},$x=[{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"}],Zs=new Map;for(let t of $x)Zs.set(t.name,t);var Aa=t=>{Zs.set(t.name,t)},Yp=t=>{$x.some(e=>e.name===t)||Zs.delete(t)},Zp=()=>Array.from(Zs.keys()),ei=(t,e)=>{var r,n;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(r=e[t])!=null?r:null:(n=Zs.get(t))!=null?n:null},Dl=(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},hv=(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},xv=(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},Jp=/\s/,yv=(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},bv=(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(Jp.test(s[i])){let l=i;for(;l<s.length&&Jp.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&&!Jp.test(s[p]);)l.appendChild(hv(n,s[p],e,r.value)),r.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,t)},wv=(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(xv(n,l,e,r.value)),r.value+=1));o.replaceChild(a,t)},ti=(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:gv).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)yv(d,s)||i.push(d),d=a.nextNode();let l={value:(f=n==null?void 0:n.startIndex)!=null?f:0},p=e==="char"?bv:wv;for(let m of i)p(m,r,l);return o.innerHTML},Ol=(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},ri=(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,vv=(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)},Qp=new WeakMap,Cv=(t,e)=>{if(!t.onAttach)return;let r=Qp.get(e);if(r||(r=new Map,Qp.set(e,r)),r.has(t.name))return;let n=t.onAttach(e);r.set(t.name,n)},Ux=t=>{let e=Qp.get(t);if(e){for(let r of e.values())typeof r=="function"&&r();e.clear()}},eu=(t,e)=>{vv(t,e),Cv(t,e)};function tu(t,e=Qr){let r=t.style.position,n=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=r),t.style.zIndex=n,t.style.isolation=o}}var ni=0,jo=null;function ru(t=document){var r;if(ni++,ni===1){let n=t.body,s=((r=t.defaultView)!=null?r:window).scrollY||t.documentElement.scrollTop;jo={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,ni=Math.max(0,ni-1),ni===0&&jo)){let o=t.body,s=(n=t.defaultView)!=null?n:window;o.style.overflow=jo.originalOverflow,o.style.position=jo.originalPosition,o.style.top=jo.originalTop,o.style.width=jo.originalWidth,s.scrollTo(0,jo.scrollY),jo=null}}}var Nl={side:"right",width:"420px",animate:!0,reveal:"resize"},Br=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="docked"},Go=t=>{var e,r;return((r=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?r:"floating")==="composer-bar"},Nn=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:Nl.side,width:(o=e==null?void 0:e.width)!=null?o:Nl.width,animate:(s=e==null?void 0:e.animate)!=null?s:Nl.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Nl.reveal}};var Xn={"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 oi=(t,e)=>{let r=w("button");r.type="button",r.innerHTML=`
66
66
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
67
67
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
68
68
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -70,14 +70,14 @@ _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]
70
70
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
71
71
  </span>
72
72
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
73
- `,r.addEventListener("click",e);let n=s=>{var M,h,w,y,E,B,P,R,O,V,ne,be,Ye,Ge;let a=(M=s.launcher)!=null?M:{},i=Ar(s),d=r.querySelector("[data-role='launcher-title']");if(d){let ve=(h=a.title)!=null?h:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let ve=(w=a.subtitle)!=null?w:"Get answers fast";l.textContent=ve,l.setAttribute("title",ve)}let p=r.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=r.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ve=(y=a.agentIconSize)!=null?y:"40px";if(m.style.height=ve,m.style.width=ve,m.innerHTML="",a.agentIconName){let Ee=parseFloat(ve)||24,Ke=Ie(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);Ke?(m.appendChild(Ke),m.style.display=""):(m.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",m.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let ve=(P=a.agentIconSize)!=null?P:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ve=(R=a.callToActionIconSize)!=null?R:"32px";f.style.height=ve,f.style.width=ve,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ke=parseFloat(ve)||24,Ne=Math.max(Ke-Ee,8),X=Ie(a.callToActionIconName,Ne,"currentColor",2);X?f.appendChild(X):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let x=a.position&&$n[a.position]?$n[a.position]:$n["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?S:`${C} ${x}`,i||(r.style.zIndex=String((ne=a.zIndex)!=null?ne:qr));let k="1px solid var(--persona-border, #e5e7eb)",T="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(be=a.border)!=null?be:k,r.style.boxShadow=(Ye=a.shadow)!=null?Ye:T,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(Ge=a.collapsedMaxWidth)!=null?Ge:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},o=()=>{r.removeEventListener("click",e),r.remove()};return t&&n(t),{element:r,update:n,destroy:o}};var Dw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Pl=(t,e={})=>{var C,S,k,T,M,h;let{showClose:r=!0,wrapperClassName:n=Dw,buttonSize:o,iconSize:s="28px"}=e,a=(C=t==null?void 0:t.launcher)!=null?C:{},i=(S=o!=null?o:a.closeButtonSize)!=null?S:"32px",d=v("div",n),l=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(k=a.closeButtonTooltipText)!=null?k:"Close chat",m=(T=a.closeButtonShowTooltip)!=null?T:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let u=(M=a.closeButtonIconName)!=null?M:"x",f=(h=a.closeButtonIconText)!=null?h:"\xD7";l.style.color=a.closeButtonColor||en.actionIconColor;let x=Ie(u,s,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):l.textContent=f,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let w=a.closeButtonBorderWidth||"0px",y=a.closeButtonBorderColor||"transparent";l.style.border=`${w} solid ${y}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let w=null,y=()=>{if(w)return;let B=l.ownerDocument,P=B.body;if(!P)return;w=Qn(B,"div","persona-clear-chat-tooltip"),w.textContent=p;let R=Qn(B,"div");R.className="persona-clear-chat-tooltip-arrow",w.appendChild(R);let O=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(Wo),w.style.left=`${O.left+O.width/2}px`,w.style.top=`${O.top-8}px`,w.style.transform="translate(-50%, -100%)",P.appendChild(w)},E=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};d.addEventListener("mouseenter",y),d.addEventListener("mouseleave",E),l.addEventListener("focus",y),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",y),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",y),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},Ow="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Il=(t,e={})=>{var w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve;let{wrapperClassName:r=Ow,buttonSize:n,iconSize:o="20px"}=e,a=(y=((w=t==null?void 0:t.launcher)!=null?w:{}).clearChat)!=null?y:{},i=(E=n!=null?n:a.size)!=null?E:"32px",d=(B=a.iconName)!=null?B:"refresh-cw",l=(P=a.iconColor)!=null?P:"",p=(R=a.backgroundColor)!=null?R:"",m=(O=a.borderWidth)!=null?O:"",u=(V=a.borderColor)!=null?V:"",f=(ne=a.borderRadius)!=null?ne:"",x=(be=a.paddingX)!=null?be:"",C=(Ye=a.paddingY)!=null?Ye:"",S=(Ge=a.tooltipText)!=null?Ge:"Clear chat",k=(ve=a.showTooltip)!=null?ve:!0,T=v("div",r),M=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",S),M.style.color=l||en.actionIconColor;let h=Ie(d,o,"currentColor",1);if(h&&(h.style.display="block",M.appendChild(h)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),m||u){let Ee=m||"0px",Ke=u||"transparent";M.style.border=`${Ee} solid ${Ke}`,M.classList.remove("persona-border-none")}if(f&&(M.style.borderRadius=f,M.classList.remove("persona-rounded-full")),x&&(M.style.paddingLeft=x,M.style.paddingRight=x),C&&(M.style.paddingTop=C,M.style.paddingBottom=C),T.appendChild(M),k&&S){let Ee=null,Ke=()=>{if(Ee)return;let X=M.ownerDocument,Ue=X.body;if(!Ue)return;Ee=Qn(X,"div","persona-clear-chat-tooltip"),Ee.textContent=S;let K=Qn(X,"div");K.className="persona-clear-chat-tooltip-arrow",Ee.appendChild(K);let Te=M.getBoundingClientRect();Ee.style.position="fixed",Ee.style.zIndex=String(Wo),Ee.style.left=`${Te.left+Te.width/2}px`,Ee.style.top=`${Te.top-8}px`,Ee.style.transform="translate(-50%, -100%)",Ue.appendChild(Ee)},Ne=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};T.addEventListener("mouseenter",Ke),T.addEventListener("mouseleave",Ne),M.addEventListener("focus",Ke),M.addEventListener("blur",Ne),T._cleanupTooltip=()=>{Ne(),T.removeEventListener("mouseenter",Ke),T.removeEventListener("mouseleave",Ne),M.removeEventListener("focus",Ke),M.removeEventListener("blur",Ne)}}return{button:M,wrapper:T}};var en={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},go=t=>{var w,y,E,B,P,R,O,V,ne,be,Ye,Ge,ve,Ee,Ke,Ne;let{config:e,showClose:r=!0}=t,n=v("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(w=e==null?void 0:e.launcher)!=null?w:{},s=(y=o.headerIconSize)!=null?y:"48px",a=(E=o.closeButtonPlacement)!=null?E:"inline",i=(B=o.headerIconHidden)!=null?B:!1,d=o.headerIconName,l=v("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let X=parseFloat(s)||24,Ue=Ie(d,X*.6,"currentColor",1);Ue?l.replaceChildren(Ue):l.textContent=(R=(P=e==null?void 0:e.launcher)==null?void 0:P.agentIconText)!=null?R:"\u{1F4AC}"}else if((O=e==null?void 0:e.launcher)!=null&&O.iconUrl){let X=v("img");X.src=e.launcher.iconUrl,X.alt="",X.className="persona-rounded-xl persona-object-cover",X.style.height=s,X.style.width=s,l.replaceChildren(X)}else l.textContent=(ne=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=v("span","persona-text-base persona-font-semibold");m.style.color=en.titleColor,m.textContent=(Ye=(be=e==null?void 0:e.launcher)==null?void 0:be.title)!=null?Ye:"Chat Assistant";let u=v("span","persona-text-xs");u.style.color=en.subtitleColor,u.textContent=(ve=(Ge=e==null?void 0:e.launcher)==null?void 0:Ge.subtitle)!=null?ve:"Here to help you get answers fast",p.append(m,u),i?n.append(p):n.append(l,p);let f=(Ee=o.clearChat)!=null?Ee:{},x=(Ke=f.enabled)!=null?Ke:!0,C=(Ne=f.placement)!=null?Ne:"inline",S=null,k=null;if(x){let Ue=Il(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=Ue.button,k=Ue.wrapper,C==="top-right"&&(k.style.right="48px"),C==="inline"&&n.appendChild(k)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:M,wrapper:h}=Pl(e,{showClose:r,wrapperClassName:T});return a!=="top-right"&&n.appendChild(h),{header:n,iconHolder:l,headerTitle:m,headerSubtitle:u,closeButton:M,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:k}},ua=(t,e,r)=>{var a,i,d,l;let n=(a=r==null?void 0:r.launcher)!=null?a:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",s=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function Do(t){let{items:e,onSelect:r,anchor:n,position:o="bottom-left",portal:s}=t,a=v("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Wo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",f.id),f.destructive&&x.setAttribute("data-destructive",""),f.icon){let S=Ie(f.icon,16,"currentColor",1.5);S&&x.appendChild(S)}let C=document.createElement("span");C.textContent=f.label,x.appendChild(C),x.addEventListener("click",S=>{S.stopPropagation(),p(),r(f.id)}),a.appendChild(x)}let i=null;function d(){if(!s)return;let f=n.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=x=>{!a.contains(x.target)&&!n.contains(x.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function u(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:u}}function Er(t){let{icon:e,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",r),d.title=r;let l=Ie(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Gs(t){let{icon:e,label:r,variant:n="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=v("button",l);if(p.type="button",p.setAttribute("aria-label",r),e){let u=Ie(e,s!=null?s:14,"currentColor",2);u&&p.appendChild(u)}let m=v("span");if(m.textContent=r,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[u,f]of Object.entries(d))p.setAttribute(u,f);return p}function px(t){let{items:e,selectedId:r,onSelect:n,className:o}=t,s=v("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=r,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of e){let m;p.icon?m=Er({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(m=v("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),s.appendChild(m)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Rl(t){var f,x;let{label:e,icon:r="chevron-down",menuItems:n,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,l=v("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",e);let p=v("span","persona-combo-btn-label");p.textContent=e,l.appendChild(p);let m=Ie(r,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var C,S;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Do({items:n,onSelect:C=>{l.setAttribute("aria-expanded","false"),o(C)},anchor:l,position:s,portal:a});return a||l.appendChild(u.element),l.addEventListener("click",C=>{C.stopPropagation();let S=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),u.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{p.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let C=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Up=t=>{var n;let e=go({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),r=(n=t.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(r){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>r()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())}))}return e};function Nw(t,e,r){var n,o,s;if(e!=null&&e.length)for(let a of e){let i=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=a.ariaLabel)!=null?n:a.label)!=null?o:a.id),a.icon){let d=Ie(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(i);let l=Do({items:a.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>r==null?void 0:r(a.id)),t.appendChild(i)}}var qp=t=>{var T,M,h,w,y,E,B,P,R;let{config:e,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Rl({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=en.titleColor,p=(h=l.querySelector(".persona-combo-btn-label"))!=null?h:l;else{if(l=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=en.titleColor,p.textContent=(w=a.title)!=null?w:"Chat Assistant",l.appendChild(p),Nw(l,o==null?void 0:o.trailingActions,(y=o==null?void 0:o.onAction)!=null?y:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=o.onTitleClick;l.addEventListener("click",ne=>{ne.target.closest("button")||V()}),l.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",l.style.padding=(B=O.padding)!=null?B:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,ne;l.style.backgroundColor=(V=O.background)!=null?V:"",l.style.borderColor=(ne=O.border)!=null?ne:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(P=a.closeButtonSize)!=null?P:"32px",u=v("div",""),f=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=a.closeButtonColor||en.actionIconColor;let x=(R=a.closeButtonIconName)!=null?R:"x",C=Ie(x,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",n&&f.addEventListener("click",n),u.appendChild(f),i.appendChild(u);let S=v("div");S.style.display="none";let k=v("span");return k.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:k,closeButton:f,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Wl={default:Up,minimal:qp},zp=t=>{var e;return(e=Wl[t])!=null?e:Wl.default},Na=(t,e,r)=>{var a,i,d;if(e!=null&&e.render){let l=e.render({config:t,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=v("div");p.style.display="none";let m=v("span"),u=v("span"),f=v("button");f.style.display="none";let x=v("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:u,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=e==null?void 0:e.layout)!=null?a:"default",s=zp(n)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Bl=t=>{var a,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,n=20;e.style.maxHeight=`${r*n}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:r*n},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Hl=t=>{var w,y,E,B,P,R,O,V,ne,be,Ye,Ge;let e=(w=t==null?void 0:t.sendButton)!=null?w:{},r=(y=e.useIcon)!=null?y:!1,n=(E=e.iconText)!=null?E:"\u2191",o=e.iconName,s=(B=e.stopIconName)!=null?B:"square",a=(P=e.tooltipText)!=null?P:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(V=(O=t==null?void 0:t.copy)==null?void 0:O.sendButtonLabel)!=null?V:"Send",l=(be=(ne=t==null?void 0:t.copy)==null?void 0:ne.stopButtonLabel)!=null?be:"Stop",p=(Ye=e.showTooltip)!=null?Ye:!1,m=(Ge=e.size)!=null?Ge:"40px",u=e.backgroundColor,f=e.textColor,x=v("div","persona-send-button-wrapper"),C=v("button",r?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");C.type="submit",C.setAttribute("data-persona-composer-submit","");let S=null,k=null;if(r){C.style.width=m,C.style.height=m,C.style.minWidth=m,C.style.minHeight=m,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",f?C.style.color=f:C.style.color="var(--persona-button-primary-fg, #ffffff)";let ve=parseFloat(m)||24,Ee=(f==null?void 0:f.trim())||"currentColor";o?(S=Ie(o,ve,Ee,2),S?C.appendChild(S):C.textContent=n):C.textContent=n,k=Ie(s,ve,Ee,2),u?C.style.backgroundColor=u:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,f?C.style.color=f:C.classList.add("persona-text-white");e.borderWidth&&(C.style.borderWidth=e.borderWidth,C.style.borderStyle="solid"),e.borderColor&&(C.style.borderColor=e.borderColor),e.paddingX?(C.style.paddingLeft=e.paddingX,C.style.paddingRight=e.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),e.paddingY?(C.style.paddingTop=e.paddingY,C.style.paddingBottom=e.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let T=null;p&&a&&(T=v("div","persona-send-button-tooltip"),T.textContent=a,x.appendChild(T)),C.setAttribute("aria-label",a),x.appendChild(C);let M="send";return{button:C,wrapper:x,setMode:ve=>{if(ve===M)return;M=ve;let Ee=ve==="stop"?i:a;if(C.setAttribute("aria-label",Ee),T&&(T.textContent=Ee),r){if(S&&k){let Ke=ve==="stop"?k:S;C.replaceChildren(Ke)}}else C.textContent=ve==="stop"?l:d}}},Dl=t=>{var T,M,h,w,y,E,B,P,R,O,V,ne;let e=(T=t==null?void 0:t.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=e.provider)==null?void 0:M.type)==="runtype";if(!(n||o))return null;let a=(w=(h=t==null?void 0:t.sendButton)==null?void 0:h.size)!=null?w:"40px",i=v("div","persona-send-button-wrapper"),d=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(y=e.iconName)!=null?y:"mic",p=(E=e.iconSize)!=null?E:a,m=parseFloat(p)||24,u=(P=e.backgroundColor)!=null?P:(B=t==null?void 0:t.sendButton)==null?void 0:B.backgroundColor,f=(O=e.iconColor)!=null?O:(R=t==null?void 0:t.sendButton)==null?void 0:R.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",f?d.style.color=f:d.style.color="var(--persona-text, #111827)";let C=Ie(l,m,f||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",u&&(d.style.backgroundColor=u),e.borderWidth&&(d.style.borderWidth=e.borderWidth,d.style.borderStyle="solid"),e.borderColor&&(d.style.borderColor=e.borderColor),e.paddingX&&(d.style.paddingLeft=e.paddingX,d.style.paddingRight=e.paddingX),e.paddingY&&(d.style.paddingTop=e.paddingY,d.style.paddingBottom=e.paddingY),i.appendChild(d);let S=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((ne=e.showTooltip)!=null?ne:!1)&&S){let be=v("div","persona-send-button-tooltip");be.textContent=S,i.appendChild(be)}return{button:d,wrapper:i}},Ol=t=>{var x,C,S,k,T,M,h,w;let e=(x=t==null?void 0:t.attachments)!=null?x:{};if(e.enabled!==!0)return null;let r=(S=(C=t==null?void 0:t.sendButton)==null?void 0:C.size)!=null?S:"40px",n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=v("input");o.type="file",o.accept=((k=e.allowedTypes)!=null?k:mo).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=v("div","persona-send-button-wrapper"),a=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(M=e.buttonTooltipText)!=null?M:"Attach file");let i=(h=e.buttonIconName)!=null?h:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Ie(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",y=>{y.preventDefault(),o.click()}),s.appendChild(a);let u=(w=e.buttonTooltipText)!=null?w:"Attach file",f=v("div","persona-send-button-tooltip");return f.textContent=u,s.appendChild(f),{button:a,wrapper:s,input:o,previewsContainer:n}},Nl=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},r=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",n=v("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;n.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=v("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=s;return n},_l=()=>v("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var _a=t=>{var x,C,S,k,T,M;let{config:e}=t,r=v("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");r.setAttribute("data-persona-theme-zone","composer");let n=_l(),o=v("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Bl(e);a();let i=Hl(e),d=Dl(e),l=Ol(e),p=Nl(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let m=v("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),u=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(u,f),o.append(m),o.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==(d==null?void 0:d.button)&&h.target!==(d==null?void 0:d.wrapper)&&h.target!==(l==null?void 0:l.button)&&h.target!==(l==null?void 0:l.wrapper)&&s.focus()}),r.append(n,o,p),{footer:r,suggestions:n,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(k=l==null?void 0:l.wrapper)!=null?k:null,attachmentInput:(T=l==null?void 0:l.input)!=null?T:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var ux=()=>{let t=v("button","persona-pill-peek");t.type="button",t.setAttribute("data-persona-pill-peek",""),t.setAttribute("aria-label","Show conversation"),t.setAttribute("tabindex","-1");let e=v("span","persona-pill-peek__icon"),r=Ie("message-square",16,"currentColor",1.5);r&&e.appendChild(r);let n=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=Ie("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,n,o),{root:t,textNode:n}},fx=t=>{var x,C,S,k,T,M;let{config:e}=t,r=v("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=_l();n.style.display="none";let o=Nl(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Bl(e);s.style.maxHeight="100px",a();let i=Hl(e),d=Dl(e),l=Ol(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=v("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=v("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let u=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),p.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==(d==null?void 0:d.button)&&h.target!==(d==null?void 0:d.wrapper)&&h.target!==(l==null?void 0:l.button)&&h.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,u),l&&r.append(l.previewsContainer),r.append(p,n,o);let f=p;return{footer:r,suggestions:n,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:o,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(k=l==null?void 0:l.wrapper)!=null?k:null,attachmentInput:(T=l==null?void 0:l.input)!=null?T:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:f,leftActions:m,rightActions:u,setSendButtonMode:i.setMode}};var mx=t=>{var p,m,u,f,x,C,S,k,T,M,h,w,y,E,B,P,R;let e=(m=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)!=null?m:!0,r=Ar(t);if(Ho(t)){let O=(f=(u=t==null?void 0:t.launcher)==null?void 0:u.composerBar)!=null?f:{},V=v("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(x=O.expandedSize)!=null?x:"anchored",V.style.zIndex=String((S=(C=t==null?void 0:t.launcher)==null?void 0:C.zIndex)!=null?S:qr);let ne=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let be=v("div","persona-widget-pill-root");return be.setAttribute("data-persona-composer-bar",""),be.dataset.state="collapsed",be.dataset.expandedSize=(k=O.expandedSize)!=null?k:"anchored",be.style.zIndex=String((M=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?M:qr),{wrapper:V,panel:ne,pillRoot:be}}if(r){let O=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(V),{wrapper:O,panel:V}}if(!e){let O=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(w=(h=t==null?void 0:t.launcher)==null?void 0:h.width)!=null?w:"100%";return O.style.width=ne,V.style.width="100%",O.appendChild(V),{wrapper:O,panel:V}}let o=(y=t==null?void 0:t.launcher)!=null?y:{},s=o.position&&$n[o.position]?$n[o.position]:$n["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((B=(E=t==null?void 0:t.launcher)==null?void 0:E.zIndex)!=null?B:qr);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(P=t==null?void 0:t.launcher)==null?void 0:P.width)!=null?R:t==null?void 0:t.launcherWidth,l=d!=null?d:yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},_w=(t,e)=>{var h,w,y,E,B,P,R,O,V;let r=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Pl(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(y=(w=(h=t==null?void 0:t.launcher)==null?void 0:h.clearChat)==null?void 0:w.enabled)!=null?y:!0,a=null,i=null;if(s){let ne=Il(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=v("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(B=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeTitle)!=null?B:"Hello \u{1F44B}";let u=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(R=(P=t==null?void 0:t.copy)==null?void 0:P.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(m,u);let f=v("div","persona-flex persona-flex-col persona-gap-3"),x=(O=t==null?void 0:t.layout)==null?void 0:O.contentMaxWidth;x&&(f.style.maxWidth=x,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((V=t==null?void 0:t.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,f);let S=v("div","persona-composer-overlay persona-pointer-events-none");S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20";let k=fx({config:t}),{root:T,textNode:M}=ux();return r.append(d,o,l,S),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:f,composerOverlay:S,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:m,introSubtitle:u,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:T,peekTextNode:M}},gx=(t,e=!0)=>{var S,k,T,M,h,w,y,E,B;if(Ho(t))return _w(t,e);let r=v("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");r.setAttribute("data-persona-theme-zone","container");let n=(S=t==null?void 0:t.layout)==null?void 0:S.header,o=((k=t==null?void 0:t.layout)==null?void 0:k.showHeader)!==!1,s=n?Na(t,n,{showClose:e}):go({config:t,showClose:e}),a=v("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Ar(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(M=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(h=t==null?void 0:t.copy)==null?void 0:h.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let p=v("div","persona-flex persona-flex-col persona-gap-3"),m=(y=t==null?void 0:t.layout)==null?void 0:y.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((E=t==null?void 0:t.copy)==null?void 0:E.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let f=_a({config:t}),x=((B=t==null?void 0:t.layout)==null?void 0:B.showFooter)!==!1;o?ua(r,s,t):(s.header.style.display="none",ua(r,s,t)),r.append(a);let C=v("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",x||(f.footer.style.display="none"),r.append(f.footer),r.append(C),{container:r,body:a,messagesWrapper:p,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Fw=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},$w=(t,e)=>{if(!t)return null;let r=Fw(t);if(r===null)return null;let n=e==null?void 0:e[t],o=n!==void 0?n:r;return o||null},Uw=(t,e)=>{let r=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",t),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=e,r},qw=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Vp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},jp=320,xx=320,zw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Vw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),jw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Gw=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Kw=(t,e,r)=>{if(t.length===0)return null;try{let n=v("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),e&&(n.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,n.remove(),r==null||r())};return t.forEach((i,d)=>{var m;let l=v("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${jp}px`,l.style.maxHeight=`${xx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),qw(i.image)?(l.src=i.image,n.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):n}catch{return r==null||r(),null}},Xw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let r=0;return t.forEach(n=>{if(!Vp(n.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${jp}px`,e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Jw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let r=0;return t.forEach(n=>{if(!Vp(n.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${jp}px`,o.style.maxHeight=`${xx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Qw=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let r=0;return t.forEach(n=>{if(!Vp(n.data))return;let o=v("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},fa=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(r),t.appendChild(n),t.appendChild(o),t},Gp=(t,e,r)=>{let n={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:fa};if(e){let o=e(n);if(o!==null)return o}return fa()},Yw=(t,e)=>{let r=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=e==="user"?t.userAvatar:t.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=v("img");o.src=n,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(o)}else r.textContent=n,r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},hx=(t,e)=>{let r=v("div","persona-text-xs persona-text-persona-muted"),n=new Date(t.createdAt);return e.format?r.textContent=e.format(n):r.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Zw=(t,e="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},Kp=(t,e,r)=>{var f,x,C,S,k,T;let n=(f=e.showCopy)!=null?f:!0,o=(x=e.showUpvote)!=null?x:!0,s=(C=e.showDownvote)!=null?C:!0;if(!n&&!o&&!s){let M=v("div");return M.style.display="none",M.id=`actions-${t.id}`,M.setAttribute("data-actions-for",t.id),M}let a=(S=e.visibility)!=null?S:"hover",i=(k=e.align)!=null?k:"right",d=(T=e.layout)!=null?T:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id);let u=(M,h,w)=>{let y=Er({icon:M,label:h,size:14,className:"persona-message-action-btn"});return y.setAttribute("data-action",w),y};return n&&m.appendChild(u("copy","Copy message","copy")),o&&m.appendChild(u("thumbs-up","Upvote","upvote")),s&&m.appendChild(u("thumbs-down","Downvote","downvote")),m},Fa=(t,e,r,n,o,s)=>{var X,Ue,K,Te,oe,xe,Me,Xe,ce,te,le,ut,Ce,he,rt,_e,me;let a=r!=null?r:{},i=(X=a.layout)!=null?X:"bubble",d=a.avatar,l=a.timestamp,p=(Ue=d==null?void 0:d.show)!=null?Ue:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,u=(Te=d==null?void 0:d.position)!=null?Te:"left",f=(oe=l==null?void 0:l.position)!=null?oe:"below",x=Zw(t.role,i),C=v("div",x.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=zw(t),k=(Me=(xe=t.content)==null?void 0:xe.trim())!=null?Me:"",M=S.length>0&&k===el,h=Ml((ce=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.features)==null?void 0:ce.streamAnimation),w=(ut=(le=(te=s==null?void 0:s.widgetConfig)==null?void 0:te.features)==null?void 0:le.streamAnimation)==null?void 0:ut.plugins,y=t.role==="assistant"&&h.type!=="none"?Us(h.type,w):null,E=t.role==="assistant"&&((Ce=y==null?void 0:y.isAnimating)==null?void 0:Ce.call(y,t))===!0,B=t.role==="assistant"&&y!==null&&(!!t.streaming||E);B&&(y!=null&&y.bubbleClass)&&C.classList.add(y.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),B&&y&&(y.containerClass&&P.classList.add(y.containerClass),P.style.setProperty("--persona-stream-step",`${h.speed}ms`),P.style.setProperty("--persona-stream-duration",`${h.duration}ms`));let R=B?kl((he=t.content)!=null?he:"",h.buffer,y,t,!!t.streaming):(rt=t.content)!=null?rt:"",O=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),V=O;B&&(y==null?void 0:y.wrap)==="char"?V=qs(O,"char",t.id,{skipTags:y.skipTags}):B&&(y==null?void 0:y.wrap)==="word"&&(V=qs(O,"word",t.id,{skipTags:y.skipTags}));let ne=null;if(M?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",P.appendChild(ne)):P.innerHTML=V,B&&(y!=null&&y.useCaret)&&!M&&k){let J=El(),ze=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),Z=ze[ze.length-1];if(Z!=null&&Z.parentNode)Z.parentNode.insertBefore(J,Z.nextSibling);else{let ge=P.lastElementChild;ge?ge.appendChild(J):P.appendChild(J)}}if(m&&f==="inline"&&t.createdAt){let J=hx(t,l);J.classList.add("persona-ml-2","persona-inline"),P.appendChild(J)}if(S.length>0){let J=Kw(S,!M&&!!k,()=>{M&&ne&&(ne.style.display="")});J?C.appendChild(J):M&&ne&&(ne.style.display="")}let be=Vw(t);if(be.length>0){let J=Xw(be);J&&C.appendChild(J)}let Ye=jw(t);if(Ye.length>0){let J=Jw(Ye);J&&C.appendChild(J)}let Ge=Gw(t);if(Ge.length>0){let J=Qw(Ge);J&&C.appendChild(J)}if(C.appendChild(P),m&&f==="below"&&t.createdAt){let J=hx(t,l);J.classList.add("persona-mt-1"),C.appendChild(J)}let ve=t.role==="assistant"?$w(t.stopReason,(me=(_e=s==null?void 0:s.widgetConfig)==null?void 0:_e.copy)==null?void 0:me.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let J=!!(R&&R.trim()),ze=h.placeholder==="skeleton",Z=ze&&h.buffer==="line"&&J;if(J)Z&&C.appendChild(zs());else if(ze)C.appendChild(zs());else{let ge=Gp("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ge&&C.appendChild(ge)}}if(ve&&t.stopReason&&!t.streaming&&(k||(P.style.display="none"),C.appendChild(Uw(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let J=Kp(t,n,o);C.appendChild(J)}if(!p||t.role==="system")return C;let Ke=v("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Ne=Yw(d,t.role);return u==="right"||u==="left"&&t.role==="user"?Ke.append(C,Ne):Ke.append(Ne,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ke},yx=(t,e,r,n,o,s)=>{let a=r!=null?r:{};return t.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:t,config:{},streaming:!!t.streaming}):t.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:t,config:{},streaming:!!t.streaming}):Fa(t,e,r,n,o,s)};var $a=new Set,ev=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),tv=(t,e)=>{var n,o;let r=(o=(n=t.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
74
- `):""},bx=(t,e)=>{let r=$a.has(t),n=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",r?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ie(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none",s&&(s.style.display=r?"none":s.textContent||s.childNodes.length?"":"none")},Xp=(t,e)=>{var Ye,Ge,ve,Ee,Ke,Ne,X,Ue,K,Te,oe;let r=t.reasoning,n=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${t.id}`,n.setAttribute("data-message-id",t.id),!r)return n;let o=(Ge=(Ye=e==null?void 0:e.features)==null?void 0:Ye.reasoningDisplay)!=null?Ge:{},s=o.expandable!==!1,a=s&&$a.has(t.id),i=r.status!=="complete",d=tv(t,(ve=o.previewMaxLines)!=null?ve:3),l=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",f=(Ee=e==null?void 0:e.reasoning)!=null?Ee:{},x=String((Ke=r.startedAt)!=null?Ke:Date.now()),C=()=>{let xe=v("span","");return xe.setAttribute("data-tool-elapsed",x),xe.textContent=ji(r),xe},S=(Ne=f.renderCollapsedSummary)==null?void 0:Ne.call(f,{message:t,reasoning:r,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:ji(r),createElapsedElement:C});typeof S=="string"&&S.trim()?(m.textContent=S,p.appendChild(m)):S instanceof HTMLElement?p.appendChild(S):(m.textContent=u,p.appendChild(m));let k=v("span","persona-text-xs persona-text-persona-primary");k.textContent=Rh(r),p.appendChild(k);let T=(X=o.loadingAnimation)!=null?X:"none",M=f.activeTextTemplate,h=f.completeTextTemplate,w=i?M:h,y=S instanceof HTMLElement,E=(xe,Me,Xe)=>{let ce=Xe;for(let te of Me){let le=v("span","persona-tool-char");le.style.setProperty("--char-index",String(ce)),le.textContent=te===" "?"\xA0":te,xe.appendChild(le),ce++}return ce},B=(xe,Me)=>{m.textContent="";let Xe=Gi(xe,""),ce=0;for(let te of Xe){let le=te.styles.length>0?(()=>{let ut=v("span",te.styles.map(Ce=>`persona-tool-text-${Ce}`).join(" "));return m.appendChild(ut),ut})():m;if(te.isDuration&&i)le.appendChild(C());else{let ut=te.isDuration?ji(r):te.text;Me?ce=E(le,ut,ce):le.appendChild(document.createTextNode(ut))}}};if(!y&&w)if(k.style.display="none",m.style.display="",i&&T!=="none"){let xe=(Ue=f.loadingAnimationDuration)!=null?Ue:2e3;m.setAttribute("data-preserve-animation","true"),T==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),B(w,!1)):(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),B(w,!0))}else B(w,!1);else if(!y&&i&&T!=="none"){m.style.display="";let xe=(K=f.loadingAnimationDuration)!=null?K:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`);else{m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Me=m.textContent||u;m.textContent="",E(m,Me,0)}r.status==="complete"&&(m.style.display="none")}else y||(r.status==="complete"?m.style.display="none":m.style.display="");let P=null;if(s){P=v("div","persona-flex persona-items-center");let Me=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?P.appendChild(Me):P.textContent=a?"Hide":"Show";let Xe=v("div","persona-flex persona-items-center persona-ml-auto");Xe.append(P),l.append(p,Xe)}else l.append(p);let R=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let xe=(oe=(Te=e==null?void 0:e.reasoning)==null?void 0:Te.renderCollapsedPreview)==null?void 0:oe.call(Te,{message:t,reasoning:r,defaultPreview:d,isActive:i,config:e!=null?e:{}});ev(R,xe)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!s)return n.append(l,R),n;let O=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let V=r.chunks.join(""),ne=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(ne),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),P){P.innerHTML="";let Me=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?P.appendChild(Me):P.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),n.append(l,R,O),n};var Ua=new Set,rv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),nv=(t,e)=>{var s;let r=t.toolCall;if(!r)return"";let n=((s=r.chunks)!=null?s:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
75
- `);let o=Ra(r.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
76
- `):""},ov=(t,e)=>{var p,m,u,f,x;let r=t.toolCall,n=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(m=n==null?void 0:n.collapsedMode)!=null?m:"tool-call",s=nv(t,(u=n==null?void 0:n.previewMaxLines)!=null?u:3),a=r?Wh(r):"";if(!r)return{summary:a,previewText:s,isActive:!1};let i=r.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Wd(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Wd(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},wx=(t,e,r)=>{var p;let n=Ua.has(t),o=(p=r==null?void 0:r.toolCall)!=null?p:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",n?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=o.toggleTextColor||o.headerTextColor||"currentColor",u=Ie(n?"chevron-up":"chevron-down",16,m,2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Jp=(t,e)=>{var V,ne,be,Ye,Ge,ve,Ee,Ke,Ne;let r=t.toolCall,n=(V=e==null?void 0:e.toolCall)!=null?V:{},o=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!r)return o;let s=(be=(ne=e==null?void 0:e.features)==null?void 0:ne.toolCallDisplay)!=null?be:{},a=s.expandable!==!1,i=a&&Ua.has(t.id),{summary:d,previewText:l,isActive:p}=ov(t,e),m=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let u=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let x=String((Ye=r.startedAt)!=null?Ye:Date.now()),C=()=>{let X=v("span","");return X.setAttribute("data-tool-elapsed",x),X.textContent=Is(r),X},S=(ve=n.renderCollapsedSummary)==null?void 0:ve.call(n,{message:t,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(Ge=s.collapsedMode)!=null?Ge:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Is(r),createElapsedElement:C});typeof S=="string"&&S.trim()?(f.textContent=S,u.appendChild(f)):S instanceof HTMLElement?u.appendChild(S):(f.textContent=d,u.appendChild(f));let k=(Ee=s.loadingAnimation)!=null?Ee:"none",T=n.activeTextTemplate,M=n.completeTextTemplate,h=p?T:M,w=S instanceof HTMLElement,y=(X,Ue,K)=>{let Te=K;for(let oe of Ue){let xe=v("span","persona-tool-char");xe.style.setProperty("--char-index",String(Te)),xe.textContent=oe===" "?"\xA0":oe,X.appendChild(xe),Te++}return Te},E=(X,Ue)=>{var xe;f.textContent="";let K=((xe=r.name)==null?void 0:xe.trim())||"tool",Te=Gi(X,K),oe=0;for(let Me of Te){let Xe=Me.styles.length>0?(()=>{let ce=v("span",Me.styles.map(te=>`persona-tool-text-${te}`).join(" "));return f.appendChild(ce),ce})():f;if(Me.isDuration&&p)Xe.appendChild(C());else{let ce=Me.isDuration?Is(r):Me.text;Ue?oe=y(Xe,ce,oe):Xe.appendChild(document.createTextNode(ce))}}};if(!w)if(p&&k!=="none"){let X=(Ke=n.loadingAnimationDuration)!=null?Ke:2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),h&&E(h,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${X}ms`),k==="shimmer-color"&&(n.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),h)E(h,!0);else{let Ue=f.textContent||d;f.textContent="",y(f,Ue,0)}}else h&&E(h,!1);let B=null;if(a){B=v("div","persona-flex persona-items-center");let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?B.appendChild(Ue):B.textContent=i?"Hide":"Show";let K=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(B),m.append(u,K)}else m.append(u);let P=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(P.setAttribute("data-persona-collapsed-preview","tool"),P.style.display="none",P.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let X=(Ne=n.renderCollapsedPreview)==null?void 0:Ne.call(n,{message:t,toolCall:r,defaultPreview:l,isActive:p,config:e!=null?e:{}});rv(P,X)||(P.textContent=l),P.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(m,P),o;let R=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",n.contentBackgroundColor&&(R.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(R.style.color=n.contentTextColor),n.contentPaddingX&&(R.style.paddingLeft=n.contentPaddingX,R.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(R.style.paddingTop=n.contentPaddingY,R.style.paddingBottom=n.contentPaddingY),r.name){let X=v("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?X.style.color=n.contentTextColor:n.headerTextColor&&(X.style.color=n.headerTextColor),X.textContent=r.name,R.appendChild(X)}if(r.args!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Arguments";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ra(r.args),X.append(Ue,K),R.appendChild(X)}if(r.chunks&&r.chunks.length){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Activity";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=r.chunks.join(""),X.append(Ue,K),R.appendChild(X)}if(r.status==="complete"&&r.result!==void 0){let X=v("div","persona-space-y-1"),Ue=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ue.style.color=n.labelTextColor),Ue.textContent="Result";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(K.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(K.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(K.style.color=n.codeBlockTextColor),K.textContent=Ra(r.result),X.append(Ue,K),R.appendChild(X)}if(r.status==="complete"&&typeof r.duration=="number"){let X=v("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(X.style.color=n.contentTextColor),X.textContent=`Duration: ${r.duration}ms`,R.appendChild(X)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),B){B.innerHTML="";let X=n.toggleTextColor||n.headerTextColor||"currentColor",Ue=Ie(i?"chevron-up":"chevron-down",16,X,2);Ue?B.appendChild(Ue):B.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",P.style.display=i?"none":P.textContent||P.childNodes.length?"":"none"})(),o.append(m,P,R),o};var Oo=ad(qi(),1);var Yp="ask_user_question",Qp=8,qa="data-persona-ask-sheet-for",av="Other",sv="Other\u2026",Cx="Type your own answer here",Ax="Send",iv="Next",lv="Back",dv="Submit all",cv="Skip",pv=3,Zp="data-ask-current-index",eu="data-ask-question-count",Sx="data-ask-answers",tu="data-ask-grouped",Tx="data-ask-layout",uv=t=>t.layout==="pills"?"pills":"rows",fv=t=>t.getAttribute(Tx)==="pills"?"pills":"rows",vx=!1,Mx=t=>t.replace(/["\\]/g,"\\$&"),ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Yp,Fl=t=>{var e,r;return(r=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?r:{}},xo=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let r=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:r};let n=e.chunks;if(!n||n.length===0)return{payload:null,complete:r};try{let o=n.join(""),s=(0,Oo.parse)(o,Oo.STR|Oo.OBJ|Oo.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},Ks=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Qp&&!vx&&(vx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Qp}.`)),e.slice(0,Qp)},mv=t=>{var e;return(e=Ks(t)[0])!=null?e:null},gv=(t,e)=>{var r;return(r=Ks(t)[e])!=null?r:null},kx=(t,e)=>{let r=e.styles;r&&(r.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Ex=(t,e,r)=>{if(t!=="rows")return null;let n=v("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");n.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},hv=(t,e,r,n)=>{let s=v("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",n?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),r==="rows"){let a=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let l=v("span","persona-ask-row-description");l.textContent=t.description,a.appendChild(l)}s.appendChild(a);let d=Ex(r,n,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},xv=t=>{let r=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},yv=(t,e,r,n)=>{var p,m,u;let s=v("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!r){for(let f=0;f<pv;f++)s.appendChild(xv(n));return s}if(d.forEach((f,x)=>{s.appendChild(hv(f,x,n,a))}),(t==null?void 0:t.allowFreeText)!==!1){let f=n==="rows"?av:sv;if(n==="rows"){let x=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let C=v("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=e.freeTextPlaceholder)!=null?p:Cx,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),C.appendChild(S),x.appendChild(C);let k=Ex(n,a,d.length);k&&x.appendChild(k),s.appendChild(x)}else{let x=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(u=e.freeTextLabel)!=null?u:f,s.appendChild(x)}}return s},Lx=(t,e)=>{var s,a;let n=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:Cx,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),e!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:Ax,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},bv=t=>{var n;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let r=v("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=t.submitLabel)!=null?n:Ax,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,e.appendChild(r),e},wv=(t,e,r)=>{var l,p,m,u;let n=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=r.backLabel)!=null?l:lv,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,n.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:cv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(m=r.submitAllLabel)!=null?m:dv:(u=r.nextLabel)!=null?u:iv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},ma=t=>{let e=t.getAttribute(Sx);if(!e)return{};try{let r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}},Px=(t,e)=>{t.setAttribute(Sx,JSON.stringify(e))},En=t=>{var r;let e=Number((r=t.getAttribute(Zp))!=null?r:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},vv=(t,e)=>{t.setAttribute(Zp,String(Math.max(0,Math.floor(e))))},za=t=>{var r;let e=Number((r=t.getAttribute(eu))!=null?r:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},No=t=>t.getAttribute(tu)==="true",Cv=(t,e)=>{var o;let r=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let n={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let d=r[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},Av=(t,e)=>{var n;let r=(n=t.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(e-1,Math.floor(r)))},$l=(t,e)=>{let{payload:r}=xo(e),n=Ks(r),o=ma(t),s={},a=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Ix=t=>{let e=ma(t),r=En(t),n=e[r],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!a.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Rx=t=>{if(!No(t))return;let e=ma(t),r=En(t),n=e[r],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},ru=(t,e,r)=>{let n=Fl(r),o=fv(t),{payload:s,complete:a}=xo(e),i=No(t),d=En(t),l=za(t),p=i?gv(s,d):mv(s),m=!!(p!=null&&p.multiSelect),u=t.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${l}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let T=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=T,x.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let T=yv(p,n,a,o);C.replaceWith(T)}if(o!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(Lx(n,o))}let S=t.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!S?t.appendChild(bv(n)):(!m||i)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let k=t.querySelector('[data-ask-nav-row="true"]');if(i){let T=wv(d,l,n);k?k.replaceWith(T):t.appendChild(T)}else k&&k.remove();Ix(t),Rx(t)},Sv=(t,e,r)=>{let n=Fl(e),o=uv(n),s=t.toolCall.id,a=Ks(r),i=Math.max(1,a.length),d=i>1,l=Cv(t,a),p=d?Av(t,i):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(qa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(eu,String(i)),m.setAttribute(Zp,String(p)),m.setAttribute(tu,d?"true":"false"),m.setAttribute(Tx,o),Px(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),kx(m,n);let u=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=v("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",u.appendChild(f);let x=v("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),m.appendChild(u);let S=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),o!=="rows"&&m.appendChild(Lx(n,o)),ru(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Tv=(t,e,r)=>{let{payload:n}=xo(e),o=Math.max(1,Ks(n).length);o>za(t)&&(t.setAttribute(eu,String(o)),o>1&&!No(t)&&t.setAttribute(tu,"true")),ru(t,e,r)},Wx=(t,e)=>{let r=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Fl(e);kx(r,n);let o=v("span","persona-ask-stub-label"),{complete:s}=xo(t);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},Va=(t,e,r)=>{if(!r||!ho(t)||Fl(e).enabled===!1)return;let o=t.toolCall.id;r.querySelectorAll(`[${qa}]`).forEach(l=>{l.getAttribute(qa)!==o&&l.remove()});let a=r.querySelector(`[${qa}="${Mx(o)}"]`);if(a){Tv(a,t,e);return}let{payload:i}=xo(t),d=Sv(t,e,i);r.appendChild(d)},_o=(t,e)=>{if(!t)return;let r=e?`[${qa}="${Mx(e)}"]`:`[${qa}]`;t.querySelectorAll(r).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},nu=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Fo=(t,e)=>{let r=ma(t),n=En(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete r[n]:r[n]=e,Px(t,r),Ix(t),Rx(t)},Ul=(t,e,r,n)=>{let o=za(t),s=Math.max(0,Math.min(o-1,n));vv(t,s),ru(t,e,r)};var ou=(t,e)=>{var C,S,k,T,M,h,w,y,E,B,P,R;let r=t.approval,n=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(C=n==null?void 0:n.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(S=n==null?void 0:n.borderColor)!=null?S:"var(--persona-approval-border, #fef08a)",!r)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=v("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(k=n==null?void 0:n.titleColor)!=null?k:"currentColor",p=Ie(d,20,l,2);p&&i.appendChild(p);let m=v("div","persona-flex-1 persona-min-w-0"),u=v("div","persona-flex persona-items-center persona-gap-2"),f=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(T=n==null?void 0:n.title)!=null?T:"Approval Required",u.appendChild(f),!o){let O=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",r.status),r.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):r.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):r.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),u.appendChild(O)}m.appendChild(u);let x=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(x.style.color=n.descriptionColor),x.textContent=r.description,m.appendChild(x),r.parameters){let O=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Ra(r.parameters),m.appendChild(O)}if(o){let O=v("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let V=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=(M=n==null?void 0:n.approveButtonColor)!=null?M:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(h=n==null?void 0:n.approveButtonTextColor)!=null?h:"#ffffff",V.setAttribute("data-approval-action","approve");let ne=Ie("shield-check",14,(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",2);ne&&(ne.style.marginRight="4px",V.appendChild(ne));let be=document.createTextNode((y=n==null?void 0:n.approveLabel)!=null?y:"Approve");V.appendChild(be);let Ye=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Ye.type="button",Ye.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",Ye.style.color=(B=n==null?void 0:n.denyButtonTextColor)!=null?B:"var(--persona-feedback-error, #dc2626)",Ye.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ye.setAttribute("data-approval-action","deny");let Ge=Ie("shield-x",14,(P=n==null?void 0:n.denyButtonTextColor)!=null?P:"var(--persona-feedback-error, #dc2626)",2);Ge&&(Ge.style.marginRight="4px",Ye.appendChild(Ge));let ve=document.createTextNode((R=n==null?void 0:n.denyLabel)!=null?R:"Deny");Ye.appendChild(ve),O.append(V,Ye),m.appendChild(O)}return a.append(i,m),s.appendChild(a),s};var Bx=t=>{let e=[];return{buttons:e,render:(n,o,s,a,i)=>{if(t.innerHTML="",e.length=0,!n||!n.length||(a!=null?a:o?o.getMessages():[]).some(f=>f.role==="user"))return;let p=document.createDocumentFragment(),m=o?o.isStreaming():!1,u=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let x=v("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=f,x.disabled=m,i!=null&&i.fontFamily&&(x.style.fontFamily=u(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),p.appendChild(x),e.push(x)}),t.appendChild(p)}}};var Xs=class{constructor(e=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=r}push(e){var r;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(r=this.store)==null||r.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let r=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let n of r)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=e.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let r=this.getAll();return e>=r.length?r:r.slice(r.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(e="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=r}open(){return new Promise((e,r)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}getAll(){return new Promise((e,r)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{r(a.error)}}catch(n){r(n)}})}getCount(){return new Promise((e,r)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}clear(){return new Promise((e,r)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{r(s.error)}}catch(n){r(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,r)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{e()},n.onerror=()=>{r(n.error)}}catch(n){r(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}};var Mv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),kv=new Set(["step_start","execution_start"]),Ev=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Lv=new Set(["step_complete","agent_turn_complete"]),Pv=new Set(["flow_complete","agent_complete"]),Hx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ox=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ga=(t,e)=>{let r=t[e];return Ox(r)?r:void 0};function au(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ql(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Iv(t,e){return typeof e.type=="string"?e.type:t}function Rv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Wv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Dx(t){var n,o,s,a,i;let e=ga(t,"result"),r=[ga(t,"tokens"),ga(t,"totalTokens"),e?ga(e,"tokens"):void 0,ga(t,"usage"),e?ga(e,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=bn(d.output))!=null?n:bn(d.outputTokens))!=null?o:bn(d.completionTokens);if(l!==void 0)return l}return(i=(s=bn(t.outputTokens))!=null?s:bn(t.completionTokens))!=null?i:e?(a=bn(e.outputTokens))!=null?a:bn(e.completionTokens):void 0}function Bv(t){var r,n,o,s,a;let e=ga(t,"result");return(a=(o=(n=(r=bn(t.executionTime))!=null?r:bn(t.executionTimeMs))!=null?n:bn(t.execution_time))!=null?o:bn(t.duration))!=null?a:e?(s=bn(e.executionTime))!=null?s:bn(e.executionTimeMs):void 0}function Hv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(e=Hv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:ql(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,r){var s;if(!Ox(r)){Hx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=Iv(e,r),o=this.now();if(Mv.has(n)){this.startRun(o);return}if(kv.has(n)){this.run||this.startRun(o);return}if(Ev.has(n)){if(!Wv(n,r))return;let a=Rv(r);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+au(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ql(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Lv.has(n)){if(!this.run)return;let a=this.run,i=Dx(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+au(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:ql(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Pv.has(n)){if(!this.run)return;let a=this.run,i=Dx(r),d=i!=null?i:a.exactOutputTokens+au(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:ql(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Hx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,r,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Bv(r);return s!=null?s:n-e.startedAt}};function ja(t,e){e&&e.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Dv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Ov={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Nv=["flowName","stepName","reasoningText","text","name","tool","toolName"],_v=100;function Fv(t,e){let r={...Dv,...e};if(r[t])return r[t];for(let n of Object.keys(r))if(n.endsWith("_")&&t.startsWith(n))return r[n];return Ov}function $v(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Uv(t){let e=new Date(t),r=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${r}:${n}:${o}.${s}`}function qv(t,e){try{let r=JSON.parse(t);if(typeof r!="object"||r===null)return null;for(let n of e){let o=n.split("."),s=r;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function zv(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(r=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),r()})}function Vv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function jv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Gv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Kv(t,e,r){let n,o;try{o=JSON.parse(t.payload),n=JSON.stringify(o,null,2)}catch{o=t.payload,n=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let i=s.renderEventStreamPayload({event:t,config:r,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function su(t,e,r,n,o,s,a,i){var u;let d=o.has(t.id),l=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ja(l,(u=n.classNames)==null?void 0:u.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(f)return l.appendChild(f),l}return l.appendChild(m()),l;function m(){var V,ne;let f=v("div",""),x=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",t.id);let C=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=Ie(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&C.appendChild(S);let k=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(V=n.timestampFormat)!=null?V:"relative";k.textContent=T==="relative"?$v(t.timestamp,r):Uv(t.timestamp);let M=null;n.showSequenceNumbers!==!1&&(M=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let h=Fv(t.type,n.badgeColors),w=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=h.bg,w.style.color=h.text,w.style.borderColor=h.text+"50",w.textContent=t.type;let y=(ne=n.descriptionFields)!=null?ne:Nv,E=qv(t.payload,y),B=null;E&&(B=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=E);let P=v("div","persona-flex-1 persona-min-w-0"),R=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=Ie("clipboard","12px","currentColor",1.5);return O&&R.appendChild(O),R.addEventListener("click",async be=>{be.stopPropagation(),await zv(Vv(t)),R.innerHTML="";let Ye=Ie("check","12px","currentColor",1.5);Ye&&R.appendChild(Ye),setTimeout(()=>{R.innerHTML="";let Ge=Ie("clipboard","12px","currentColor",1.5);Ge&&R.appendChild(Ge)},1500)}),x.appendChild(C),x.appendChild(k),M&&x.appendChild(M),x.appendChild(w),B&&x.appendChild(B),x.appendChild(P),x.appendChild(R),f.appendChild(x),d&&f.appendChild(Kv(t,a,i)),f}}function Nx(t){var x,C,S,k,T;let{buffer:e,getFullHistory:r,onClose:n,config:o,plugins:s=[],getThroughput:a}=t,i=(x=o==null?void 0:o.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",m=(T=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?T:{},u=s.find(M=>M.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let M=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=m.classNames,h=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ja(h,M==null?void 0:M.panel);let w=[],y="",E="",B=null,P=[],R={},O=0,V=Al(),ne=0,be=0,Ye=!1,Ge=null,ve=!1,Ee=0,Ke=new Set,Ne=new Map,X="",Ue="",K=null,Te,oe,xe,Me,Xe,ce=null,te=null,le=null;function ut(){let de=v("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ye=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");ja(ye,M==null?void 0:M.headerBar);let Rt=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Rt.textContent="Events",Te=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Te.textContent="0",a){te=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let dr=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");dr.textContent="Throughput",ce=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ce.textContent="-- tok/s",le=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let wr=te,Lr=le,Or=()=>{if(!Lr.textContent)return;let sn=wr.getBoundingClientRect(),fr=de.getBoundingClientRect();Lr.style.left=`${sn.left-fr.left}px`,Lr.style.top=`${sn.bottom-fr.top+4}px`,Lr.style.display="block"},xt=()=>{Lr.style.display="none"};te.addEventListener("mouseenter",Or),te.addEventListener("mouseleave",xt),te.appendChild(dr),te.appendChild(ce)}let ar=v("div","persona-flex-1");oe=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let kt=v("option","");kt.value="",kt.textContent="All events",oe.appendChild(kt),xe=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),xe.type="button",xe.title="Copy All";let Ot=Ie("clipboard-copy","12px","currentColor",1.5);Ot&&xe.appendChild(Ot);let Wt=v("span","persona-text-xs");Wt.textContent="Copy All",xe.appendChild(Wt),ye.appendChild(Rt),ye.appendChild(Te),te&&ye.appendChild(te),ye.appendChild(ar),ye.appendChild(oe),ye.appendChild(xe);let St=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ja(St,M==null?void 0:M.searchBar);let Et=Ie("search","14px","var(--persona-muted, #9ca3af)",1.5),sr=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Et&&sr.appendChild(Et),Me=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ja(Me,M==null?void 0:M.searchInput),Me.type="text",Me.placeholder="Search event payloads...",Xe=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Xe.type="button",Xe.style.display="none";let ft=Ie("x","12px","currentColor",2);return ft&&Xe.appendChild(ft),St.appendChild(sr),St.appendChild(Me),St.appendChild(Xe),de.appendChild(ye),de.appendChild(St),le&&de.appendChild(le),de}let Ce,he=s.find(de=>de.renderEventStreamToolbar);if(he!=null&&he.renderEventStreamToolbar&&o){let de=he.renderEventStreamToolbar({config:o,defaultRenderer:()=>ut(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ye=>{y=ye,pe(),_()},onSearchChange:ye=>{E=ye,pe(),_()}});Ce=de!=null?de:ut()}else Ce=ut();let rt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");rt.style.display="none";function _e(){if(!a||!ce||!te)return;let de=a();ce.textContent=jv(de);let ye=Gv(de);le&&(le.textContent=ye,ye||(le.style.display="none")),ye?te.setAttribute("aria-label",ye):te.removeAttribute("aria-label")}let me=v("div","persona-flex-1 persona-min-h-0 persona-relative"),J=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ze=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ja(ze,M==null?void 0:M.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Z=Ie(l,"14px","currentColor",2);Z&&ze.appendChild(Z);let ge=v("span","");ge.textContent=p,ze.appendChild(ge);let z=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");z.style.display="none",me.appendChild(J),me.appendChild(z),me.appendChild(ze),h.setAttribute("tabindex","0"),h.appendChild(Ce),h.appendChild(rt),h.appendChild(me);function Re(){let de=e.getAll(),ye={};for(let Wt of de)ye[Wt.type]=(ye[Wt.type]||0)+1;let Rt=Object.keys(ye).sort(),ar=Rt.length!==P.length||!Rt.every((Wt,St)=>Wt===P[St]),kt=!ar&&Rt.some(Wt=>ye[Wt]!==R[Wt]),mr=de.length!==Object.values(R).reduce((Wt,St)=>Wt+St,0);if(!ar&&!kt&&!mr||(P=Rt,R=ye,!oe))return;let Ot=oe.value;if(oe.options[0].textContent="All events",ar){for(;oe.options.length>1;)oe.remove(1);for(let Wt of Rt){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${ye[Wt]||0})`,oe.appendChild(St)}Ot&&Rt.includes(Ot)?oe.value=Ot:Ot&&(oe.value="",y="")}else for(let Wt=1;Wt<oe.options.length;Wt++){let St=oe.options[Wt];St.textContent=`${St.value} (${ye[St.value]||0})`}}function Ae(){let de=e.getAll();if(y&&(de=de.filter(ye=>ye.type===y)),E){let ye=E.toLowerCase();de=de.filter(Rt=>Rt.type.toLowerCase().includes(ye)||Rt.payload.toLowerCase().includes(ye))}return de}function fe(){return y!==""||E!==""}function pe(){O=0,ne=0,V.resume(),ze.style.display="none"}function Be(de){Ke.has(de)?Ke.delete(de):Ke.add(de),K=de;let ye=J.scrollTop,Rt=V.isFollowing();ve=!0,V.pause(),_(),J.scrollTop=ye,Rt&&V.resume(),ve=!1}function Q(){return _s(J,50)}function _(){be=Date.now(),Ye=!1,_e(),Re();let de=e.getEvictedCount();de>0?(rt.textContent=`${de.toLocaleString()} older events truncated`,rt.style.display=""):rt.style.display="none",w=Ae();let ye=w.length,Rt=e.getSize()>0;Te&&(Te.textContent=String(e.getSize())),ye===0&&Rt&&fe()?(z.textContent=E?`No events matching '${E}'`:"No events matching filter",z.style.display="",J.style.display="none"):(z.style.display="none",J.style.display=""),xe&&(xe.title=fe()?`Copy Filtered (${ye})`:"Copy All"),d&&!V.isFollowing()&&ye>O&&(ne+=ye-O,ge.textContent=p?`${p}${ne>0?` (${ne})`:""}`:"",ze.style.display=""),O=ye;let ar=e.getAll(),kt=ar.length>0?ar[0].timestamp:0,mr=new Set(w.map(St=>St.id));for(let St of Ke)mr.has(St)||Ke.delete(St);let Ot=y!==X||E!==Ue,Wt=Ne.size===0&&w.length>0;if(Ot||Wt||w.length===0){J.innerHTML="",Ne.clear();let St=document.createDocumentFragment();for(let Et=0;Et<w.length;Et++){let sr=su(w[Et],Et,kt,m,Ke,Be,s,o);Ne.set(w[Et].id,sr),St.appendChild(sr)}J.appendChild(St),X=y,Ue=E,K=null}else{if(K!==null){let Et=Ne.get(K);if(Et&&Et.parentNode===J){let sr=w.findIndex(ft=>ft.id===K);if(sr>=0){let ft=su(w[sr],sr,kt,m,Ke,Be,s,o);J.insertBefore(ft,Et),Et.remove(),Ne.set(K,ft)}}K=null}let St=new Set(w.map(Et=>Et.id));for(let[Et,sr]of Ne)St.has(Et)||(sr.remove(),Ne.delete(Et));for(let Et=0;Et<w.length;Et++){let sr=w[Et];if(!Ne.has(sr.id)){let ft=su(sr,Et,kt,m,Ke,Be,s,o);Ne.set(sr.id,ft),J.appendChild(ft)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function ke(){if(Date.now()-be>=_v){Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),_();return}Ye||(Ye=!0,Ge=requestAnimationFrame(()=>{Ge=null,_()}))}let He=(de,ye)=>{if(!xe)return;xe.innerHTML="";let Rt=Ie(de,"12px","currentColor",1.5);Rt&&xe.appendChild(Rt);let ar=v("span","persona-text-xs");ar.textContent="Copy All",xe.appendChild(ar),setTimeout(()=>{xe.innerHTML="";let kt=Ie("clipboard-copy","12px","currentColor",1.5);kt&&xe.appendChild(kt);let mr=v("span","persona-text-xs");mr.textContent="Copy All",xe.appendChild(mr),xe.disabled=!1},ye)},Ve=async()=>{if(xe){xe.disabled=!0;try{let de;fe()?de=w:r?(de=await r(),de.length===0&&(de=e.getAll())):de=e.getAll();let ye=de.map(Rt=>{try{return JSON.parse(Rt.payload)}catch{return Rt.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),He("check",1500)}catch{He("x",1500)}}},Je=()=>{oe&&(y=oe.value,pe(),_())},gt=()=>{!Me||!Xe||(Xe.style.display=Me.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{E=Me.value,pe(),_()},150))},at=()=>{!Me||!Xe||(Me.value="",E="",Xe.style.display="none",B&&clearTimeout(B),pe(),_())},Mt=()=>{if(ve)return;let de=J.scrollTop,{action:ye,nextLastScrollTop:Rt}=Sl({following:V.isFollowing(),currentScrollTop:de,lastScrollTop:Ee,nearBottom:Q(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ee=Rt,ye==="resume"?(V.resume(),ne=0,ze.style.display="none"):ye==="pause"&&(V.pause(),d&&(ge.textContent=p,ze.style.display=""))},Xt=de=>{let ye=Tl({following:V.isFollowing(),deltaY:de.deltaY,nearBottom:Q(),resumeWhenNearBottom:!0});ye==="pause"?(V.pause(),d&&(ge.textContent=p,ze.style.display="")):ye==="resume"&&(V.resume(),ne=0,ze.style.display="none")},G=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),ne=0,ze.style.display="none")},Jt=de=>{let ye=de.target;if(!ye||ye.closest("button"))return;let Rt=ye.closest("[data-event-id]");if(!Rt)return;let ar=Rt.getAttribute("data-event-id");ar&&Be(ar)},st=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),Me==null||Me.focus(),Me==null||Me.select();return}de.key==="Escape"&&(Me&&document.activeElement===Me?(at(),Me.blur(),h.focus()):n&&n())};xe&&xe.addEventListener("click",Ve),oe&&oe.addEventListener("change",Je),Me&&Me.addEventListener("input",gt),Xe&&Xe.addEventListener("click",at),J.addEventListener("scroll",Mt),J.addEventListener("wheel",Xt,{passive:!0}),J.addEventListener("click",Jt),ze.addEventListener("click",G),h.addEventListener("keydown",st);function _t(){B&&clearTimeout(B),Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),Ye=!1,Ne.clear(),xe&&xe.removeEventListener("click",Ve),oe&&oe.removeEventListener("change",Je),Me&&Me.removeEventListener("input",gt),Xe&&Xe.removeEventListener("click",at),J.removeEventListener("scroll",Mt),J.removeEventListener("wheel",Xt),J.removeEventListener("click",Jt),ze.removeEventListener("click",G),h.removeEventListener("keydown",st)}return{element:h,update:ke,destroy:_t}}}function _x(t,e){let r=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",n=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(u);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(l.append(p,m),i.append(d,l),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",n),i.append(u)}return i}var Fx=(t,e)=>{var n,o,s;let r=(s=(o=(n=e==null?void 0:e.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(r){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=r({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:e.config,defaultRenderer:()=>_x(t,e)});if(p)return p}return _x(t,e)};var iu=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,n])=>{this.register(r,n)})}},yo=new iu;yo.register("PersonaArtifactCard",Fx);function Xv(t){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=v("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=t.component?`Component: ${t.component}`:"Component";let n=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(r),e.appendChild(n),e}function $x(t,e){var oe,xe,Me,Xe;let r=(xe=(oe=t.features)==null?void 0:oe.artifacts)==null?void 0:xe.layout,o=((Me=r==null?void 0:r.toolbarPreset)!=null?Me:"default")==="document",s=(Xe=r==null?void 0:r.panePadding)==null?void 0:Xe.trim(),a=t.markdown?na(t.markdown):null,i=Ea(t.sanitize),d=ce=>{let te=a?a(ce):oa(ce);return i?i(te):te},l=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let m=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),o&&m.classList.add("persona-artifact-pane-document");let u=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let f=v("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let x=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let C="rendered",S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),k=o?Er({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Er({icon:"eye",label:"Rendered view"}),T=o?Er({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Er({icon:"code-2",label:"Source"}),M=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),h=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,y=r==null?void 0:r.documentToolbarCopyMenuItems,E=!!(w&&y&&y.length>0),B=null,P,R=null,O=null;if(o&&(h||w)&&!E){if(P=h?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ce=Ie("chevron-down",14,"currentColor",2);ce&&P.appendChild(ce)}}else o&&E?(B=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),P=h?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Er({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),B.append(P,R)):o?P=Er({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):P=Er({icon:"copy",label:"Copy"});let V=o?Er({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Er({icon:"refresh-cw",label:"Refresh"}),ne=o?Er({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Er({icon:"x",label:"Close"}),be=()=>{var Ce,he,rt;let ce=(Ce=Ne.find(_e=>_e.id===X))!=null?Ce:Ne[Ne.length-1],te=(he=ce==null?void 0:ce.id)!=null?he:null,le=(ce==null?void 0:ce.artifactType)==="markdown"&&(rt=ce.markdown)!=null?rt:"",ut=ce?JSON.stringify({component:ce.component,props:ce.props},null,2):"";return{markdown:le,jsonPayload:ut,id:te}},Ye=async()=>{var Ce;let{markdown:ce,jsonPayload:te}=be(),le=(Ce=Ne.find(he=>he.id===X))!=null?Ce:Ne[Ne.length-1],ut=(le==null?void 0:le.artifactType)==="markdown"?ce:le?te:"";try{await navigator.clipboard.writeText(ut)}catch{}};if(P.addEventListener("click",async()=>{let ce=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ce&&E){let{markdown:te,jsonPayload:le,id:ut}=be();try{await ce({actionId:"primary",artifactId:ut,markdown:te,jsonPayload:le})}catch{}return}await Ye()}),R&&(y!=null&&y.length)){let ce=()=>{var le;return(le=m.closest("[data-persona-root]"))!=null?le:document.body},te=()=>{O=Do({items:y.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:ut,jsonPayload:Ce,id:he}=be(),rt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{rt?await rt({actionId:le,artifactId:he,markdown:ut,jsonPayload:Ce}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(ut):le==="json"||le==="source"?await navigator.clipboard.writeText(Ce):await navigator.clipboard.writeText(ut||Ce)}catch{}},anchor:B!=null?B:R,position:"bottom-right",portal:ce()})};m.isConnected?te():requestAnimationFrame(te),R.addEventListener("click",le=>{le.stopPropagation(),O==null||O.toggle()})}V.addEventListener("click",async()=>{var ce;try{await((ce=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ce.call(r))}catch{}K()}),ne.addEventListener("click",()=>{var ce;p(),(ce=e.onDismiss)==null||ce.call(e)});let Ge=()=>{o&&(k.setAttribute("aria-pressed",C==="rendered"?"true":"false"),T.setAttribute("aria-pressed",C==="source"?"true":"false"))};k.addEventListener("click",()=>{C="rendered",Ge(),K()}),T.addEventListener("click",()=>{C="source",Ge(),K()});let ve=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),S.append(k,T),B?M.append(B,V,ne):M.append(P,V,ne),u.append(S,ve,M),Ge()):(u.appendChild(f),u.appendChild(x)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Ee=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Ke=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ee.style.paddingLeft=s,Ee.style.paddingRight=s,Ke.style.padding=s),m.appendChild(u),m.appendChild(Ee),m.appendChild(Ke);let Ne=[],X=null,Ue=!1,K=()=>{var ut,Ce,he,rt;let ce=o&&Ne.length<=1;Ee.classList.toggle("persona-hidden",ce),Ee.replaceChildren();for(let _e of Ne){let me=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");me.type="button",me.textContent=_e.title||_e.id.slice(0,8),_e.id===X&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>e.onSelect(_e.id)),Ee.appendChild(me)}Ke.replaceChildren();let te=X&&Ne.find(_e=>_e.id===X)||Ne[Ne.length-1];if(!te)return;if(o){let _e=te.artifactType==="markdown"?"MD":(ut=te.component)!=null?ut:"Component",J=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${J} \xB7 ${_e}`}else f.textContent="Artifacts";if(te.artifactType==="markdown"){if(o&&C==="source"){let me=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(Ce=te.markdown)!=null?Ce:"",Ke.appendChild(me);return}let _e=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");_e.innerHTML=d((he=te.markdown)!=null?he:""),Ke.appendChild(_e);return}let le=te.component?yo.get(te.component):void 0;if(le){let me={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let J=le((rt=te.props)!=null?rt:{},me);if(J){Ke.appendChild(J);return}}catch{}}Ke.appendChild(Xv(te))},Te=()=>{var te;let ce=Ne.length>0;if(m.classList.toggle("persona-hidden",!ce),l){let le=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ce=((te=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ce&&Ce&&Ue?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(ce){var te,le,ut;Ne=ce.artifacts,X=(ut=(le=ce.selectedId)!=null?le:(te=ce.artifacts[ce.artifacts.length-1])==null?void 0:te.id)!=null?ut:null,Ne.length>0&&(Ue=!0),K(),Te()},setMobileOpen(ce){Ue=ce,!ce&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Te()}}}function Ln(t){var e,r;return((r=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:r.enabled)===!0}function Ux(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Ln(e))return;let r=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,n=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),o=(d=r==null?void 0:r.paneBorderLeft)==null?void 0:d.trim();n?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",n)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function Jv(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function zl(t,e){var d,l,p,m,u,f,x,C,S,k;if(!Ln(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Jv(t),Ux(t,e);return}let r=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;t.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(m=r==null?void 0:r.paneWidth)!=null?m:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=r==null?void 0:r.paneBackground)==null?void 0:f.trim();n?t.style.setProperty("--persona-artifact-pane-bg",n):t.style.removeProperty("--persona-artifact-pane-bg");let o=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(k=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:k.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ux(t,e)}var qx=["panel","seamless"];function Vl(t,e){var i,d,l,p,m,u;for(let f of qx)t.classList.remove(`persona-artifact-appearance-${f}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!Ln(e))return;let r=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",o=qx.includes(n)?n:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=r==null?void 0:r.paneShadow)==null?void 0:m.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(r==null?void 0:r.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let f=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;f&&t.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function zx(t,e){var r,n,o;return!e||!Ln(t)?!1:((o=(n=(r=t.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Qv(t,e){if(!(t!=null&&t.trim()))return e;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return r?Math.max(0,Number(r[1])):e}function Yv(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Zv(t,e,r){return r<e?e:Math.min(r,Math.max(e,t))}function eC(t,e,r,n){let o=t-n-2*e-r;return Math.max(0,o)}function Vx(t,e){var a;let n=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(n);return s?Number(s[1]):8}function jx(t,e,r,n,o,s){let a=Qv(o,200),i=eC(e,r,n,200);i=Math.max(a,i);let d=Yv(s);return d!==null&&(i=Math.min(i,d)),Zv(t,a,i)}var Gx={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},lu=(t,e,r,n)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,C,S;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(C=Gx[a])!=null?C:Gx.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),l=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let k=v("p","persona-text-sm persona-text-persona-muted");k.textContent=i.description,d.appendChild(k)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(k=>{var y,E;let T=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${k.name}`;let M=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=k.label,T.appendChild(M);let h=(y=k.type)!=null?y:"text",w;h==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=h),w.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",w.id=`${e.id}-${a}-${k.name}`,w.name=k.name,w.placeholder=(E=k.placeholder)!=null?E:"",k.required&&(w.required=!0),T.appendChild(w),p.appendChild(T)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(S=i.submitLabel)!=null?S:"Submit",m.appendChild(u),m.appendChild(f),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async k=>{var w,y;k.preventDefault();let T=(w=r.formEndpoint)!=null?w:"/form",M=new FormData(p),h={};M.forEach((E,B)=>{h[B]=E}),h.type=a,f.disabled=!0,u.textContent="Submitting\u2026";try{let E=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let B=await E.json();u.textContent=(y=B.message)!=null?y:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await n.sendMessage(String(B.nextPrompt))}catch(E){u.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var du=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var n;let r=this.plugins.get(e);r&&((n=r.onUnregister)==null||n.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var n,o;return((n=r.priority)!=null?n:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let n=new Set(e.map(s=>s.id));return[...r.filter(s=>!n.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},Ys=new du;var Kx=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var tC=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},rC=t=>{let e=t.trim(),r=e.indexOf("{");if(r===-1)return null;let n=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(n+=1),s==="}"&&(n-=1,n===0))return e.slice(r,o+1)}return null},Zs=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=tC(t),r=rC(e);if(!r)return null;let n=JSON.parse(r);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...s}=n;return{type:String(o),payload:s,raw:n}}catch{return null}},cu=t=>typeof t=="string"?t:t==null?"":String(t),ha={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:cu(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,n=cu(r.element);if(n&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(n);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:cu(r.text)}}},Xx=t=>Array.isArray(t)?t.map(e=>String(e)):[],ei=t=>{let e=new Set(Xx(t.getSessionMetadata().processedActionMessageIds)),r=()=>{e=new Set(Xx(t.getSessionMetadata().processedActionMessageIds))},n=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),n();let d={action:i,message:s.message};t.emit("action:detected",d);for(let l of t.handlers)if(l)try{let p=()=>{t.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let u=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:u,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var nC=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},oC=t=>t.map(e=>({...e,streaming:!1})),aC=t=>t.map(e=>({...e,status:"complete"})),jl=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?nC(r.getItem(t)):null},save:r=>{let n=e();if(n)try{let o={...r,messages:r.messages?oC(r.messages):void 0,artifacts:r.artifacts?aC(r.artifacts):void 0};n.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(t)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Ga=ad(qi(),1);function sC(t){if(!t||typeof t!="object"||!("component"in t))return!1;let e=t.component;return typeof e=="string"&&e.length>0}function iC(t,e){if(!sC(t))return null;let r=t.props&&typeof t.props=="object"&&t.props!==null?t.props:{};return{component:t.component,props:r,raw:e}}function Gl(){let t=null,e=0;return{getExtractedDirective:()=>t,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=e)return t;try{let o=(0,Ga.parse)(r,Ga.STR|Ga.OBJ),s=iC(o,r);s&&(t=s)}catch{}return e=r.length,t},reset:()=>{t=null,e=0}}}function Jx(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function Kl(t,e){let{config:r,message:n,onPropsUpdate:o}=e,s=yo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:r,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Qx(){let t=Gl();return{processChunk:e=>t.processChunk(e),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function Yx(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Xl(t){let e=Yx(t);if(!e)return!1;try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Jl(t){let e=Yx(t);if(!e)return null;try{let r=JSON.parse(e);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let n=r;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e}}}catch{}return null}var lC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ql(t){let{onSubmit:e,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=lC}=t,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,u=document.createElement("div");u.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,f.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=o,f.appendChild(C),u.appendChild(f);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let y=1;y<=5;y++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${y} star${y>1?"s":""}: ${l[y-1]}`),E.title=l[y-1],E.dataset.rating=String(y),E.innerHTML=`
73
+ `,r.addEventListener("click",e);let n=s=>{var M,h,C,v,T,W,P,R,N,j,ce,be,Ze;let a=(M=s.launcher)!=null?M:{},i=Br(s),d=r.querySelector("[data-role='launcher-title']");if(d){let Se=(h=a.title)!=null?h:"Chat Assistant";d.textContent=Se,d.setAttribute("title",Se)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let Se=(C=a.subtitle)!=null?C:"Get answers fast";l.textContent=Se,l.setAttribute("title",Se)}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 Se=(v=a.agentIconSize)!=null?v:"40px";if(u.style.height=Se,u.style.width=Se,u.innerHTML="",a.agentIconName){let Ne=parseFloat(Se)||24,Ce=Ie(a.agentIconName,Ne*.6,"var(--persona-text-inverse, #ffffff)",2);Ce?(u.appendChild(Ce),u.style.display=""):(u.textContent=(T=a.agentIconText)!=null?T:"\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 Se=(P=a.agentIconSize)!=null?P:"40px";f.style.height=Se,f.style.width=Se,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 Se=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=Se,m.style.width=Se,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 Ne=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ne=(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 Ce=parseFloat(Se)||24,Fe=Math.max(Ce-Ne,8),We=Ie(a.callToActionIconName,Fe,"currentColor",2);We?m.appendChild(We):m.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}let y=a.position&&Xn[a.position]?Xn[a.position]:Xn["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((ce=a.zIndex)!=null?ce:Qr));let k="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))";r.style.border=(be=a.border)!=null?be:k,r.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,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=(Ze=a.collapsedMaxWidth)!=null?Ze:"",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 Av="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",_l=(t,e={})=>{var x,S,k,E,M,h;let{showClose:r=!0,wrapperClassName:n=Av,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=w("div",n),l=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(k=a.closeButtonTooltipText)!=null?k:"Close chat",u=(E=a.closeButtonShowTooltip)!=null?E:!0;l.setAttribute("aria-label",p),l.style.display=r?"":"none";let f=(M=a.closeButtonIconName)!=null?M:"x",m=(h=a.closeButtonIconText)!=null?h:"\xD7";l.style.color=a.closeButtonColor||sn.actionIconColor;let y=Ie(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",v=a.closeButtonBorderColor||"transparent";l.style.border=`${C} solid ${v}`,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,v=()=>{if(C)return;let W=l.ownerDocument,P=W.body;if(!P)return;C=lo(W,"div","persona-clear-chat-tooltip"),C.textContent=p;let R=lo(W,"div");R.className="persona-clear-chat-tooltip-arrow",C.appendChild(R);let N=l.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Vo),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)},T=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",T),l.addEventListener("focus",v),l.addEventListener("blur",T),d._cleanupTooltip=()=>{T(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",T),l.removeEventListener("focus",v),l.removeEventListener("blur",T)}}return{button:l,wrapper:d}},Sv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Fl=(t,e={})=>{var C,v,T,W,P,R,N,j,ce,be,Ze,Se,Ne;let{wrapperClassName:r=Sv,buttonSize:n,iconSize:o="20px"}=e,a=(v=((C=t==null?void 0:t.launcher)!=null?C:{}).clearChat)!=null?v:{},i=(T=n!=null?n:a.size)!=null?T:"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=(ce=a.borderRadius)!=null?ce:"",y=(be=a.paddingX)!=null?be:"",x=(Ze=a.paddingY)!=null?Ze:"",S=(Se=a.tooltipText)!=null?Se:"Clear chat",k=(Ne=a.showTooltip)!=null?Ne:!0,E=w("div",r),M=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",S),M.style.color=l||sn.actionIconColor;let h=Ie(d,o,"currentColor",1);if(h&&(h.style.display="block",M.appendChild(h)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),u||f){let Ce=u||"0px",Fe=f||"transparent";M.style.border=`${Ce} solid ${Fe}`,M.classList.remove("persona-border-none")}if(m&&(M.style.borderRadius=m,M.classList.remove("persona-rounded-full")),y&&(M.style.paddingLeft=y,M.style.paddingRight=y),x&&(M.style.paddingTop=x,M.style.paddingBottom=x),E.appendChild(M),k&&S){let Ce=null,Fe=()=>{if(Ce)return;let Z=M.ownerDocument,ne=Z.body;if(!ne)return;Ce=lo(Z,"div","persona-clear-chat-tooltip"),Ce.textContent=S;let ee=lo(Z,"div");ee.className="persona-clear-chat-tooltip-arrow",Ce.appendChild(ee);let we=M.getBoundingClientRect();Ce.style.position="fixed",Ce.style.zIndex=String(Vo),Ce.style.left=`${we.left+we.width/2}px`,Ce.style.top=`${we.top-8}px`,Ce.style.transform="translate(-50%, -100%)",ne.appendChild(Ce)},We=()=>{Ce&&Ce.parentNode&&(Ce.parentNode.removeChild(Ce),Ce=null)};E.addEventListener("mouseenter",Fe),E.addEventListener("mouseleave",We),M.addEventListener("focus",Fe),M.addEventListener("blur",We),E._cleanupTooltip=()=>{We(),E.removeEventListener("mouseenter",Fe),E.removeEventListener("mouseleave",We),M.removeEventListener("focus",Fe),M.removeEventListener("blur",We)}}return{button:M,wrapper:E}};var sn={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))"},Mo=t=>{var C,v,T,W,P,R,N,j,ce,be,Ze,Se,Ne,Ce,Fe,We;let{config:e,showClose:r=!0}=t,n=w("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=(v=o.headerIconSize)!=null?v:"48px",a=(T=o.closeButtonPlacement)!=null?T:"inline",i=(W=o.headerIconHidden)!=null?W:!1,d=o.headerIconName,l=w("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 Z=parseFloat(s)||24,ne=Ie(d,Z*.6,"currentColor",1);ne?l.replaceChildren(ne):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 Z=w("img");Z.src=e.launcher.iconUrl,Z.alt="",Z.className="persona-rounded-xl persona-object-cover",Z.style.height=s,Z.style.width=s,l.replaceChildren(Z)}else l.textContent=(ce=(j=e==null?void 0:e.launcher)==null?void 0:j.agentIconText)!=null?ce:"\u{1F4AC}";let p=w("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=w("span","persona-text-base persona-font-semibold");u.style.color=sn.titleColor,u.textContent=(Ze=(be=e==null?void 0:e.launcher)==null?void 0:be.title)!=null?Ze:"Chat Assistant";let f=w("span","persona-text-xs");f.style.color=sn.subtitleColor,f.textContent=(Ne=(Se=e==null?void 0:e.launcher)==null?void 0:Se.subtitle)!=null?Ne:"Here to help you get answers fast",p.append(u,f),i?n.append(p):n.append(l,p);let m=(Ce=o.clearChat)!=null?Ce:{},y=(Fe=m.enabled)!=null?Fe:!0,x=(We=m.placement)!=null?We:"inline",S=null,k=null;if(y){let ne=Fl(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=ne.button,k=ne.wrapper,x==="top-right"&&(k.style.right="48px"),x==="inline"&&n.appendChild(k)}let E=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:M,wrapper:h}=_l(e,{showClose:r,wrapperClassName:E});return a!=="top-right"&&n.appendChild(h),{header:n,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:M,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:k}},Sa=(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 Ko(t){let{items:e,onSelect:r,anchor:n,position:o="bottom-left",portal:s}=t,a=w("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(Vo)):(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=Ie(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 Fr(t){let{icon:e,label:r,size:n,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=w("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",r),d.title=r;let l=Ie(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function ai(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=w("button",l);if(p.type="button",p.setAttribute("aria-label",r),e){let f=Ie(e,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=w("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 qx(t){let{items:e,selectedId:r,onSelect:n,className:o}=t,s=w("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=Fr({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=w("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 $l(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=w("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=w("span","persona-combo-btn-label");p.textContent=e,l.appendChild(p);let u=Ie(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=Ko({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 nu=t=>{var n;let e=Mo({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 Tv(t,e,r){var n,o,s;if(e!=null&&e.length)for(let a of e){let i=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=a.ariaLabel)!=null?n:a.label)!=null?o:a.id),a.icon){let d=Ie(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=w("div","persona-relative");d.appendChild(i);let l=Ko({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 ou=t=>{var E,M,h,C,v,T,W,P,R;let{config:e,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=w("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=$l({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=sn.titleColor,p=(h=l.querySelector(".persona-combo-btn-label"))!=null?h:l;else{if(l=w("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=w("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=sn.titleColor,p.textContent=(C=a.title)!=null?C:"Chat Assistant",l.appendChild(p),Tv(l,o==null?void 0:o.trailingActions,(v=o==null?void 0:o.onAction)!=null?v:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let j=o.onTitleClick;l.addEventListener("click",ce=>{ce.target.closest("button")||j()}),l.addEventListener("keydown",ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),j())})}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 j,ce;l.style.backgroundColor=(j=N.background)!=null?j:"",l.style.borderColor=(ce=N.border)!=null?ce:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(P=a.closeButtonSize)!=null?P:"32px",f=w("div",""),m=w("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||sn.actionIconColor;let y=(R=a.closeButtonIconName)!=null?R:"x",x=Ie(y,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let S=w("div");S.style.display="none";let k=w("span");return k.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:k,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ul={default:nu,minimal:ou},au=t=>{var e;return(e=Ul[t])!=null?e:Ul.default},Za=(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=w("div");p.style.display="none";let u=w("span"),f=w("span"),m=w("button");m.style.display="none";let y=w("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=au(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 ql=t=>{var a,i;let e=w("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}},zl=t=>{var C,v,T,W,P,R,N,j,ce,be,Ze,Se;let e=(C=t==null?void 0:t.sendButton)!=null?C:{},r=(v=e.useIcon)!=null?v:!1,n=(T=e.iconText)!=null?T:"\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=(be=(ce=t==null?void 0:t.copy)==null?void 0:ce.stopButtonLabel)!=null?be:"Stop",p=(Ze=e.showTooltip)!=null?Ze:!1,u=(Se=e.size)!=null?Se:"40px",f=e.backgroundColor,m=e.textColor,y=w("div","persona-send-button-wrapper"),x=w("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,k=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 Ne=parseFloat(u)||24,Ce=(m==null?void 0:m.trim())||"currentColor";o?(S=Ie(o,Ne,Ce,2),S?x.appendChild(S):x.textContent=n):x.textContent=n,k=Ie(s,Ne,Ce,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 E=null;p&&a&&(E=w("div","persona-send-button-tooltip"),E.textContent=a,y.appendChild(E)),x.setAttribute("aria-label",a),y.appendChild(x);let M="send";return{button:x,wrapper:y,setMode:Ne=>{if(Ne===M)return;M=Ne;let Ce=Ne==="stop"?i:a;if(x.setAttribute("aria-label",Ce),E&&(E.textContent=Ce),r){if(S&&k){let Fe=Ne==="stop"?k:S;x.replaceChildren(Fe)}}else x.textContent=Ne==="stop"?l:d}}},Vl=t=>{var E,M,h,C,v,T,W,P,R,N,j,ce;let e=(E=t==null?void 0:t.voiceRecognition)!=null?E:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=e.provider)==null?void 0:M.type)==="runtype";if(!(n||o))return null;let a=(C=(h=t==null?void 0:t.sendButton)==null?void 0:h.size)!=null?C:"40px",i=w("div","persona-send-button-wrapper"),d=w("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=(v=e.iconName)!=null?v:"mic",p=(T=e.iconSize)!=null?T: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=Ie(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(((ce=e.showTooltip)!=null?ce:!1)&&S){let be=w("div","persona-send-button-tooltip");be.textContent=S,i.appendChild(be)}return{button:d,wrapper:i}},jl=t=>{var y,x,S,k,E,M,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=w("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=w("input");o.type="file",o.accept=((k=e.allowedTypes)!=null?k:So).join(","),o.multiple=((E=e.maxFiles)!=null?E:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=w("div","persona-send-button-wrapper"),a=w("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(M=e.buttonTooltipText)!=null?M:"Attach file");let i=(h=e.buttonIconName)!=null?h:"paperclip",d=r,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Ie(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),o.click()}),s.appendChild(a);let f=(C=e.buttonTooltipText)!=null?C:"Attach file",m=w("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:o,previewsContainer:n}},Gl=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=w("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=w("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},Kl=()=>w("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var es=t=>{var y,x,S,k,E,M;let{config:e}=t,r=w("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=Kl(),o=w("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}=ql(e);a();let i=zl(e),d=Vl(e),l=jl(e),p=Gl(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=w("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=w("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=w("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:(k=l==null?void 0:l.wrapper)!=null?k:null,attachmentInput:(E=l==null?void 0:l.input)!=null?E:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var zx=()=>{let t=w("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=w("span","persona-pill-peek__icon"),r=Ie("message-square",16,"currentColor",1.5);r&&e.appendChild(r);let n=w("span","persona-pill-peek__text"),o=w("span","persona-pill-peek__caret"),s=Ie("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,n,o),{root:t,textNode:n}},Vx=t=>{var y,x,S,k,E,M;let{config:e}=t,r=w("div","persona-widget-footer persona-widget-footer--pill");r.setAttribute("data-persona-theme-zone","composer");let n=Kl();n.style.display="none";let o=Gl(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ql(e);s.style.maxHeight="100px",a();let i=zl(e),d=Vl(e),l=jl(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=w("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let u=w("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let f=w("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:(k=l==null?void 0:l.wrapper)!=null?k:null,attachmentInput:(E=l==null?void 0:l.input)!=null?E:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var jx=t=>{var p,u,f,m,y,x,S,k,E,M,h,C,v,T,W,P,R;let e=(u=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)!=null?u:!0,r=Br(t);if(Go(t)){let N=(m=(f=t==null?void 0:t.launcher)==null?void 0:f.composerBar)!=null?m:{},j=w("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:Qr);let ce=w("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ce.style.width="100%",j.appendChild(ce);let be=w("div","persona-widget-pill-root");return be.setAttribute("data-persona-composer-bar",""),be.dataset.state="collapsed",be.dataset.expandedSize=(k=N.expandedSize)!=null?k:"anchored",be.style.zIndex=String((M=(E=t==null?void 0:t.launcher)==null?void 0:E.zIndex)!=null?M:Qr),{wrapper:j,panel:ce,pillRoot:be}}if(r){let N=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=w("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=w("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=w("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ce=(C=(h=t==null?void 0:t.launcher)==null?void 0:h.width)!=null?C:"100%";return N.style.width=ce,j.style.width="100%",N.appendChild(j),{wrapper:N,panel:j}}let o=(v=t==null?void 0:t.launcher)!=null?v:{},s=o.position&&Xn[o.position]?Xn[o.position]:Xn["bottom-right"],a=w("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((W=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?W:Qr);let i=w("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:Tn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Mv=(t,e)=>{var h,C,v,T,W,P,R,N,j;let r=w("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}=_l(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=(v=(C=(h=t==null?void 0:t.launcher)==null?void 0:h.clearChat)==null?void 0:C.enabled)!=null?v:!0,a=null,i=null;if(s){let ce=Fl(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ce.button,i=ce.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=w("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=w("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=w("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=w("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(W=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?W:"Hello \u{1F44B}";let f=w("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=w("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=w("div","persona-composer-overlay persona-pointer-events-none");S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20";let k=Vx({config:t}),{root:E,textNode:M}=zx();return r.append(d,o,l,S),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,composerOverlay:S,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:u,introSubtitle:f,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:w("span"),headerTitle:w("span"),headerSubtitle:w("span"),header:d,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:E,peekTextNode:M}},Gx=(t,e=!0)=>{var S,k,E,M,h,C,v,T,W;if(Go(t))return Mv(t,e);let r=w("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");r.setAttribute("data-persona-theme-zone","container");let n=(S=t==null?void 0:t.layout)==null?void 0:S.header,o=((k=t==null?void 0:t.layout)==null?void 0:k.showHeader)!==!1,s=n?Za(t,n,{showClose:e}):Mo({config:t,showClose:e}),a=w("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"),a.style.setProperty("scrollbar-gutter","stable");let i=w("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Br(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=w("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(M=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=w("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=w("div","persona-flex persona-flex-col persona-gap-3"),u=(v=t==null?void 0:t.layout)==null?void 0:v.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((T=t==null?void 0:t.copy)==null?void 0:T.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=es({config:t}),y=((W=t==null?void 0:t.layout)==null?void 0:W.showFooter)!==!1;o?Sa(r,s,t):(s.header.style.display="none",Sa(r,s,t)),r.append(a);let x=w("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 kv=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}},Ev=(t,e)=>{if(!t)return null;let r=kv(t);if(r===null)return null;let n=e==null?void 0:e[t],o=n!==void 0?n:r;return o||null},Lv=(t,e)=>{let r=w("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},Pv=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},su=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(":"))},iu=320,Xx=320,Iv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Rv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Wv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Hv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Bv=(t,e,r)=>{if(t.length===0)return null;try{let n=w("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=w("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=`${iu}px`,l.style.maxHeight=`${Xx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),Pv(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}},Dv=t=>{if(t.length===0)return null;try{let e=w("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let r=0;return t.forEach(n=>{if(!su(n.audio))return;let o=w("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${iu}px`,e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Ov=t=>{if(t.length===0)return null;try{let e=w("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let r=0;return t.forEach(n=>{if(!su(n.video))return;let o=w("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${iu}px`,o.style.maxHeight=`${Xx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),r+=1}),r===0?(e.remove(),null):e}catch{return null}},Nv=t=>{if(t.length===0)return null;try{let e=w("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let r=0;return t.forEach(n=>{if(!su(n.data))return;let o=w("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}},Ta=()=>{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},lu=(t,e,r)=>{let n={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:Ta};if(e){let o=e(n);if(o!==null)return o}return Ta()},_v=(t,e)=>{let r=w("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=w("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},Kx=(t,e)=>{let r=w("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},Fv=(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},du=(t,e,r)=>{var m,y,x,S,k,E;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 M=w("div");return M.style.display="none",M.id=`actions-${t.id}`,M.setAttribute("data-actions-for",t.id),M}let a=(S=e.visibility)!=null?S:"hover",i=(k=e.align)!=null?k:"right",d=(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],u=w("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=(M,h,C)=>{let v=Fr({icon:M,label:h,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",C),v};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},ts=(t,e,r,n,o,s)=>{var Z,ne,ee,we,Q,X,fe,Le,me,te,le,ht,mt,Re,ye,ot,He;let a=r!=null?r:{},i=(Z=a.layout)!=null?Z:"bubble",d=a.avatar,l=a.timestamp,p=(ne=d==null?void 0:d.show)!=null?ne:!1,u=(ee=l==null?void 0:l.show)!=null?ee:!1,f=(we=d==null?void 0:d.position)!=null?we:"left",m=(Q=l==null?void 0:l.position)!=null?Q:"below",y=Fv(t.role,i),x=w("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=Iv(t),k=(fe=(X=t.content)==null?void 0:X.trim())!=null?fe:"",M=S.length>0&&k===dl,h=Bl((me=(Le=s==null?void 0:s.widgetConfig)==null?void 0:Le.features)==null?void 0:me.streamAnimation),C=(ht=(le=(te=s==null?void 0:s.widgetConfig)==null?void 0:te.features)==null?void 0:le.streamAnimation)==null?void 0:ht.plugins,v=t.role==="assistant"&&h.type!=="none"?ei(h.type,C):null,T=t.role==="assistant"&&((mt=v==null?void 0:v.isAnimating)==null?void 0:mt.call(v,t))===!0,W=t.role==="assistant"&&v!==null&&(!!t.streaming||T);W&&(v!=null&&v.bubbleClass)&&x.classList.add(v.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),W&&v&&(v.containerClass&&P.classList.add(v.containerClass),P.style.setProperty("--persona-stream-step",`${h.speed}ms`),P.style.setProperty("--persona-stream-duration",`${h.duration}ms`));let R=W?Dl((Re=t.content)!=null?Re:"",h.buffer,v,t,!!t.streaming):(ye=t.content)!=null?ye:"",N=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),j=N;W&&(v==null?void 0:v.wrap)==="char"?j=ti(N,"char",t.id,{skipTags:v.skipTags}):W&&(v==null?void 0:v.wrap)==="word"&&(j=ti(N,"word",t.id,{skipTags:v.skipTags}));let ce=null;if(M?(ce=document.createElement("div"),ce.innerHTML=j,ce.style.display="none",P.appendChild(ce)):P.innerHTML=j,W&&(v!=null&&v.useCaret)&&!M&&k){let G=Ol(),he=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),K=he[he.length-1];if(K!=null&&K.parentNode)K.parentNode.insertBefore(G,K.nextSibling);else{let wt=P.lastElementChild;wt?wt.appendChild(G):P.appendChild(G)}}if(u&&m==="inline"&&t.createdAt){let G=Kx(t,l);G.classList.add("persona-ml-2","persona-inline"),P.appendChild(G)}if(S.length>0){let G=Bv(S,!M&&!!k,()=>{M&&ce&&(ce.style.display="")});G?x.appendChild(G):M&&ce&&(ce.style.display="")}let be=Rv(t);if(be.length>0){let G=Dv(be);G&&x.appendChild(G)}let Ze=Wv(t);if(Ze.length>0){let G=Ov(Ze);G&&x.appendChild(G)}let Se=Hv(t);if(Se.length>0){let G=Nv(Se);G&&x.appendChild(G)}if(x.appendChild(P),u&&m==="below"&&t.createdAt){let G=Kx(t,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let Ne=t.role==="assistant"?Ev(t.stopReason,(He=(ot=s==null?void 0:s.widgetConfig)==null?void 0:ot.copy)==null?void 0:He.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let G=!!(R&&R.trim()),he=h.placeholder==="skeleton",K=he&&h.buffer==="line"&&G;if(G)K&&x.appendChild(ri());else if(he)x.appendChild(ri());else{let wt=lu("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);wt&&x.appendChild(wt)}}if(Ne&&t.stopReason&&!t.streaming&&(k||(P.style.display="none"),x.appendChild(Lv(t.stopReason,Ne))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let G=du(t,n,o);x.appendChild(G)}if(!p||t.role==="system")return x;let Fe=w("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),We=_v(d,t.role);return f==="right"||f==="left"&&t.role==="user"?Fe.append(x,We):Fe.append(We,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Fe},Jx=(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}):ts(t,e,r,n,o,s)};var rs=new Set,$v=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Uv=(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
+ `):""},Qx=(t,e)=>{let r=rs.has(t),n=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",r?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ie(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none",s&&(s.style.display=r?"none":s.textContent||s.childNodes.length?"":"none")},cu=(t,e)=>{var Ze,Se,Ne,Ce,Fe,We,Z,ne,ee,we,Q;let r=t.reasoning,n=w("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=(Se=(Ze=e==null?void 0:e.features)==null?void 0:Ze.reasoningDisplay)!=null?Se:{},s=o.expandable!==!1,a=s&&rs.has(t.id),i=r.status!=="complete",d=Uv(t,(Ne=o.previewMaxLines)!=null?Ne:3),l=w("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=w("div","persona-flex persona-flex-col persona-text-left"),u=w("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(Ce=e==null?void 0:e.reasoning)!=null?Ce:{},y=String((Fe=r.startedAt)!=null?Fe:Date.now()),x=()=>{let X=w("span","");return X.setAttribute("data-tool-elapsed",y),X.textContent=tl(r),X},S=(We=m.renderCollapsedSummary)==null?void 0:We.call(m,{message:t,reasoning:r,defaultSummary:f,previewText:d,isActive:i,config:e!=null?e:{},elapsed:tl(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 k=w("span","persona-text-xs persona-text-persona-primary");k.textContent=ix(r),p.appendChild(k);let E=(Z=o.loadingAnimation)!=null?Z:"none",M=m.activeTextTemplate,h=m.completeTextTemplate,C=i?M:h,v=S instanceof HTMLElement,T=(X,fe,Le)=>{let me=Le;for(let te of fe){let le=w("span","persona-tool-char");le.style.setProperty("--char-index",String(me)),le.textContent=te===" "?"\xA0":te,X.appendChild(le),me++}return me},W=(X,fe)=>{u.textContent="";let Le=rl(X,""),me=0;for(let te of Le){let le=te.styles.length>0?(()=>{let ht=w("span",te.styles.map(mt=>`persona-tool-text-${mt}`).join(" "));return u.appendChild(ht),ht})():u;if(te.isDuration&&i)le.appendChild(x());else{let ht=te.isDuration?tl(r):te.text;fe?me=T(le,ht,me):le.appendChild(document.createTextNode(ht))}}};if(!v&&C)if(k.style.display="none",u.style.display="",i&&E!=="none"){let X=(ne=m.loadingAnimationDuration)!=null?ne:2e3;u.setAttribute("data-preserve-animation","true"),E==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${X}ms`),W(C,!1)):(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${X}ms`),E==="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(!v&&i&&E!=="none"){u.style.display="";let X=(ee=m.loadingAnimationDuration)!=null?ee:2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${X}ms`);else{u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${X}ms`),E==="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 fe=u.textContent||f;u.textContent="",T(u,fe,0)}r.status==="complete"&&(u.style.display="none")}else v||(r.status==="complete"?u.style.display="none":u.style.display="");let P=null;if(s){P=w("div","persona-flex persona-items-center");let fe=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);fe?P.appendChild(fe):P.textContent=a?"Hide":"Show";let Le=w("div","persona-flex persona-items-center persona-ml-auto");Le.append(P),l.append(p,Le)}else l.append(p);let R=w("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 X=(Q=(we=e==null?void 0:e.reasoning)==null?void 0:we.renderCollapsedPreview)==null?void 0:Q.call(we,{message:t,reasoning:r,defaultPreview:d,isActive:i,config:e!=null?e:{}});$v(R,X)||(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=w("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(""),ce=w("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ce.textContent=j||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(ce),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),P){P.innerHTML="";let fe=Ie(a?"chevron-up":"chevron-down",16,"currentColor",2);fe?P.appendChild(fe):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 ns=new Set,qv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),zv=(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=Ga(r.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
76
+ `):""},Vv=(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=zv(t,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=r?lx(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=Kd(r,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Kd(r,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Yx=(t,e,r)=>{var p;let n=ns.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=Ie(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")},pu=(t,e)=>{var j,ce,be,Ze,Se,Ne,Ce,Fe,We;let r=t.toolCall,n=(j=e==null?void 0:e.toolCall)!=null?j:{},o=w("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=(be=(ce=e==null?void 0:e.features)==null?void 0:ce.toolCallDisplay)!=null?be:{},a=s.expandable!==!1,i=a&&ns.has(t.id),{summary:d,previewText:l,isActive:p}=Vv(t,e),u=w("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=w("div","persona-flex persona-flex-col persona-text-left"),m=w("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let y=String((Ze=r.startedAt)!=null?Ze:Date.now()),x=()=>{let Z=w("span","");return Z.setAttribute("data-tool-elapsed",y),Z.textContent=Vs(r),Z},S=(Ne=n.renderCollapsedSummary)==null?void 0:Ne.call(n,{message:t,toolCall:r,defaultSummary:d,previewText:l,collapsedMode:(Se=s.collapsedMode)!=null?Se:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Vs(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 k=(Ce=s.loadingAnimation)!=null?Ce:"none",E=n.activeTextTemplate,M=n.completeTextTemplate,h=p?E:M,C=S instanceof HTMLElement,v=(Z,ne,ee)=>{let we=ee;for(let Q of ne){let X=w("span","persona-tool-char");X.style.setProperty("--char-index",String(we)),X.textContent=Q===" "?"\xA0":Q,Z.appendChild(X),we++}return we},T=(Z,ne)=>{var X;m.textContent="";let ee=((X=r.name)==null?void 0:X.trim())||"tool",we=rl(Z,ee),Q=0;for(let fe of we){let Le=fe.styles.length>0?(()=>{let me=w("span",fe.styles.map(te=>`persona-tool-text-${te}`).join(" "));return m.appendChild(me),me})():m;if(fe.isDuration&&p)Le.appendChild(x());else{let me=fe.isDuration?Vs(r):fe.text;ne?Q=v(Le,me,Q):Le.appendChild(document.createTextNode(me))}}};if(!C)if(p&&k!=="none"){let Z=(Fe=n.loadingAnimationDuration)!=null?Fe:2e3;if(m.setAttribute("data-preserve-animation","true"),k==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),h&&T(h,!1);else if(m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),k==="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 ne=m.textContent||d;m.textContent="",v(m,ne,0)}}else h&&T(h,!1);let W=null;if(a){W=w("div","persona-flex persona-items-center");let Z=n.toggleTextColor||n.headerTextColor||"currentColor",ne=Ie(i?"chevron-up":"chevron-down",16,Z,2);ne?W.appendChild(ne):W.textContent=i?"Hide":"Show";let ee=w("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ee.append(W),u.append(f,ee)}else u.append(f);let P=w("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 Z=(We=n.renderCollapsedPreview)==null?void 0:We.call(n,{message:t,toolCall:r,defaultPreview:l,isActive:p,config:e!=null?e:{}});qv(P,Z)||(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=w("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 Z=w("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Z.style.color=n.contentTextColor:n.headerTextColor&&(Z.style.color=n.headerTextColor),Z.textContent=r.name,R.appendChild(Z)}if(r.args!==void 0){let Z=w("div","persona-space-y-1"),ne=w("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ne.style.color=n.labelTextColor),ne.textContent="Arguments";let ee=w("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");ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(ee.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(ee.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(ee.style.color=n.codeBlockTextColor),ee.textContent=Ga(r.args),Z.append(ne,ee),R.appendChild(Z)}if(r.chunks&&r.chunks.length){let Z=w("div","persona-space-y-1"),ne=w("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ne.style.color=n.labelTextColor),ne.textContent="Activity";let ee=w("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");ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(ee.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(ee.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(ee.style.color=n.codeBlockTextColor),ee.textContent=r.chunks.join(""),Z.append(ne,ee),R.appendChild(Z)}if(r.status==="complete"&&r.result!==void 0){let Z=w("div","persona-space-y-1"),ne=w("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ne.style.color=n.labelTextColor),ne.textContent="Result";let ee=w("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");ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(ee.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(ee.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(ee.style.color=n.codeBlockTextColor),ee.textContent=Ga(r.result),Z.append(ne,ee),R.appendChild(Z)}if(r.status==="complete"&&typeof r.duration=="number"){let Z=w("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Z.style.color=n.contentTextColor),Z.textContent=`Duration: ${r.duration}ms`,R.appendChild(Z)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let Z=n.toggleTextColor||n.headerTextColor||"currentColor",ne=Ie(i?"chevron-up":"chevron-down",16,Z,2);ne?W.appendChild(ne):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 Xo=bd(Yi(),1);var fu="ask_user_question",uu=8,os="data-persona-ask-sheet-for",jv="Other",Gv="Other\u2026",ey="Type your own answer here",ty="Send",Kv="Next",Xv="Back",Jv="Submit all",Qv="Skip",Yv=3,mu="data-ask-current-index",gu="data-ask-question-count",ry="data-ask-answers",hu="data-ask-grouped",ny="data-ask-layout",Zv=t=>t.layout==="pills"?"pills":"rows",eC=t=>t.getAttribute(ny)==="pills"?"pills":"rows",Zx=!1,oy=t=>t.replace(/["\\]/g,"\\$&"),ko=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===fu,Xl=t=>{var e,r;return(r=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?r:{}},Eo=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,Xo.parse)(o,Xo.STR|Xo.OBJ|Xo.ARR);if(s&&typeof s=="object")return{payload:s,complete:r}}catch{}return{payload:null,complete:r}},si=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>uu&&!Zx&&(Zx=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${uu}.`)),e.slice(0,uu)},tC=t=>{var e;return(e=si(t)[0])!=null?e:null},rC=(t,e)=>{var r;return(r=si(t)[e])!=null?r:null},ay=(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))},sy=(t,e,r)=>{if(t!=="rows")return null;let n=w("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),e){let o=w("span","persona-ask-row-check");n.appendChild(o)}else{let o=w("span","persona-ask-row-badge");o.textContent=String(r+1),n.appendChild(o)}return n},nC=(t,e,r,n)=>{let s=w("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=w("span","persona-ask-row-content"),i=w("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let l=w("span","persona-ask-row-description");l.textContent=t.description,a.appendChild(l)}s.appendChild(a);let d=sy(r,n,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},oC=t=>{let r=w("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},aC=(t,e,r,n)=>{var p,u,f;let s=w("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<Yv;m++)s.appendChild(oC(n));return s}if(d.forEach((m,y)=>{s.appendChild(nC(m,y,n,a))}),(t==null?void 0:t.allowFreeText)!==!1){let m=n==="rows"?jv:Gv;if(n==="rows"){let y=w("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=w("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:ey,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 k=sy(n,a,d.length);k&&y.appendChild(k),s.appendChild(y)}else{let y=w("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},iy=(t,e)=>{var s,a;let n=w("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:ey,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),e!=="rows"){let i=w("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:ty,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},sC=t=>{var n;let e=w("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let r=w("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(n=t.submitLabel)!=null?n:ty,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,e.appendChild(r),e},iC=(t,e,r)=>{var l,p,u,f;let n=w("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=w("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=w("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=w("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=r.skipLabel)!=null?p:Qv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=w("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:Jv:(f=r.nextLabel)!=null?f:Kv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),n.appendChild(s),n},Ma=t=>{let e=t.getAttribute(ry);if(!e)return{};try{let r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}},ly=(t,e)=>{t.setAttribute(ry,JSON.stringify(e))},_n=t=>{var r;let e=Number((r=t.getAttribute(mu))!=null?r:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},lC=(t,e)=>{t.setAttribute(mu,String(Math.max(0,Math.floor(e))))},as=t=>{var r;let e=Number((r=t.getAttribute(gu))!=null?r:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Jo=t=>t.getAttribute(hu)==="true",dC=(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},cC=(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)))},Jl=(t,e)=>{let{payload:r}=Eo(e),n=si(r),o=Ma(t),s={},a=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},dy=t=>{let e=Ma(t),r=_n(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=""},cy=t=>{if(!Jo(t))return;let e=Ma(t),r=_n(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}},xu=(t,e,r)=>{let n=Xl(r),o=eC(t),{payload:s,complete:a}=Eo(e),i=Jo(t),d=_n(t),l=as(t),p=i?rC(s,d):tC(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 E=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=E,y.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let x=t.querySelector('[data-ask-pill-list="true"]');if(x){let E=aC(p,n,a,o);x.replaceWith(E)}if(o!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(iy(n,o))}let S=t.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?t.appendChild(sC(n)):(!u||i)&&S&&S.remove(),t.setAttribute("data-multi-select",u?"true":"false");let k=t.querySelector('[data-ask-nav-row="true"]');if(i){let E=iC(d,l,n);k?k.replaceWith(E):t.appendChild(E)}else k&&k.remove();dy(t),cy(t)},pC=(t,e,r)=>{let n=Xl(e),o=Zv(n),s=t.toolCall.id,a=si(r),i=Math.max(1,a.length),d=i>1,l=dC(t,a),p=d?cC(t,i):0,u=w("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(os,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(gu,String(i)),u.setAttribute(mu,String(p)),u.setAttribute(hu,d?"true":"false"),u.setAttribute(ny,o),ly(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`),ay(u,n);let f=w("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=w("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let y=w("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),u.appendChild(f);let S=w("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(iy(n,o)),xu(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},uC=(t,e,r)=>{let{payload:n}=Eo(e),o=Math.max(1,si(n).length);o>as(t)&&(t.setAttribute(gu,String(o)),o>1&&!Jo(t)&&t.setAttribute(hu,"true")),xu(t,e,r)},py=(t,e)=>{let r=w("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=Xl(e);ay(r,n);let o=w("span","persona-ask-stub-label"),{complete:s}=Eo(t);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(o),r},ss=(t,e,r)=>{if(!r||!ko(t)||Xl(e).enabled===!1)return;let o=t.toolCall.id;r.querySelectorAll(`[${os}]`).forEach(l=>{l.getAttribute(os)!==o&&l.remove()});let a=r.querySelector(`[${os}="${oy(o)}"]`);if(a){uC(a,t,e);return}let{payload:i}=Eo(t),d=pC(t,e,i);r.appendChild(d)},Qo=(t,e)=>{if(!t)return;let r=e?`[${os}="${oy(e)}"]`:`[${os}]`;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)})},yu=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),Yo=(t,e)=>{let r=Ma(t),n=_n(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete r[n]:r[n]=e,ly(t,r),dy(t),cy(t)},Ql=(t,e,r,n)=>{let o=as(t),s=Math.max(0,Math.min(o-1,n));lC(t,s),xu(t,e,r)};var Yl=new Map,fC=t=>{let r=(t.startsWith(Co)?t.slice(Co.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)},uy=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,fy=(t,e)=>{var n,o,s;let r=(o=(n=uy(e))==null?void 0:n.detailsDisplay)!=null?o:"collapsed";return(s=Yl.get(t))!=null?s:r==="expanded"},my=(t,e,r)=>{var a,i;let n=uy(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=Ie(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},gy=(t,e,r)=>{let n=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!n||!o)return;let s=fy(t,r);my(n,s,r),o.style.display=s?"":"none"};var Zl=(t,e)=>{var T,W,P,R,N,j,ce,be,Ze,Se,Ne,Ce,Fe,We,Z;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=w("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=(T=n==null?void 0:n.backgroundColor)!=null?T:"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=w("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=w("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=Ie(d,20,l,2);p&&i.appendChild(p);let u=w("div","persona-flex-1 persona-min-w-0"),f=w("div","persona-flex persona-items-center persona-gap-2"),m=w("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 ne=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ne.setAttribute("data-approval-status",r.status),r.status==="approved"?(ne.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ne.style.color="var(--persona-palette-colors-success-700, #15803d)",ne.textContent="Approved"):r.status==="denied"?(ne.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ne.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ne.textContent="Denied"):r.status==="timeout"&&(ne.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ne.style.color="var(--persona-palette-colors-warning-700, #b45309)",ne.textContent="Timeout"),f.appendChild(ne)}u.appendChild(f);let x=r.toolType==="webmcp"||r.toolName.startsWith(Co)?jd(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}:{},...r.reason?{reason:r.reason}:{}}),k=!r.toolName,E=S||(k?r.description:`The assistant wants to use \u201C${x!=null?x:fC(r.toolName)}\u201D.`),M=w("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),n!=null&&n.descriptionColor&&(M.style.color=n.descriptionColor),M.textContent=E,u.appendChild(M),r.reason){let ne=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ne.setAttribute("data-approval-reason","true"),n!=null&&n.reasonColor?ne.style.color=n.reasonColor:n!=null&&n.descriptionColor&&(ne.style.color=n.descriptionColor);let ee=w("span","persona-font-medium");ee.textContent=`${(j=n==null?void 0:n.reasonLabel)!=null?j:"Agent's stated reason:"} `,ne.appendChild(ee),ne.appendChild(document.createTextNode(r.reason)),u.appendChild(ne)}let h=(ce=n==null?void 0:n.detailsDisplay)!=null?ce:"collapsed",C=!!r.description&&!k,v=C||!!r.parameters;if(h!=="hidden"&&v){let ne=fy(t.id,e),ee=w("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");ee.type="button",ee.setAttribute("data-expand-header","true"),ee.setAttribute("data-bubble-type","approval"),n!=null&&n.descriptionColor&&(ee.style.color=n.descriptionColor);let we=w("span");we.setAttribute("data-approval-details-label","true");let Q=w("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),ee.append(we,Q),my(ee,ne,e),u.appendChild(ee);let X=w("div");if(X.setAttribute("data-approval-details","true"),X.style.display=ne?"":"none",C){let fe=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");n!=null&&n.descriptionColor&&(fe.style.color=n.descriptionColor),fe.textContent=r.description,X.appendChild(fe)}if(r.parameters){let fe=w("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&&(fe.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(fe.style.color=n.parameterTextColor),fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",fe.textContent=Ga(r.parameters),X.appendChild(fe)}u.appendChild(X)}if(o){let ne=w("div","persona-flex persona-gap-2 persona-mt-2");ne.setAttribute("data-approval-buttons","true");let ee=w("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");ee.type="button",ee.style.backgroundColor=(be=n==null?void 0:n.approveButtonColor)!=null?be:"var(--persona-approval-approve-bg, #22c55e)",ee.style.color=(Ze=n==null?void 0:n.approveButtonTextColor)!=null?Ze:"#ffffff",ee.setAttribute("data-approval-action","approve");let we=Ie("shield-check",14,(Se=n==null?void 0:n.approveButtonTextColor)!=null?Se:"#ffffff",2);we&&(we.style.marginRight="4px",ee.appendChild(we));let Q=document.createTextNode((Ne=n==null?void 0:n.approveLabel)!=null?Ne:"Approve");ee.appendChild(Q);let X=w("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");X.type="button",X.style.backgroundColor=(Ce=n==null?void 0:n.denyButtonColor)!=null?Ce:"transparent",X.style.color=(Fe=n==null?void 0:n.denyButtonTextColor)!=null?Fe:"var(--persona-feedback-error, #dc2626)",X.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,X.setAttribute("data-approval-action","deny");let fe=Ie("shield-x",14,(We=n==null?void 0:n.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);fe&&(fe.style.marginRight="4px",X.appendChild(fe));let Le=document.createTextNode((Z=n==null?void 0:n.denyLabel)!=null?Z:"Deny");X.appendChild(Le),ne.append(ee,X),u.appendChild(ne)}return a.append(i,u),s.appendChild(a),s};var hy=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=w("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 ii=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 li=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 mC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),gC=new Set(["step_start","execution_start"]),hC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),xC=new Set(["step_complete","agent_turn_complete"]),yC=new Set(["flow_complete","agent_complete"]),xy=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),by=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Mn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ka=(t,e)=>{let r=t[e];return by(r)?r:void 0};function bu(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ed(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function bC(t,e){return typeof e.type=="string"?e.type:t}function wC(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 vC(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 yy(t){var n,o,s,a,i;let e=ka(t,"result"),r=[ka(t,"tokens"),ka(t,"totalTokens"),e?ka(e,"tokens"):void 0,ka(t,"usage"),e?ka(e,"usage"):void 0];for(let d of r){if(!d)continue;let l=(o=(n=Mn(d.output))!=null?n:Mn(d.outputTokens))!=null?o:Mn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Mn(t.outputTokens))!=null?s:Mn(t.completionTokens))!=null?i:e?(a=Mn(e.outputTokens))!=null?a:Mn(e.completionTokens):void 0}function CC(t){var r,n,o,s,a;let e=ka(t,"result");return(a=(o=(n=(r=Mn(t.executionTime))!=null?r:Mn(t.executionTimeMs))!=null?n:Mn(t.execution_time))!=null?o:Mn(t.duration))!=null?a:e?(s=Mn(e.executionTime))!=null?s:Mn(e.executionTimeMs):void 0}function AC(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var di=class{constructor(e=AC){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:ed(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(!by(r)){xy.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=bC(e,r),o=this.now();if(mC.has(n)){this.startRun(o);return}if(gC.has(n)){this.run||this.startRun(o);return}if(hC.has(n)){if(!vC(n,r))return;let a=wC(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+bu(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ed(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(xC.has(n)){if(!this.run)return;let a=this.run,i=yy(r);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+bu(a.visibleCharCount),p=this.resolveDuration(a,r,o);this.metric={status:"running",tokensPerSecond:ed(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(yC.has(n)){if(!this.run)return;let a=this.run,i=yy(r),d=i!=null?i:a.exactOutputTokens+bu(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,r,o);this.metric={status:"complete",tokensPerSecond:ed(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(xy.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=CC(r);return s!=null?s:n-e.startedAt}};function is(t,e){e&&e.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var SC={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)"}},TC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},MC=["flowName","stepName","reasoningText","text","name","tool","toolName"],kC=100;function EC(t,e){let r={...SC,...e};if(r[t])return r[t];for(let n of Object.keys(r))if(n.endsWith("_")&&t.startsWith(n))return r[n];return TC}function LC(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function PC(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 IC(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 RC(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 WC(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 HC(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function BC(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 DC(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=w("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=w("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 wu(t,e,r,n,o,s,a,i){var f;let d=o.has(t.id),l=w("div","persona-border-b persona-border-persona-divider persona-text-xs");is(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,ce;let m=w("div",""),y=w("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=w("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=Ie(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&x.appendChild(S);let k=w("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(j=n.timestampFormat)!=null?j:"relative";k.textContent=E==="relative"?LC(t.timestamp,r):PC(t.timestamp);let M=null;n.showSequenceNumbers!==!1&&(M=w("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let h=EC(t.type,n.badgeColors),C=w("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 v=(ce=n.descriptionFields)!=null?ce:MC,T=IC(t.payload,v),W=null;T&&(W=w("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=T);let P=w("div","persona-flex-1 persona-min-w-0"),R=w("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=Ie("clipboard","12px","currentColor",1.5);return N&&R.appendChild(N),R.addEventListener("click",async be=>{be.stopPropagation(),await RC(WC(t)),R.innerHTML="";let Ze=Ie("check","12px","currentColor",1.5);Ze&&R.appendChild(Ze),setTimeout(()=>{R.innerHTML="";let Se=Ie("clipboard","12px","currentColor",1.5);Se&&R.appendChild(Se)},1500)}),y.appendChild(x),y.appendChild(k),M&&y.appendChild(M),y.appendChild(C),W&&y.appendChild(W),y.appendChild(P),y.appendChild(R),m.appendChild(y),d&&m.appendChild(DC(t,a,i)),m}}function wy(t){var y,x,S,k,E;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=(E=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?E:{},f=s.find(M=>M.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let M=f.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return m();function m(){let M=u.classNames,h=w("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");is(h,M==null?void 0:M.panel);let C=[],v="",T="",W=null,P=[],R={},N=0,j=Rl(),ce=0,be=0,Ze=!1,Se=null,Ne=!1,Ce=0,Fe=new Set,We=new Map,Z="",ne="",ee=null,we,Q,X,fe,Le,me=null,te=null,le=null;function ht(){let Te=w("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ue=w("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");is(ue,M==null?void 0:M.headerBar);let pt=w("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(pt.textContent="Events",we=w("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"),we.textContent="0",a){te=w("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let pr=w("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");pr.textContent="Throughput",me=w("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"),me.textContent="-- tok/s",le=w("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 xr=te,Er=le,fn=()=>{if(!Er.textContent)return;let zr=xr.getBoundingClientRect(),wr=Te.getBoundingClientRect();Er.style.left=`${zr.left-wr.left}px`,Er.style.top=`${zr.bottom-wr.top+4}px`,Er.style.display="block"},Wt=()=>{Er.style.display="none"};te.addEventListener("mouseenter",fn),te.addEventListener("mouseleave",Wt),te.appendChild(pr),te.appendChild(me)}let hr=w("div","persona-flex-1");Q=w("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 xt=w("option","");xt.value="",xt.textContent="All events",Q.appendChild(xt),X=w("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"),X.type="button",X.title="Copy All";let Dr=Ie("clipboard-copy","12px","currentColor",1.5);Dr&&X.appendChild(Dr);let yt=w("span","persona-text-xs");yt.textContent="Copy All",X.appendChild(yt),ue.appendChild(pt),ue.appendChild(we),te&&ue.appendChild(te),ue.appendChild(hr),ue.appendChild(Q),ue.appendChild(X);let Dt=w("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");is(Dt,M==null?void 0:M.searchBar);let it=Ie("search","14px","var(--persona-muted, #9ca3af)",1.5),Xt=w("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");it&&Xt.appendChild(it),fe=w("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"),is(fe,M==null?void 0:M.searchInput),fe.type="text",fe.placeholder="Search event payloads...",Le=w("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"),Le.type="button",Le.style.display="none";let Cr=Ie("x","12px","currentColor",2);return Cr&&Le.appendChild(Cr),Dt.appendChild(Xt),Dt.appendChild(fe),Dt.appendChild(Le),Te.appendChild(ue),Te.appendChild(Dt),le&&Te.appendChild(le),Te}let mt,Re=s.find(Te=>Te.renderEventStreamToolbar);if(Re!=null&&Re.renderEventStreamToolbar&&o){let Te=Re.renderEventStreamToolbar({config:o,defaultRenderer:()=>ht(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ue=>{v=ue,ie(),B()},onSearchChange:ue=>{T=ue,ie(),B()}});mt=Te!=null?Te:ht()}else mt=ht();let ye=w("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");ye.style.display="none";function ot(){if(!a||!me||!te)return;let Te=a();me.textContent=HC(Te);let ue=BC(Te);le&&(le.textContent=ue,ue||(le.style.display="none")),ue?te.setAttribute("aria-label",ue):te.removeAttribute("aria-label")}let He=w("div","persona-flex-1 persona-min-h-0 persona-relative"),G=w("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let he=w("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");is(he,M==null?void 0:M.scrollIndicator),he.style.display="none",he.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let K=Ie(l,"14px","currentColor",2);K&&he.appendChild(K);let wt=w("span","");wt.textContent=p,he.appendChild(wt);let U=w("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");U.style.display="none",He.appendChild(G),He.appendChild(U),He.appendChild(he),h.setAttribute("tabindex","0"),h.appendChild(mt),h.appendChild(ye),h.appendChild(He);function J(){let Te=e.getAll(),ue={};for(let yt of Te)ue[yt.type]=(ue[yt.type]||0)+1;let pt=Object.keys(ue).sort(),hr=pt.length!==P.length||!pt.every((yt,Dt)=>yt===P[Dt]),xt=!hr&&pt.some(yt=>ue[yt]!==R[yt]),vr=Te.length!==Object.values(R).reduce((yt,Dt)=>yt+Dt,0);if(!hr&&!xt&&!vr||(P=pt,R=ue,!Q))return;let Dr=Q.value;if(Q.options[0].textContent="All events",hr){for(;Q.options.length>1;)Q.remove(1);for(let yt of pt){let Dt=w("option","");Dt.value=yt,Dt.textContent=`${yt} (${ue[yt]||0})`,Q.appendChild(Dt)}Dr&&pt.includes(Dr)?Q.value=Dr:Dr&&(Q.value="",v="")}else for(let yt=1;yt<Q.options.length;yt++){let Dt=Q.options[yt];Dt.textContent=`${Dt.value} (${ue[Dt.value]||0})`}}function qe(){let Te=e.getAll();if(v&&(Te=Te.filter(ue=>ue.type===v)),T){let ue=T.toLowerCase();Te=Te.filter(pt=>pt.type.toLowerCase().includes(ue)||pt.payload.toLowerCase().includes(ue))}return Te}function se(){return v!==""||T!==""}function ie(){N=0,ce=0,j.resume(),he.style.display="none"}function Be(Te){Fe.has(Te)?Fe.delete(Te):Fe.add(Te),ee=Te;let ue=G.scrollTop,pt=j.isFollowing();Ne=!0,j.pause(),B(),G.scrollTop=ue,pt&&j.resume(),Ne=!1}function Xe(){return Ca(G,50)}function B(){be=Date.now(),Ze=!1,ot(),J();let Te=e.getEvictedCount();Te>0?(ye.textContent=`${Te.toLocaleString()} older events truncated`,ye.style.display=""):ye.style.display="none",C=qe();let ue=C.length,pt=e.getSize()>0;we&&(we.textContent=String(e.getSize())),ue===0&&pt&&se()?(U.textContent=T?`No events matching '${T}'`:"No events matching filter",U.style.display="",G.style.display="none"):(U.style.display="none",G.style.display=""),X&&(X.title=se()?`Copy Filtered (${ue})`:"Copy All"),d&&!j.isFollowing()&&ue>N&&(ce+=ue-N,wt.textContent=p?`${p}${ce>0?` (${ce})`:""}`:"",he.style.display=""),N=ue;let hr=e.getAll(),xt=hr.length>0?hr[0].timestamp:0,vr=new Set(C.map(Dt=>Dt.id));for(let Dt of Fe)vr.has(Dt)||Fe.delete(Dt);let Dr=v!==Z||T!==ne,yt=We.size===0&&C.length>0;if(Dr||yt||C.length===0){G.innerHTML="",We.clear();let Dt=document.createDocumentFragment();for(let it=0;it<C.length;it++){let Xt=wu(C[it],it,xt,u,Fe,Be,s,o);We.set(C[it].id,Xt),Dt.appendChild(Xt)}G.appendChild(Dt),Z=v,ne=T,ee=null}else{if(ee!==null){let it=We.get(ee);if(it&&it.parentNode===G){let Xt=C.findIndex(Cr=>Cr.id===ee);if(Xt>=0){let Cr=wu(C[Xt],Xt,xt,u,Fe,Be,s,o);G.insertBefore(Cr,it),it.remove(),We.set(ee,Cr)}}ee=null}let Dt=new Set(C.map(it=>it.id));for(let[it,Xt]of We)Dt.has(it)||(Xt.remove(),We.delete(it));for(let it=0;it<C.length;it++){let Xt=C[it];if(!We.has(Xt.id)){let Cr=wu(Xt,it,xt,u,Fe,Be,s,o);We.set(Xt.id,Cr),G.appendChild(Cr)}}}j.isFollowing()&&(G.scrollTop=G.scrollHeight)}function xe(){if(Date.now()-be>=kC){Se!==null&&(cancelAnimationFrame(Se),Se=null),B();return}Ze||(Ze=!0,Se=requestAnimationFrame(()=>{Se=null,B()}))}let De=(Te,ue)=>{if(!X)return;X.innerHTML="";let pt=Ie(Te,"12px","currentColor",1.5);pt&&X.appendChild(pt);let hr=w("span","persona-text-xs");hr.textContent="Copy All",X.appendChild(hr),setTimeout(()=>{X.innerHTML="";let xt=Ie("clipboard-copy","12px","currentColor",1.5);xt&&X.appendChild(xt);let vr=w("span","persona-text-xs");vr.textContent="Copy All",X.appendChild(vr),X.disabled=!1},ue)},rt=async()=>{if(X){X.disabled=!0;try{let Te;se()?Te=C:r?(Te=await r(),Te.length===0&&(Te=e.getAll())):Te=e.getAll();let ue=Te.map(pt=>{try{return JSON.parse(pt.payload)}catch{return pt.payload}});await navigator.clipboard.writeText(JSON.stringify(ue,null,2)),De("check",1500)}catch{De("x",1500)}}},ze=()=>{Q&&(v=Q.value,ie(),B())},je=()=>{!fe||!Le||(Le.style.display=fe.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{T=fe.value,ie(),B()},150))},at=()=>{!fe||!Le||(fe.value="",T="",Le.style.display="none",W&&clearTimeout(W),ie(),B())},Rt=()=>{if(Ne)return;let Te=G.scrollTop,{action:ue,nextLastScrollTop:pt}=Wl({following:j.isFollowing(),currentScrollTop:Te,lastScrollTop:Ce,nearBottom:Xe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ce=pt,ue==="resume"?(j.resume(),ce=0,he.style.display="none"):ue==="pause"&&(j.pause(),d&&(wt.textContent=p,he.style.display=""))},tr=Te=>{let ue=Hl({following:j.isFollowing(),deltaY:Te.deltaY,nearBottom:Xe(),resumeWhenNearBottom:!0});ue==="pause"?(j.pause(),d&&(wt.textContent=p,he.style.display="")):ue==="resume"&&(j.resume(),ce=0,he.style.display="none")},cr=()=>{d&&(G.scrollTop=G.scrollHeight,j.resume(),ce=0,he.style.display="none")},Y=Te=>{let ue=Te.target;if(!ue||ue.closest("button"))return;let pt=ue.closest("[data-event-id]");if(!pt)return;let hr=pt.getAttribute("data-event-id");hr&&Be(hr)},vt=Te=>{if((Te.metaKey||Te.ctrlKey)&&Te.key==="f"){Te.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}Te.key==="Escape"&&(fe&&document.activeElement===fe?(at(),fe.blur(),h.focus()):n&&n())};X&&X.addEventListener("click",rt),Q&&Q.addEventListener("change",ze),fe&&fe.addEventListener("input",je),Le&&Le.addEventListener("click",at),G.addEventListener("scroll",Rt),G.addEventListener("wheel",tr,{passive:!0}),G.addEventListener("click",Y),he.addEventListener("click",cr),h.addEventListener("keydown",vt);function ut(){W&&clearTimeout(W),Se!==null&&(cancelAnimationFrame(Se),Se=null),Ze=!1,We.clear(),X&&X.removeEventListener("click",rt),Q&&Q.removeEventListener("change",ze),fe&&fe.removeEventListener("input",je),Le&&Le.removeEventListener("click",at),G.removeEventListener("scroll",Rt),G.removeEventListener("wheel",tr),G.removeEventListener("click",Y),he.removeEventListener("click",cr),h.removeEventListener("keydown",vt)}return{element:h,update:xe,destroy:ut}}}function vy(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 Cy=(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:()=>vy(t,e)});if(p)return p}return vy(t,e)};var vu=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)})}},Lo=new vu;Lo.register("PersonaArtifactCard",Cy);function OC(t){var o;let e=w("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=w("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=t.component?`Component: ${t.component}`:"Component";let n=w("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 Ay(t,e){var Q,X,fe,Le;let r=(X=(Q=t.features)==null?void 0:Q.artifacts)==null?void 0:X.layout,o=((fe=r==null?void 0:r.toolbarPreset)!=null?fe:"default")==="document",s=(Le=r==null?void 0:r.panePadding)==null?void 0:Le.trim(),a=t.markdown?ma(t.markdown):null,i=qa(t.sanitize),d=me=>{let te=a?a(me):ga(me);return i?i(te):te},l=typeof document!="undefined"?w("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 me;p(),(me=e.onDismiss)==null||me.call(e)});let u=w("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=w("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=w("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let y=w("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 me;p(),(me=e.onDismiss)==null||me.call(e)});let x="rendered",S=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),k=o?Fr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Fr({icon:"eye",label:"Rendered view"}),E=o?Fr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Fr({icon:"code-2",label:"Source"}),M=w("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,v=r==null?void 0:r.documentToolbarCopyMenuItems,T=!!(C&&v&&v.length>0),W=null,P,R=null,N=null;if(o&&(h||C)&&!T){if(P=h?ai({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Fr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),C){let me=Ie("chevron-down",14,"currentColor",2);me&&P.appendChild(me)}}else o&&T?(W=w("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),P=h?ai({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Fr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Fr({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=Fr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):P=Fr({icon:"copy",label:"Copy"});let j=o?Fr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Fr({icon:"refresh-cw",label:"Refresh"}),ce=o?Fr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Fr({icon:"x",label:"Close"}),be=()=>{var mt,Re,ye;let me=(mt=We.find(ot=>ot.id===Z))!=null?mt:We[We.length-1],te=(Re=me==null?void 0:me.id)!=null?Re:null,le=(me==null?void 0:me.artifactType)==="markdown"&&(ye=me.markdown)!=null?ye:"",ht=me?JSON.stringify({component:me.component,props:me.props},null,2):"";return{markdown:le,jsonPayload:ht,id:te}},Ze=async()=>{var mt;let{markdown:me,jsonPayload:te}=be(),le=(mt=We.find(Re=>Re.id===Z))!=null?mt:We[We.length-1],ht=(le==null?void 0:le.artifactType)==="markdown"?me:le?te:"";try{await navigator.clipboard.writeText(ht)}catch{}};if(P.addEventListener("click",async()=>{let me=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(me&&T){let{markdown:te,jsonPayload:le,id:ht}=be();try{await me({actionId:"primary",artifactId:ht,markdown:te,jsonPayload:le})}catch{}return}await Ze()}),R&&(v!=null&&v.length)){let me=()=>{var le;return(le=u.closest("[data-persona-root]"))!=null?le:document.body},te=()=>{N=Ko({items:v.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:ht,jsonPayload:mt,id:Re}=be(),ye=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{ye?await ye({actionId:le,artifactId:Re,markdown:ht,jsonPayload:mt}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(ht):le==="json"||le==="source"?await navigator.clipboard.writeText(mt):await navigator.clipboard.writeText(ht||mt)}catch{}},anchor:W!=null?W:R,position:"bottom-right",portal:me()})};u.isConnected?te():requestAnimationFrame(te),R.addEventListener("click",le=>{le.stopPropagation(),N==null||N.toggle()})}j.addEventListener("click",async()=>{var me;try{await((me=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:me.call(r))}catch{}ee()}),ce.addEventListener("click",()=>{var me;p(),(me=e.onDismiss)==null||me.call(e)});let Se=()=>{o&&(k.setAttribute("aria-pressed",x==="rendered"?"true":"false"),E.setAttribute("aria-pressed",x==="source"?"true":"false"))};k.addEventListener("click",()=>{x="rendered",Se(),ee()}),E.addEventListener("click",()=>{x="source",Se(),ee()});let Ne=w("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(k,E),W?M.append(W,j,ce):M.append(P,j,ce),f.append(S,Ne,M),Se()):(f.appendChild(m),f.appendChild(y)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Ce=w("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"),Fe=w("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ce.style.paddingLeft=s,Ce.style.paddingRight=s,Fe.style.padding=s),u.appendChild(f),u.appendChild(Ce),u.appendChild(Fe);let We=[],Z=null,ne=!1,ee=()=>{var ht,mt,Re,ye;let me=o&&We.length<=1;Ce.classList.toggle("persona-hidden",me),Ce.replaceChildren();for(let ot of We){let He=w("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=ot.title||ot.id.slice(0,8),ot.id===Z&&He.classList.add("persona-bg-persona-container","persona-border-persona-border"),He.addEventListener("click",()=>e.onSelect(ot.id)),Ce.appendChild(He)}Fe.replaceChildren();let te=Z&&We.find(ot=>ot.id===Z)||We[We.length-1];if(!te)return;if(o){let ot=te.artifactType==="markdown"?"MD":(ht=te.component)!=null?ht:"Component",G=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ne.textContent=`${G} \xB7 ${ot}`}else m.textContent="Artifacts";if(te.artifactType==="markdown"){if(o&&x==="source"){let He=w("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");He.textContent=(mt=te.markdown)!=null?mt:"",Fe.appendChild(He);return}let ot=w("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ot.innerHTML=d((Re=te.markdown)!=null?Re:""),Fe.appendChild(ot);return}let le=te.component?Lo.get(te.component):void 0;if(le){let He={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let G=le((ye=te.props)!=null?ye:{},He);if(G){Fe.appendChild(G);return}}catch{}}Fe.appendChild(OC(te))},we=()=>{var te;let me=We.length>0;if(u.classList.toggle("persona-hidden",!me),l){let le=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,mt=((te=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;me&&mt&&ne?(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(me){var te,le,ht;We=me.artifacts,Z=(ht=(le=me.selectedId)!=null?le:(te=me.artifacts[me.artifacts.length-1])==null?void 0:te.id)!=null?ht:null,We.length>0&&(ne=!0),ee(),we()},setMobileOpen(me){ne=me,!me&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):we()}}}function Fn(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 Sy(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"),!Fn(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 NC(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 td(t,e){var d,l,p,u,f,m,y,x,S,k;if(!Fn(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"),NC(t),Sy(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=(k=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:k.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Sy(t,e)}var Ty=["panel","seamless"];function rd(t,e){var i,d,l,p,u,f;for(let m of Ty)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"),!Fn(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=Ty.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 My(t,e){var r,n,o;return!e||!Fn(t)?!1:((o=(n=(r=t.features)==null?void 0:r.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function _C(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 FC(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 $C(t,e,r){return r<e?e:Math.min(r,Math.max(e,t))}function UC(t,e,r,n){let o=t-n-2*e-r;return Math.max(0,o)}function ky(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 Ey(t,e,r,n,o,s){let a=_C(o,200),i=UC(e,r,n,200);i=Math.max(a,i);let d=FC(s);return d!==null&&(i=Math.min(i,d)),$C(t,a,i)}var Ly={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Cu=(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=Ly[a])!=null?x:Ly.init;s.classList.add("persona-form-card","persona-space-y-4");let d=w("div","persona-space-y-1"),l=w("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let k=w("p","persona-text-sm persona-text-persona-muted");k.textContent=i.description,d.appendChild(k)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(k=>{var v,T;let E=w("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${a}-${k.name}`;let M=w("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=k.label,E.appendChild(M);let h=(v=k.type)!=null?v:"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}-${k.name}`,C.name=k.name,C.placeholder=(T=k.placeholder)!=null?T:"",k.required&&(C.required=!0),E.appendChild(C),p.appendChild(E)});let u=w("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=w("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=w("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 k=>{var C,v;k.preventDefault();let E=(C=r.formEndpoint)!=null?C:"/form",M=new FormData(p),h={};M.forEach((T,W)=>{h[W]=T}),h.type=a,m.disabled=!0,f.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();f.textContent=(v=W.message)!=null?v:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await n.sendMessage(String(W.nextPrompt))}catch(T){f.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Au=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()}},ci=new Au;var Py=()=>{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 qC=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},zC=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},pi=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=qC(t),r=zC(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}},Su=t=>typeof t=="string"?t:t==null?"":String(t),Ea={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Su(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,n=Su(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:Su(r.text)}}},Iy=t=>Array.isArray(t)?t.map(e=>String(e)):[],ui=t=>{let e=new Set(Iy(t.getSessionMetadata().processedActionMessageIds)),r=()=>{e=new Set(Iy(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 VC=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}},jC=t=>t.map(e=>({...e,streaming:!1})),GC=t=>t.map(e=>({...e,status:"complete"})),nd=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?VC(r.getItem(t)):null},save:r=>{let n=e();if(n)try{let o={...r,messages:r.messages?jC(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 ls=bd(Yi(),1);function KC(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(!KC(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 od(){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,ls.parse)(r,ls.STR|ls.OBJ),s=XC(o,r);s&&(t=s)}catch{}return e=r.length,t},reset:()=>{t=null,e=0}}}function Ry(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function ad(t,e){let{config:r,message:n,onPropsUpdate:o}=e,s=Lo.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 Wy(){let t=od();return{processChunk:e=>t.processChunk(e),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function Hy(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 sd(t){let e=Hy(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 id(t){let e=Hy(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 JC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ld(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=JC}=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 k=[];for(let v=1;v<=5;v++){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",`${v} star${v>1?"s":""}: ${l[v-1]}`),T.title=l[v-1],T.dataset.rating=String(v),T.innerHTML=`
77
77
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
78
78
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
79
79
  </svg>
80
- `,E.addEventListener("click",()=>{m=y,k.forEach((B,P)=>{let R=P<y;B.classList.toggle("selected",R),B.setAttribute("aria-checked",P===y-1?"true":"false")})}),k.push(E),S.appendChild(E)}u.appendChild(S);let T=null;if(d){let y=document.createElement("div");y.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),y.appendChild(T),u.appendChild(y)}let M=document.createElement("div");M.className="persona-feedback-actions";let h=document.createElement("button");h.type="button",h.className="persona-feedback-btn persona-feedback-btn-skip",h.textContent=i,h.addEventListener("click",()=>{r==null||r(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=a,w.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let y=(T==null?void 0:T.value.trim())||void 0;await e(m,y),p.remove()}catch(y){w.disabled=!1,w.textContent=a,console.error("[CSAT Feedback] Failed to submit:",y)}}),M.appendChild(h),M.appendChild(w),u.appendChild(M),p.appendChild(u),p}function Yl(t){let{onSubmit:e,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,x.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,x.appendChild(S),f.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let h=document.createElement("span");h.className="persona-feedback-label-high",h.textContent=p,T.appendChild(M),T.appendChild(h);let w=document.createElement("div");w.className="persona-feedback-numbers";let y=[];for(let O=0;O<=10;O++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${O} out of 10`),V.textContent=String(O),V.dataset.rating=String(O),O<=6?V.classList.add("persona-feedback-detractor"):O<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{u=O,y.forEach((ne,be)=>{ne.classList.toggle("selected",be===O),ne.setAttribute("aria-checked",be===O?"true":"false")})}),y.push(V),w.appendChild(V)}k.appendChild(T),k.appendChild(w),f.appendChild(k);let E=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),f.appendChild(O)}let B=document.createElement("div");B.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{r==null||r(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await e(u,O),m.remove()}catch(O){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),B.appendChild(P),B.appendChild(R),f.appendChild(B),m.appendChild(f),m}var Ka="persona-chat-history",dC=30*1e3,cC={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function pC(t){var n,o,s;if(!t)return[];let e=[],r=Array.from((n=t.items)!=null?n:[]);for(let a of r){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=cC[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function Zl(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function uC(t){var e,r,n,o,s,a,i,d,l;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(r=t.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(n=t.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=t.clearOnChatClear)!=null?l:!0}:null}function fC(t){try{let e=t==="local"?localStorage:sessionStorage,r="__persist_test__";return e.setItem(r,"1"),e.removeItem(r),e}catch{return null}}var pu=t=>!t||typeof t!="object"?{}:{...t},Zx=t=>t.map(e=>({...e,streaming:!1})),ey=(t,e,r)=>{let n=t!=null&&t.markdown?na(t.markdown):null,o=Ea(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&r&&r())}let d;return t!=null&&t.postprocessMessage?d=t.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):n?d=n(a):d=oa(a),o?o(d):d}};function ty(t){var i,d,l,p;let e=v("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let r=(i=t==null?void 0:t.iconName)!=null?i:"upload",n=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(l=t==null?void 0:t.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=t==null?void 0:t.iconStrokeWidth)!=null?p:.5,a=Ie(r,n,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let m=v("span","persona-drop-overlay-label");m.textContent=t.label,e.appendChild(m)}return e}var ed=(t,e,r)=>{var Bu,Hu,Du,Ou,Nu,_u,Fu,$u,Uu,qu,zu,Vu,ju,Gu,Ku,Xu,Ju,Qu,Yu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,wf,vf,Cf,Af,Sf,Tf,Mf,kf,Ef;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let n=xl(e),o=Ys.getForInstance(n.plugins);n.components&&yo.registerAll(n.components);let s=Kx(),i=n.persistState===!1?null:(Bu=n.storageAdapter)!=null?Bu:jl(),d={},l=null,p=!1,m=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:A}=g;return A&&(p=!0),b}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let b=g!=null?g:{messages:[],metadata:{}};return m(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=m(g);b.metadata&&(d=pu(b.metadata)),(Hu=b.messages)!=null&&Hu.length&&(n={...n,initialMessages:b.messages}),(Du=b.artifacts)!=null&&Du.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Ou=b.selectedArtifactId)!=null?Ou:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=m({messages:[],metadata:{}});(Nu=c.messages)!=null&&Nu.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let u=()=>d,f=c=>{var b;d=(b=c({...d}))!=null?b:{},ya()},x=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Zs],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ha.message,ha.messageAndClick],S=ei({parsers:x,handlers:C,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let k=(Fu=(_u=n.launcher)==null?void 0:_u.enabled)!=null?Fu:!0,T=(Uu=($u=n.launcher)==null?void 0:$u.autoExpand)!=null?Uu:!1,M=(qu=n.autoFocusInput)!=null?qu:!1,h=T,w=k,y=(Vu=(zu=n.layout)==null?void 0:zu.header)==null?void 0:Vu.layout,E=!1,B=()=>Ho(n),P=()=>k||B(),R=B()?!1:k?T:!0,O=!1,V=null,ne=()=>{O=!0,V&&clearTimeout(V),V=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},be=ey(n,S,ne),Ye=(Gu=(ju=n.features)==null?void 0:ju.showReasoning)!=null?Gu:!0,Ge=(Xu=(Ku=n.features)==null?void 0:Ku.showToolCalls)!=null?Xu:!0,ve=(Qu=(Ju=n.features)==null?void 0:Ju.showEventStreamToggle)!=null?Qu:!1,Ee=(Zu=(Yu=n.features)==null?void 0:Yu.scrollToBottom)!=null?Zu:{},Ne=`${(tf=typeof n.persistState=="object"?(ef=n.persistState)==null?void 0:ef.keyPrefix:void 0)!=null?tf:"persona-"}event-stream`,X=ve?new Js(Ne):null,Ue=(of=(nf=(rf=n.features)==null?void 0:rf.eventStream)==null?void 0:nf.maxEvents)!=null?of:2e3,K=ve?new Xs(Ue,X):null,Te=ve?new Qs:null,oe=null,xe=!1,Me=null,Xe=0;X==null||X.open().then(()=>K==null?void 0:K.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ce={onCopy:c=>{var g,b;s.emit("message:copy",c),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(c.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(b=(g=n.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;s.emit("message:feedback",c),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(c.messageId,c.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(b=(g=n.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},te=(af=n.statusIndicator)!=null?af:{},le=c=>{var g,b,A,D;return c==="idle"?(g=te.idleText)!=null?g:Ur.idle:c==="connecting"?(b=te.connectingText)!=null?b:Ur.connecting:c==="connected"?(A=te.connectedText)!=null?A:Ur.connected:c==="error"?(D=te.errorText)!=null?D:Ur.error:Ur[c]};function ut(c,g,b,A){if(A==="idle"&&b.idleLink){c.textContent="";let D=document.createElement("a");D.href=b.idleLink,D.target="_blank",D.rel="noopener noreferrer",D.textContent=g,D.style.color="inherit",D.style.textDecoration="none",c.appendChild(D)}else c.textContent=g}let{wrapper:Ce,panel:he,pillRoot:rt}=mx(n),_e=gx(n,P()),{container:me,body:J,messagesWrapper:ze,suggestions:Z,textarea:ge,sendButton:z,sendButtonWrapper:Re,composerForm:Ae,statusText:fe,introTitle:pe,introSubtitle:Be,closeButton:Q,iconHolder:_,headerTitle:ke,headerSubtitle:He,header:Ve,footer:Je,actionsRow:gt,leftActions:at,rightActions:Mt}=_e,Xt=_e.setSendButtonMode,G=_e.micButton,Jt=_e.micButtonWrapper,st=_e.attachmentButton,_t=_e.attachmentButtonWrapper,de=_e.attachmentInput,ye=_e.attachmentPreviewsContainer;me.classList.add("persona-relative"),J.classList.add("persona-relative");let Rt=12,ar=()=>{var c;return(c=Ee.label)!=null?c:""},kt=()=>{var c;return(c=Ee.iconName)!=null?c:"arrow-down"},mr=()=>Ee.enabled!==!1,Ot=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let Wt=v("span","persona-flex persona-items-center"),St=v("span","");Ot.append(Wt,St),me.appendChild(Ot);let Et=()=>{let g=Je.style.display==="none"?0:Je.offsetHeight;Ot.style.bottom=`${g+Rt}px`};Et();let sr=()=>{let c=!!ar();Ot.setAttribute("aria-label",ar()||"Jump to latest"),Ot.title=ar(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Wt.innerHTML="";let g=Ie(kt(),"14px","currentColor",2);g?(Wt.appendChild(g),Wt.style.display=""):Wt.style.display="none",St.textContent=ar(),St.style.display=c?"":"none"};sr();let ft=null,dr=null,wr=o.find(c=>c.renderHeader);if(wr!=null&&wr.renderHeader){let c=wr.renderHeader({config:n,defaultRenderer:()=>{let g=go({config:n,showClose:P()});return ua(me,g,n),g.header},onClose:()=>Kt(!1,"user")});if(c){let g=me.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ve=c)}}let Lr=()=>{var g,b,A,D;if(!K)return;if(xe=!0,!oe&&K&&(oe=Nx({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Or(),config:n,plugins:o,getThroughput:()=>{var $;return($=Te==null?void 0:Te.getMetric())!=null?$:{status:"idle"}}})),oe&&(J.style.display="none",(g=Je.parentNode)==null||g.insertBefore(oe.element,Je),oe.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${en.actionIconColor}`;let $=(D=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!xe)return;let $=Date.now();$-Xe>=200&&(oe==null||oe.update(),Xe=$),Me=requestAnimationFrame(c)};Xe=0,Me=requestAnimationFrame(c),oo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Or=()=>{var c,g,b;if(xe){if(xe=!1,oe&&oe.element.remove(),J.style.display="",xt){xt.style.boxShadow="";let A=(b=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;A&&A.split(/\s+/).forEach(D=>D&&xt.classList.remove(D))}Me!==null&&(cancelAnimationFrame(Me),Me=null),oo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(ve){let c=(lf=(sf=n.features)==null?void 0:sf.eventStream)==null?void 0:lf.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=v("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let b=Ie("activity","18px","currentColor",1.5);b&&xt.appendChild(b);let A=_e.clearChatButtonWrapper,D=_e.closeButtonWrapper,$=A||D;$&&$.parentNode===Ve?Ve.insertBefore(xt,$):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}let sn=c=>{var A,D,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(b,U):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=v("input");U.type="file",U.accept=((A=g.allowedTypes)!=null?A:mo).join(","),U.multiple=((D=g.maxFiles)!=null?D:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},fr=o.find(c=>c.renderComposer);if(fr!=null&&fr.renderComposer){let c=n.composer,g=fr.renderComposer({config:n,defaultRenderer:()=>_a({config:n}).footer,onSubmit:b=>{var U;if(!W||W.isStreaming())return;let A=b.trim(),D=(U=ft==null?void 0:ft.hasAttachments())!=null?U:!1;if(!A&&!D)return;as();let $;D&&($=[],$.push(...ft.getContentParts()),A&&$.push(Rs(A))),W.sendMessage(A,{contentParts:$}),D&&ft.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{de==null||de.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((df=n.voiceRecognition)==null?void 0:df.enabled)===!0?()=>{dr==null||dr()}:void 0});g&&(Je.replaceWith(g),Je=g)}let Un=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ae=g),b&&(ge=b),A&&(z=A),D&&(G=D,Jt=D.parentElement),$&&(fe=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Z=U);let j=c.querySelector(".persona-attachment-button");j&&(st=j,_t=j.parentElement),de=c.querySelector('input[type="file"]'),ye=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(gt=F)};sn(Je),Un(Je);let Rr=(mf=(cf=n.layout)==null?void 0:cf.contentMaxWidth)!=null?mf:B()?(ff=(uf=(pf=n.launcher)==null?void 0:pf.composerBar)==null?void 0:uf.contentMaxWidth)!=null?ff:"720px":void 0;if(Rr&&(ze.style.maxWidth=Rr,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%"),Rr&&Ae&&!B()&&(Ae.style.maxWidth=Rr,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Rr&&Z&&!B()&&(Z.style.maxWidth=Rr,Z.style.marginLeft="auto",Z.style.marginRight="auto"),Rr&&ye&&!B()&&(ye.style.maxWidth=Rr,ye.style.marginLeft="auto",ye.style.marginRight="auto"),(gf=n.attachments)!=null&&gf.enabled&&de&&ye){ft=ca.fromConfig(n.attachments),ft.setPreviewsContainer(ye),de.addEventListener("change",b=>{let A=b.target;ft==null||ft.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=ty(c);me.appendChild(g)}(()=>{var A,D;let c=(D=(A=n.layout)==null?void 0:A.slots)!=null?D:{},g=$=>{switch($){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ze;case"footer-top":return Z;case"composer":return Ae;case"footer-bottom":return fe;default:return null}},b=($,U)=>{var j;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ve.insertBefore(U,Ve.firstChild);else if($==="header-right")Ve.appendChild(U);else{let F=Ve.querySelector(".persona-flex-col");F?(j=F.parentNode)==null||j.insertBefore(U,F.nextSibling):Ve.appendChild(U)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(U):J.insertBefore(U,J.firstChild);break}case"body-bottom":J.appendChild(U);break;case"footer-top":Z.replaceWith(U);break;case"footer-bottom":fe.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let j=U({config:n,defaultContent:()=>g($)});j&&b($,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,j)}})();let Pn=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let A=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let D=A.getAttribute("data-message-id");if(!D)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?($a.has(D)?$a.delete(D):$a.add(D),bx(D,A)):$==="tool"&&(Ua.has(D)?Ua.delete(D):Ua.add(D),wx(D,A,n)),Bn.delete(D)};ze.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))}),ze.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Pn(c))});let In=new Map;ze.addEventListener("click",c=>{var U;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.closest("[data-actions-for]");if(!A)return;let D=A.getAttribute("data-actions-for");if(!D)return;let $=b.getAttribute("data-action");if($==="copy"){let F=W.getMessages().find(We=>We.id===D);if(F&&ce.onCopy){let We=F.content||"";navigator.clipboard.writeText(We).then(()=>{b.classList.add("persona-message-action-success");let we=Ie("check",14,"currentColor",2);we&&(b.innerHTML="",b.appendChild(we)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let se=Ie("copy",14,"currentColor",2);se&&(b.innerHTML="",b.appendChild(se))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),ce.onCopy(F)}}else if($==="upvote"||$==="downvote"){let F=((U=In.get(D))!=null?U:null)===$,We=$==="upvote"?"thumbs-up":"thumbs-down";if(F){In.delete(D),b.classList.remove("persona-message-action-active");let we=Ie(We,14,"currentColor",2);we&&(b.innerHTML="",b.appendChild(we))}else{let we=$==="upvote"?"downvote":"upvote",se=A.querySelector(`[data-action="${we}"]`);if(se){se.classList.remove("persona-message-action-active");let ct=Ie(we==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(se.innerHTML="",se.appendChild(ct))}In.set(D,$),b.classList.add("persona-message-action-active");let Le=Ie(We,14,"currentColor",2);Le&&(Le.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Le)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Ze=W.getMessages().find(ht=>ht.id===D);Ze&&ce.onFeedback&&ce.onFeedback({type:$,messageId:Ze.id,message:Ze})}}}),ze.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.closest(".persona-approval-bubble");if(!A)return;let D=A.getAttribute("data-message-id");if(!D)return;let $=b.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",F=W.getMessages().find(we=>we.id===D);if(!(F!=null&&F.approval))return;let We=A.querySelector("[data-approval-buttons]");We&&We.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?W.resolveWebMcpApproval(D,U):W.resolveApproval(F.approval,U)});let ue=null,I=null,ee={artifacts:[],selectedId:null},Se=!1,nt={current:null};ze.addEventListener("click",c=>{var se,Le,De,Ze,ht;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((De=(Le=(se=n.features)==null?void 0:se.artifacts)==null?void 0:Le.onArtifactAction)==null?void 0:De.call(Le,{type:"download",artifactId:A}))===!0)return;let $=W.getArtifactById(A),U=$==null?void 0:$.markdown,j=($==null?void 0:$.title)||"artifact";if(!U){let ct=b.closest("[data-open-artifact]"),wt=ct==null?void 0:ct.closest("[data-message-id]"),vt=wt==null?void 0:wt.getAttribute("data-message-id");if(vt){let $e=W.getMessages().find(ot=>ot.id===vt);if($e!=null&&$e.rawContent)try{let ot=JSON.parse($e.rawContent);U=(Ze=ot==null?void 0:ot.props)==null?void 0:Ze.markdown,j=((ht=ot==null?void 0:ot.props)==null?void 0:ht.title)||j}catch{}}}if(!U)return;let F=new Blob([U],{type:"text/markdown"}),We=URL.createObjectURL(F),we=document.createElement("a");we.href=We,we.download=`${j}.md`,we.click(),URL.revokeObjectURL(We)}),ze.addEventListener("click",c=>{var $,U,j;let b=c.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||((j=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:j.call(U,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),Se=!1,W.selectArtifact(A),ln())}),ze.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Qt=_e.composerOverlay,Ft=(c,g,b)=>{var j,F,We,we;let A=g.trim();if(!A||!nt.current)return;let D=(j=c.getAttribute("data-tool-call-id"))!=null?j:"",$=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:A,answers:b.structured,values:(F=b.values)!=null?F:b.source==="multi"?A.split(", "):[A],isFreeText:$,source:b.source},bubbles:!0,composed:!0})),_o(Qt,D);let U=nt.current.getMessages().find(se=>{var Le;return((Le=se.toolCall)==null?void 0:Le.id)===D});(We=U==null?void 0:U.agentMetadata)!=null&&We.awaitingLocalTool?nt.current.resolveAskUserQuestion(U,(we=b.structured)!=null?we:A):nt.current.sendMessage(A)},tr=c=>{var D;let g=nt.current;if(!g)return;let b=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",A=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===b});A&&g.persistAskUserQuestionProgress(A,{answers:$l(c,A),currentIndex:En(c)})},Pr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Nr=c=>{var D,$,U;if((($=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=En(c),b=za(c);if(g>=b-1)return;let A=(U=nt.current)==null?void 0:U.getMessages().find(j=>{var F;return((F=j.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});A&&(Ul(c,A,n,g+1),tr(c))};Qt.addEventListener("click",c=>{var $,U,j,F,We,we,se,Le,De,Ze,ht,ct,wt,vt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let A=b.closest("[data-persona-ask-sheet-for]");if(!A)return;let D=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let qe=($=A.getAttribute("data-tool-call-id"))!=null?$:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:qe},bubbles:!0,composed:!0})),_o(Qt,qe);let $e=(U=nt.current)==null?void 0:U.getMessages().find(ot=>{var H;return((H=ot.toolCall)==null?void 0:H.id)===qe});(j=$e==null?void 0:$e.agentMetadata)!=null&&j.awaitingLocalTool&&((F=nt.current)==null||F.markAskUserQuestionResolved($e),(We=nt.current)==null||We.resolveAskUserQuestion($e,"(dismissed)"));return}if(D==="pick"){let qe=b.getAttribute("data-option-label");if(!qe)return;let $e=A.getAttribute("data-multi-select")==="true",ot=No(A);if(ot&&$e){let H=ma(A)[En(A)],Oe=new Set(Array.isArray(H)?H:[]);Oe.has(qe)?Oe.delete(qe):Oe.add(qe),Fo(A,Array.from(Oe)),tr(A);return}if(ot){Fo(A,qe),tr(A),Nr(A);return}if($e){let H=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",H?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!H);let Oe=A.querySelector('[data-ask-user-action="submit-multi"]');Oe&&(Oe.disabled=nu(A).length===0);return}Ft(A,qe,{source:"pick",values:[qe]});return}if(D==="submit-multi"){let qe=nu(A);if(qe.length===0)return;Ft(A,qe.join(", "),{source:"multi",values:qe});return}if(D==="open-free-text"){let qe=A.querySelector('[data-ask-free-text-row="true"]');if(qe){qe.classList.remove("persona-hidden");let $e=qe.querySelector('[data-ask-free-text-input="true"]');$e==null||$e.focus()}return}if(D==="focus-free-text"){let qe=A.querySelector('[data-ask-free-text-input="true"]');qe==null||qe.focus();return}if(D==="submit-free-text"){let qe=A.querySelector('[data-ask-free-text-input="true"]'),$e=(we=qe==null?void 0:qe.value)!=null?we:"";if(!$e.trim())return;if(No(A)){Fo(A,$e.trim()),tr(A),Nr(A);return}Ft(A,$e,{source:"free-text"});return}if(D==="next"||D==="back"){if(!nt.current)return;let qe=(se=A.getAttribute("data-tool-call-id"))!=null?se:"",$e=nt.current.getMessages().find(lt=>{var Pe;return((Pe=lt.toolCall)==null?void 0:Pe.id)===qe});if(!$e)return;let ot=A.querySelector('[data-ask-free-text-input="true"]'),H=(De=(Le=ot==null?void 0:ot.value)==null?void 0:Le.trim())!=null?De:"";if(H){let lt=ma(A)[En(A)];(typeof lt!="string"||lt!==H)&&Fo(A,H)}let Oe=D==="next"?1:-1,Qe=En(A)+Oe;Ul(A,$e,n,Qe),tr(A);return}if(D==="submit-all"){if(!nt.current)return;let qe=(Ze=A.getAttribute("data-tool-call-id"))!=null?Ze:"",$e=nt.current.getMessages().find(lt=>{var Pe;return((Pe=lt.toolCall)==null?void 0:Pe.id)===qe});if(!$e)return;let ot=A.querySelector('[data-ask-free-text-input="true"]'),H=(ct=(ht=ot==null?void 0:ot.value)==null?void 0:ht.trim())!=null?ct:"";H&&Fo(A,H);let Oe=$l(A,$e);nt.current.persistAskUserQuestionProgress($e,{answers:Oe,currentIndex:En(A)});let Qe=Pr(Oe);Ft(A,Qe||"(submitted)",{source:"submit-all",structured:Oe});return}if(D==="skip"){if(!nt.current)return;let qe=(wt=A.getAttribute("data-tool-call-id"))!=null?wt:"",$e=nt.current.getMessages().find(Pe=>{var zt;return((zt=Pe.toolCall)==null?void 0:zt.id)===qe});if(!$e)return;let ot=No(A),H=En(A),Oe=za(A),Qe=H>=Oe-1;if(!ot){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:qe},bubbles:!0,composed:!0})),_o(Qt,qe),(vt=$e.agentMetadata)!=null&&vt.awaitingLocalTool&&(nt.current.markAskUserQuestionResolved($e),nt.current.resolveAskUserQuestion($e,"(dismissed)"));return}Fo(A,"");let lt=A.querySelector('[data-ask-free-text-input="true"]');if(lt&&(lt.value=""),Qe){let Pe=$l(A,$e),zt=Pr(Pe);Ft(A,zt||"(skipped)",{source:"submit-all",structured:Pe});return}Ul(A,$e,n,H+1),tr(A);return}}),Qt.addEventListener("keydown",c=>{var $;if(c.key!=="Enter")return;let b=c.target;if(!(($=b.matches)!=null&&$.call(b,'[data-ask-free-text-input="true"]')))return;let A=b.closest("[data-persona-ask-sheet-for]");if(!A)return;c.preventDefault();let D=b.value;if(D.trim()){if(No(A)){Fo(A,D.trim()),tr(A),Nr(A);return}Ft(A,D,{source:"free-text"})}});let wn=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let b=Qt.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let A=Number(c.key),$=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[A-1];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",wn);let Vt=null,$t=null,Ir=null,vn=null,bo=()=>{};function eo(){vn==null||vn(),vn=null}let wo=()=>{var U;if(!Vt||!$t)return;let c=t.classList.contains("persona-artifact-appearance-seamless"),b=((U=t.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||t.classList.contains("persona-artifact-narrow-host")||b){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let A=Vt.firstElementChild;if(!A||A===$t)return;let D=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${D}px`,$t.style.zIndex="5";let $=A.offsetWidth-D/2;$t.style.left=`${Math.max(0,$)}px`},qn=()=>{},ln=()=>{var b,A,D,$,U;if(!ue||!Ln(n))return;zl(t,n),Vl(t,n),qn();let c=($=(D=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:D.narrowHostMaxWidth)!=null?$:520,g=he.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),ue.update(ee),Se?(ue.setMobileOpen(!1),ue.element.classList.add("persona-hidden"),(U=ue.backdrop)==null||U.classList.add("persona-hidden")):ee.artifacts.length>0&&(ue.element.classList.remove("persona-hidden"),ue.setMobileOpen(!0)),bo()};if(Ln(n)){he.style.position="relative";let c=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(me),ue=$x(n,{onSelect:b=>{var A;return(A=nt.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{Se=!0,ln()}}),ue.element.classList.add("persona-hidden"),Vt=g,g.appendChild(c),g.appendChild(ue.element),ue.backdrop&&he.appendChild(ue.backdrop),he.appendChild(g),bo=()=>{var A,D,$,U;if(!Vt||!ue)return;if(!((($=(D=(A=n.features)==null?void 0:A.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue.element.style.removeProperty("width"),ue.element.style.removeProperty("maxWidth");return}if(!$t){let j=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let F=t.ownerDocument,We=(U=F.defaultView)!=null?U:window,we=se=>{var wt,vt;if(!ue||se.button!==0||t.classList.contains("persona-artifact-narrow-host")||We.innerWidth<=640)return;se.preventDefault(),eo();let Le=se.clientX,De=ue.element.getBoundingClientRect().width,Ze=(vt=(wt=n.features)==null?void 0:wt.artifacts)==null?void 0:vt.layout,ht=qe=>{let $e=Vt.getBoundingClientRect().width,ot=t.classList.contains("persona-artifact-appearance-seamless"),H=ot?0:Vx(Vt,We),Oe=ot?0:j.getBoundingClientRect().width||6,Qe=De-(qe.clientX-Le),lt=jx(Qe,$e,H,Oe,Ze==null?void 0:Ze.resizableMinWidth,Ze==null?void 0:Ze.resizableMaxWidth);ue.element.style.width=`${lt}px`,ue.element.style.maxWidth="none",wo()},ct=()=>{F.removeEventListener("pointermove",ht),F.removeEventListener("pointerup",ct),F.removeEventListener("pointercancel",ct),vn=null;try{j.releasePointerCapture(se.pointerId)}catch{}};vn=ct,F.addEventListener("pointermove",ht),F.addEventListener("pointerup",ct),F.addEventListener("pointercancel",ct);try{j.setPointerCapture(se.pointerId)}catch{}};j.addEventListener("pointerdown",we),$t=j,Vt.insertBefore(j,ue.element),Ir=()=>{j.removeEventListener("pointerdown",we)}}if($t){let j=ee.artifacts.length>0&&!Se;$t.classList.toggle("persona-hidden",!j),wo()}},qn=()=>{var We,we,se,Le,De,Ze,ht,ct,wt,vt,qe,$e,ot,H;if(!k||!ue||((we=(We=n.launcher)==null?void 0:We.sidebarMode)!=null?we:!1)||Ar(n)&&kn(n).reveal==="emerge")return;let A=(se=t.ownerDocument.defaultView)!=null?se:window,D=(De=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?De:!0,$=(ht=(Ze=n.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?ht:640;if(D&&A.innerWidth<=$||!zx(n,k))return;let U=(vt=(wt=(ct=n.launcher)==null?void 0:ct.width)!=null?wt:n.launcherWidth)!=null?vt:yn,j=(H=(ot=($e=(qe=n.features)==null?void 0:qe.artifacts)==null?void 0:$e.layout)==null?void 0:ot.expandedPanelWidth)!=null?H:"min(720px, calc(100vw - 24px))";ee.artifacts.length>0&&!Se?(he.style.width=j,he.style.maxWidth=j):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(I=new ResizeObserver(()=>{ln()}),I.observe(he))}else he.appendChild(me),B()&&rt&&(_e.peekBanner&&rt.appendChild(_e.peekBanner),rt.appendChild(Je));t.appendChild(Ce),rt&&t.appendChild(rt);let Rn=()=>{var lt,Pe,zt,bt,yr,Wr,Gt,jr,Br,pt,Ct,Gr,Fr,jo,Go,Ko,Sa,Ta,cr,Xo,Po,Bt,rn,io,Kr,nn,Yt,ir;if(B()){he.style.width="100%",he.style.maxWidth="100%";let Zt=(Pe=(lt=n.launcher)==null?void 0:lt.composerBar)!=null?Pe:{},pr=Ce.dataset.state==="expanded",on=(zt=Zt.expandedSize)!=null?zt:"anchored";if(!(pr&&on!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let Cr=(yr=(bt=n.theme)==null?void 0:bt.components)==null?void 0:yr.panel,jn=Oa(n),lo=(Jo,Ai)=>{var fs;return Jo==null||Jo===""?Ai:(fs=Ha(jn,Jo))!=null?fs:Jo},wi="1px solid var(--persona-border)",vi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ci="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=lo(Cr==null?void 0:Cr.border,wi),me.style.borderRadius=lo(Cr==null?void 0:Cr.borderRadius,Ci),me.style.boxShadow=lo(Cr==null?void 0:Cr.shadow,vi),me.style.overflow="hidden";return}let c=Ar(n),g=(Gt=(Wr=n.launcher)==null?void 0:Wr.sidebarMode)!=null?Gt:!1,b=c||g||((Br=(jr=n.launcher)==null?void 0:jr.fullHeight)!=null?Br:!1),A=((pt=n.launcher)==null?void 0:pt.enabled)===!1,D=(Gr=(Ct=n.theme)==null?void 0:Ct.components)==null?void 0:Gr.panel,$=Oa(n),U=(Zt,pr)=>{var on;return Zt==null||Zt===""?pr:(on=Ha($,Zt))!=null?on:Zt},j=(Fr=t.ownerDocument.defaultView)!=null?Fr:window,F=(Go=(jo=n.launcher)==null?void 0:jo.mobileFullscreen)!=null?Go:!0,We=(Sa=(Ko=n.launcher)==null?void 0:Ko.mobileBreakpoint)!=null?Sa:640,we=j.innerWidth<=We,se=F&&we&&k,Le=(cr=(Ta=n.launcher)==null?void 0:Ta.position)!=null?cr:"bottom-left",De=Le==="bottom-left"||Le==="top-left",Ze=(Po=(Xo=n.launcher)==null?void 0:Xo.zIndex)!=null?Po:qr,ht=g||se?"none":"1px solid var(--persona-border)",ct=se?"none":g?De?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!se&&(ct="none",ht="none");let wt=g||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=U(D==null?void 0:D.border,ht),qe=U(D==null?void 0:D.shadow,ct),$e=U(D==null?void 0:D.borderRadius,wt),ot=J.scrollTop;t.style.cssText="",Ce.style.cssText="",he.style.cssText="",me.style.cssText="",J.style.cssText="",Je.style.cssText="";let H=()=>{var pr;if(ot<=0)return;((pr=J.ownerDocument.defaultView)!=null?pr:window).requestAnimationFrame(()=>{if(J.scrollTop===ot)return;let on=J.scrollHeight-J.clientHeight;on<=0||(J.scrollTop=Math.min(ot,on))})};if(se){Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ce.style.cssText=`
80
+ `,T.addEventListener("click",()=>{u=v,k.forEach((W,P)=>{let R=P<v;W.classList.toggle("selected",R),W.setAttribute("aria-checked",P===v-1?"true":"false")})}),k.push(T),S.appendChild(T)}f.appendChild(S);let E=null;if(d){let v=document.createElement("div");v.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"),v.appendChild(E),f.appendChild(v)}let M=document.createElement("div");M.className="persona-feedback-actions";let h=document.createElement("button");h.type="button",h.className="persona-feedback-btn persona-feedback-btn-skip",h.textContent=i,h.addEventListener("click",()=>{r==null||r(),p.remove()});let 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 v=(E==null?void 0:E.value.trim())||void 0;await e(u,v),p.remove()}catch(v){C.disabled=!1,C.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),M.appendChild(h),M.appendChild(C),f.appendChild(M),p.appendChild(f),p}function dd(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 k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let h=document.createElement("span");h.className="persona-feedback-label-high",h.textContent=p,E.appendChild(M),E.appendChild(h);let C=document.createElement("div");C.className="persona-feedback-numbers";let v=[];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,v.forEach((ce,be)=>{ce.classList.toggle("selected",be===N),ce.setAttribute("aria-checked",be===N?"true":"false")})}),v.push(j),C.appendChild(j)}k.appendChild(E),k.appendChild(C),m.appendChild(k);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=s,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 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=(T==null?void 0:T.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 ds="persona-chat-history",QC=30*1e3,YC={"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 ZC(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=YC[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 cd(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 eA(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 tA(t){try{let e=t==="local"?localStorage:sessionStorage,r="__persist_test__";return e.setItem(r,"1"),e.removeItem(r),e}catch{return null}}var Tu=t=>!t||typeof t!="object"?{}:{...t},By=t=>t.map(e=>({...e,streaming:!1})),Dy=(t,e,r)=>{let n=t!=null&&t.markdown?ma(t.markdown):null,o=qa(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=ga(a),o?o(d):d}};function Oy(t){var i,d,l,p;let e=w("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let r=(i=t==null?void 0:t.iconName)!=null?i:"upload",n=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(l=t==null?void 0:t.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=t==null?void 0:t.iconStrokeWidth)!=null?p:.5,a=Ie(r,n,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let u=w("span","persona-drop-overlay-label");u.textContent=t.label,e.appendChild(u)}return e}var pd=(t,e,r)=>{var 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,Wf,Hf,Bf,Df,Of,Nf,_f,Ff,$f,Uf,qf,zf,Vf,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf;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=Ml(e),o=ci.getForInstance(n.plugins);n.components&&Lo.registerAll(n.components);let s=Py(),i=n.persistState===!1?null:(nf=n.storageAdapter)!=null?nf:nd(),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=Tu(b.metadata)),(of=b.messages)!=null&&of.length&&(n={...n,initialMessages:b.messages}),(af=b.artifacts)!=null&&af.length&&(n={...n,initialArtifacts:b.artifacts,initialSelectedArtifactId:(sf=b.selectedArtifactId)!=null?sf: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:{}});(lf=c.messages)!=null&&lf.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:{},Wa()},y=n.actionParsers&&n.actionParsers.length?n.actionParsers:[pi],x=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ea.message,Ea.messageAndClick],S=ui({parsers:y,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let k=(cf=(df=n.launcher)==null?void 0:df.enabled)!=null?cf:!0,E=(uf=(pf=n.launcher)==null?void 0:pf.autoExpand)!=null?uf:!1,M=(ff=n.autoFocusInput)!=null?ff:!1,h=E,C=k,v=(gf=(mf=n.layout)==null?void 0:mf.header)==null?void 0:gf.layout,T=!1,W=()=>Go(n),P=()=>k||W(),R=W()?!1:k?E:!0,N=!1,j=null,ce=()=>{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)},be=Dy(n,S,ce),Ze=(xf=(hf=n.features)==null?void 0:hf.showReasoning)!=null?xf:!0,Se=(bf=(yf=n.features)==null?void 0:yf.showToolCalls)!=null?bf:!0,Ne=(vf=(wf=n.features)==null?void 0:wf.showEventStreamToggle)!=null?vf:!1,Ce=(Af=(Cf=n.features)==null?void 0:Cf.scrollToBottom)!=null?Af:{},Fe=(Tf=(Sf=n.features)==null?void 0:Sf.scrollBehavior)!=null?Tf:{},Z=`${(kf=typeof n.persistState=="object"?(Mf=n.persistState)==null?void 0:Mf.keyPrefix:void 0)!=null?kf:"persona-"}event-stream`,ne=Ne?new li(Z):null,ee=(Pf=(Lf=(Ef=n.features)==null?void 0:Ef.eventStream)==null?void 0:Lf.maxEvents)!=null?Pf:2e3,we=Ne?new ii(ee,ne):null,Q=Ne?new di:null,X=null,fe=!1,Le=null,me=0;ne==null||ne.open().then(()=>we==null?void 0:we.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var g,b;s.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;s.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)}},le=(If=n.statusIndicator)!=null?If:{},ht=c=>{var g,b,A,H;return c==="idle"?(g=le.idleText)!=null?g:Jr.idle:c==="connecting"?(b=le.connectingText)!=null?b:Jr.connecting:c==="connected"?(A=le.connectedText)!=null?A:Jr.connected:c==="error"?(H=le.errorText)!=null?H:Jr.error:Jr[c]};function mt(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:Re,panel:ye,pillRoot:ot}=jx(n),He=Gx(n,P()),{container:G,body:he,messagesWrapper:K,suggestions:wt,textarea:U,sendButton:J,sendButtonWrapper:qe,composerForm:se,statusText:ie,introTitle:Be,introSubtitle:Xe,closeButton:B,iconHolder:xe,headerTitle:De,headerSubtitle:rt,header:ze,footer:je,actionsRow:at,leftActions:Rt,rightActions:tr}=He,cr=He.setSendButtonMode,Y=He.micButton,vt=He.micButtonWrapper,ut=He.attachmentButton,Te=He.attachmentButtonWrapper,ue=He.attachmentInput,pt=He.attachmentPreviewsContainer;G.classList.add("persona-relative"),he.classList.add("persona-relative");let hr=12,xt=()=>{var c;return(c=Ce.label)!=null?c:""},vr=()=>{var c;return(c=Ce.iconName)!=null?c:"arrow-down"},Dr=()=>Ce.enabled!==!1,yt=()=>{var c;return(c=Fe.mode)!=null?c:"follow"},Dt=()=>{var c;return(c=Fe.anchorTopOffset)!=null?c:16},it=w("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");it.type="button",it.style.display="none",it.setAttribute("data-persona-scroll-to-bottom","true");let Xt=w("span","persona-flex persona-items-center"),Cr=w("span",""),pr=w("span","");pr.setAttribute("data-persona-scroll-to-bottom-count",""),pr.style.display="none",it.append(Xt,Cr,pr),G.appendChild(it);let xr=w("div","persona-stream-anchor-spacer");xr.setAttribute("aria-hidden","true"),xr.setAttribute("data-persona-anchor-spacer",""),xr.style.flexShrink="0",xr.style.pointerEvents="none",xr.style.height="0px",he.appendChild(xr);let Er=()=>{let g=je.style.display==="none"?0:je.offsetHeight;it.style.bottom=`${g+hr}px`};Er();let fn=()=>{let c=!!xt();it.setAttribute("aria-label",xt()||"Jump to latest"),it.title=xt(),it.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Xt.innerHTML="";let g=Ie(vr(),"14px","currentColor",2);g?(Xt.appendChild(g),Xt.style.display=""):Xt.style.display="none",Cr.textContent=xt(),Cr.style.display=c?"":"none"};fn();let Wt=null,zr=null,wr=o.find(c=>c.renderHeader);if(wr!=null&&wr.renderHeader){let c=wr.renderHeader({config:n,defaultRenderer:()=>{let g=Mo({config:n,showClose:P()});return Sa(G,g,n),g.header},onClose:()=>Yt(!1,"user")});if(c){let g=G.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),ze=c)}}let kn=()=>{var g,b,A,H;if(!we)return;if(fe=!0,!X&&we&&(X=wy({buffer:we,getFullHistory:()=>we.getAllFromStore(),onClose:()=>ln(),config:n,plugins:o,getThroughput:()=>{var F;return(F=Q==null?void 0:Q.getMetric())!=null?F:{status:"idle"}}})),X&&(he.style.display="none",(g=je.parentNode)==null||g.insertBefore(X.element,je),X.update()),Lt){Lt.style.boxShadow=`inset 0 0 0 1.5px ${sn.actionIconColor}`;let F=(H=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:H.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&Lt.classList.add($))}let c=()=>{if(!fe)return;let F=Date.now();F-me>=200&&(X==null||X.update(),me=F),Le=requestAnimationFrame(c)};me=0,Le=requestAnimationFrame(c),cn(),s.emit("eventStream:opened",{timestamp:Date.now()})},ln=()=>{var c,g,b;if(fe){if(fe=!1,X&&X.element.remove(),he.style.display="",Lt){Lt.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&&Lt.classList.remove(H))}Le!==null&&(cancelAnimationFrame(Le),Le=null),cn(),s.emit("eventStream:closed",{timestamp:Date.now()})}},Lt=null;if(Ne){let c=(Wf=(Rf=n.features)==null?void 0:Rf.eventStream)==null?void 0:Wf.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:"");Lt=w("button",g),Lt.style.width="28px",Lt.style.height="28px",Lt.style.color=sn.actionIconColor,Lt.type="button",Lt.setAttribute("aria-label","Event Stream"),Lt.title="Event Stream";let b=Ie("activity","18px","currentColor",1.5);b&&Lt.appendChild(b);let A=He.clearChatButtonWrapper,H=He.closeButtonWrapper,F=A||H;F&&F.parentNode===ze?ze.insertBefore(Lt,F):ze.appendChild(Lt),Lt.addEventListener("click",()=>{fe?ln():kn()})}let Jn=c=>{var A,H,F;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=w("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 $=w("input");$.type="file",$.accept=((A=g.allowedTypes)!=null?A:So).join(","),$.multiple=((H=g.maxFiles)!=null?H:4)>1,$.style.display="none",$.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild($)}},En=o.find(c=>c.renderComposer);if(En!=null&&En.renderComposer){let c=n.composer,g=En.renderComposer({config:n,defaultRenderer:()=>es({config:n}).footer,onSubmit:b=>{var $;if(!q||q.isStreaming())return;let A=b.trim(),H=($=Wt==null?void 0:Wt.hasAttachments())!=null?$:!1;if(!A&&!H)return;L();let F;H&&(F=[],F.push(...Wt.getContentParts()),A&&F.push(js(A))),q.sendMessage(A,{contentParts:F}),H&&Wt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ue==null||ue.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:((Hf=n.voiceRecognition)==null?void 0:Hf.enabled)===!0?()=>{zr==null||zr()}:void 0});g&&(je.replaceWith(g),je=g)}let Ge=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]"),F=c.querySelector("[data-persona-composer-status]");g&&(se=g),b&&(U=b),A&&(J=A),H&&(Y=H,vt=H.parentElement),F&&(ie=F);let $=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(wt=$);let V=c.querySelector(".persona-attachment-button");V&&(ut=V,Te=V.parentElement),ue=c.querySelector('input[type="file"]'),pt=c.querySelector(".persona-attachment-previews");let _=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(at=_)};Jn(je),Ge(je);let I=(_f=(Bf=n.layout)==null?void 0:Bf.contentMaxWidth)!=null?_f:W()?(Nf=(Of=(Df=n.launcher)==null?void 0:Df.composerBar)==null?void 0:Of.contentMaxWidth)!=null?Nf:"720px":void 0;if(I&&(K.style.maxWidth=I,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%"),I&&se&&!W()&&(se.style.maxWidth=I,se.style.marginLeft="auto",se.style.marginRight="auto"),I&&wt&&!W()&&(wt.style.maxWidth=I,wt.style.marginLeft="auto",wt.style.marginRight="auto"),I&&pt&&!W()&&(pt.style.maxWidth=I,pt.style.marginLeft="auto",pt.style.marginRight="auto"),(Ff=n.attachments)!=null&&Ff.enabled&&ue&&pt){Wt=va.fromConfig(n.attachments),Wt.setPreviewsContainer(pt),ue.addEventListener("change",b=>{let A=b.target;Wt==null||Wt.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=Oy(c);G.appendChild(g)}(()=>{var A,H;let c=(H=(A=n.layout)==null?void 0:A.slots)!=null?H:{},g=F=>{switch(F){case"body-top":return G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return K;case"footer-top":return wt;case"composer":return se;case"footer-bottom":return ie;default:return null}},b=(F,$)=>{var V;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")ze.insertBefore($,ze.firstChild);else if(F==="header-right")ze.appendChild($);else{let _=ze.querySelector(".persona-flex-col");_?(V=_.parentNode)==null||V.insertBefore($,_.nextSibling):ze.appendChild($)}break;case"body-top":{let _=he.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith($):he.insertBefore($,he.firstChild);break}case"body-bottom":he.appendChild($);break;case"footer-top":wt.replaceWith($);break;case"footer-bottom":ie.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(c))if($)try{let V=$({config:n,defaultContent:()=>g(F)});V&&b(F,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,V)}})();let Oe=c=>{var $,V;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 F=b.getAttribute("data-bubble-type");if(F==="reasoning")rs.has(H)?rs.delete(H):rs.add(H),Qx(H,A);else if(F==="tool")ns.has(H)?ns.delete(H):ns.add(H),Yx(H,A,n);else if(F==="approval"){let _=n.approval!==!1?n.approval:void 0,ke=(($=_==null?void 0:_.detailsDisplay)!=null?$:"collapsed")==="expanded",ve=(V=Yl.get(H))!=null?V:ke;Yl.set(H,!ve),gy(H,A,n)}fo.delete(H)};K.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Oe(c))}),K.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Oe(c))});let zt=new Map;K.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 H=A.getAttribute("data-actions-for");if(!H)return;let F=b.getAttribute("data-action");if(F==="copy"){let _=q.getMessages().find(ke=>ke.id===H);if(_&&te.onCopy){let ke=_.content||"";navigator.clipboard.writeText(ke).then(()=>{b.classList.add("persona-message-action-success");let ve=Ie("check",14,"currentColor",2);ve&&(b.innerHTML="",b.appendChild(ve)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let de=Ie("copy",14,"currentColor",2);de&&(b.innerHTML="",b.appendChild(de))},2e3)}).catch(ve=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ve)}),te.onCopy(_)}}else if(F==="upvote"||F==="downvote"){let _=(($=zt.get(H))!=null?$:null)===F,ke=F==="upvote"?"thumbs-up":"thumbs-down";if(_){zt.delete(H),b.classList.remove("persona-message-action-active");let ve=Ie(ke,14,"currentColor",2);ve&&(b.innerHTML="",b.appendChild(ve))}else{let ve=F==="upvote"?"downvote":"upvote",de=A.querySelector(`[data-action="${ve}"]`);if(de){de.classList.remove("persona-message-action-active");let nt=Ie(ve==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(de.innerHTML="",de.appendChild(nt))}zt.set(H,F),b.classList.add("persona-message-action-active");let Pe=Ie(ke,14,"currentColor",2);Pe&&(Pe.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Pe)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Ee=q.getMessages().find(gt=>gt.id===H);Ee&&te.onFeedback&&te.onFeedback({type:F,messageId:Ee.id,message:Ee})}}}),K.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 F=b.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",_=q.getMessages().find(ve=>ve.id===H);if(!(_!=null&&_.approval))return;let ke=A.querySelector("[data-approval-buttons]");ke&&ke.querySelectorAll("button").forEach(de=>{de.disabled=!0,de.style.opacity="0.5",de.style.cursor="not-allowed"}),_.approval.toolType==="webmcp"?q.resolveWebMcpApproval(H,$):q.resolveApproval(_.approval,$)});let st=null,Vt=null,or={artifacts:[],selectedId:null},fr=!1,Pt={current:null};K.addEventListener("click",c=>{var de,Pe,Ye,Ee,gt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((Ye=(Pe=(de=n.features)==null?void 0:de.artifacts)==null?void 0:Pe.onArtifactAction)==null?void 0:Ye.call(Pe,{type:"download",artifactId:A}))===!0)return;let F=q.getArtifactById(A),$=F==null?void 0:F.markdown,V=(F==null?void 0:F.title)||"artifact";if(!$){let nt=b.closest("[data-open-artifact]"),St=nt==null?void 0:nt.closest("[data-message-id]"),Tt=St==null?void 0:St.getAttribute("data-message-id");if(Tt){let _e=q.getMessages().find(tt=>tt.id===Tt);if(_e!=null&&_e.rawContent)try{let tt=JSON.parse(_e.rawContent);$=(Ee=tt==null?void 0:tt.props)==null?void 0:Ee.markdown,V=((gt=tt==null?void 0:tt.props)==null?void 0:gt.title)||V}catch{}}}if(!$)return;let _=new Blob([$],{type:"text/markdown"}),ke=URL.createObjectURL(_),ve=document.createElement("a");ve.href=ke,ve.download=`${V}.md`,ve.click(),URL.revokeObjectURL(ke)}),K.addEventListener("click",c=>{var F,$,V;let b=c.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||((V=($=(F=n.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:V.call($,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),fr=!1,q.selectArtifact(A),gn())}),K.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Vr=He.composerOverlay,Jt=(c,g,b)=>{var V,_,ke,ve;let A=g.trim();if(!A||!Pt.current)return;let H=(V=c.getAttribute("data-tool-call-id"))!=null?V:"",F=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:H,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(Vr,H);let $=Pt.current.getMessages().find(de=>{var Pe;return((Pe=de.toolCall)==null?void 0:Pe.id)===H});(ke=$==null?void 0:$.agentMetadata)!=null&&ke.awaitingLocalTool?Pt.current.resolveAskUserQuestion($,(ve=b.structured)!=null?ve:A):Pt.current.sendMessage(A)},jr=c=>{var H;let g=Pt.current;if(!g)return;let b=(H=c.getAttribute("data-tool-call-id"))!=null?H:"",A=g.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===b});A&&g.persistAskUserQuestionProgress(A,{answers:Jl(c,A),currentIndex:_n(c)})},$n=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),po=c=>{var H,F,$;if(((F=(H=n.features)==null?void 0:H.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=_n(c),b=as(c);if(g>=b-1)return;let A=($=Pt.current)==null?void 0:$.getMessages().find(V=>{var _;return((_=V.toolCall)==null?void 0:_.id)===c.getAttribute("data-tool-call-id")});A&&(Ql(c,A,n,g+1),jr(c))};Vr.addEventListener("click",c=>{var F,$,V,_,ke,ve,de,Pe,Ye,Ee,gt,nt,St,Tt;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 Ue=(F=A.getAttribute("data-tool-call-id"))!=null?F:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ue},bubbles:!0,composed:!0})),Qo(Vr,Ue);let _e=($=Pt.current)==null?void 0:$.getMessages().find(tt=>{var dt;return((dt=tt.toolCall)==null?void 0:dt.id)===Ue});(V=_e==null?void 0:_e.agentMetadata)!=null&&V.awaitingLocalTool&&((_=Pt.current)==null||_.markAskUserQuestionResolved(_e),(ke=Pt.current)==null||ke.resolveAskUserQuestion(_e,"(dismissed)"));return}if(H==="pick"){let Ue=b.getAttribute("data-option-label");if(!Ue)return;let _e=A.getAttribute("data-multi-select")==="true",tt=Jo(A);if(tt&&_e){let dt=Ma(A)[_n(A)],Nt=new Set(Array.isArray(dt)?dt:[]);Nt.has(Ue)?Nt.delete(Ue):Nt.add(Ue),Yo(A,Array.from(Nt)),jr(A);return}if(tt){Yo(A,Ue),jr(A),po(A);return}if(_e){let dt=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",dt?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!dt);let Nt=A.querySelector('[data-ask-user-action="submit-multi"]');Nt&&(Nt.disabled=yu(A).length===0);return}Jt(A,Ue,{source:"pick",values:[Ue]});return}if(H==="submit-multi"){let Ue=yu(A);if(Ue.length===0)return;Jt(A,Ue.join(", "),{source:"multi",values:Ue});return}if(H==="open-free-text"){let Ue=A.querySelector('[data-ask-free-text-row="true"]');if(Ue){Ue.classList.remove("persona-hidden");let _e=Ue.querySelector('[data-ask-free-text-input="true"]');_e==null||_e.focus()}return}if(H==="focus-free-text"){let Ue=A.querySelector('[data-ask-free-text-input="true"]');Ue==null||Ue.focus();return}if(H==="submit-free-text"){let Ue=A.querySelector('[data-ask-free-text-input="true"]'),_e=(ve=Ue==null?void 0:Ue.value)!=null?ve:"";if(!_e.trim())return;if(Jo(A)){Yo(A,_e.trim()),jr(A),po(A);return}Jt(A,_e,{source:"free-text"});return}if(H==="next"||H==="back"){if(!Pt.current)return;let Ue=(de=A.getAttribute("data-tool-call-id"))!=null?de:"",_e=Pt.current.getMessages().find(Ve=>{var Ke;return((Ke=Ve.toolCall)==null?void 0:Ke.id)===Ue});if(!_e)return;let tt=A.querySelector('[data-ask-free-text-input="true"]'),dt=(Ye=(Pe=tt==null?void 0:tt.value)==null?void 0:Pe.trim())!=null?Ye:"";if(dt){let Ve=Ma(A)[_n(A)];(typeof Ve!="string"||Ve!==dt)&&Yo(A,dt)}let Nt=H==="next"?1:-1,O=_n(A)+Nt;Ql(A,_e,n,O),jr(A);return}if(H==="submit-all"){if(!Pt.current)return;let Ue=(Ee=A.getAttribute("data-tool-call-id"))!=null?Ee:"",_e=Pt.current.getMessages().find(Ve=>{var Ke;return((Ke=Ve.toolCall)==null?void 0:Ke.id)===Ue});if(!_e)return;let tt=A.querySelector('[data-ask-free-text-input="true"]'),dt=(nt=(gt=tt==null?void 0:tt.value)==null?void 0:gt.trim())!=null?nt:"";dt&&Yo(A,dt);let Nt=Jl(A,_e);Pt.current.persistAskUserQuestionProgress(_e,{answers:Nt,currentIndex:_n(A)});let O=$n(Nt);Jt(A,O||"(submitted)",{source:"submit-all",structured:Nt});return}if(H==="skip"){if(!Pt.current)return;let Ue=(St=A.getAttribute("data-tool-call-id"))!=null?St:"",_e=Pt.current.getMessages().find(Ke=>{var Ae;return((Ae=Ke.toolCall)==null?void 0:Ae.id)===Ue});if(!_e)return;let tt=Jo(A),dt=_n(A),Nt=as(A),O=dt>=Nt-1;if(!tt){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ue},bubbles:!0,composed:!0})),Qo(Vr,Ue),(Tt=_e.agentMetadata)!=null&&Tt.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(_e),Pt.current.resolveAskUserQuestion(_e,"(dismissed)"));return}Yo(A,"");let Ve=A.querySelector('[data-ask-free-text-input="true"]');if(Ve&&(Ve.value=""),O){let Ke=Jl(A,_e),Ae=$n(Ke);Jt(A,Ae||"(skipped)",{source:"submit-all",structured:Ke});return}Ql(A,_e,n,dt+1),jr(A);return}}),Vr.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 H=b.value;if(H.trim()){if(Jo(A)){Yo(A,H.trim()),jr(A),po(A);return}Jt(A,H,{source:"free-text"})}});let Po=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=Vr.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",Po);let mn=null,Qt=null,Yr=null,Ln=null,Io=()=>{};function uo(){Ln==null||Ln(),Ln=null}let Ro=()=>{var $;if(!mn||!Qt)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){Qt.style.removeProperty("position"),Qt.style.removeProperty("left"),Qt.style.removeProperty("top"),Qt.style.removeProperty("bottom"),Qt.style.removeProperty("width"),Qt.style.removeProperty("z-index");return}let A=mn.firstElementChild;if(!A||A===Qt)return;let H=10;Qt.style.position="absolute",Qt.style.top="0",Qt.style.bottom="0",Qt.style.width=`${H}px`,Qt.style.zIndex="5";let F=A.offsetWidth-H/2;Qt.style.left=`${Math.max(0,F)}px`},Qn=()=>{},gn=()=>{var b,A,H,F,$;if(!st||!Fn(n))return;td(t,n),rd(t,n),Qn();let c=(F=(H=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:H.narrowHostMaxWidth)!=null?F:520,g=ye.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),st.update(or),fr?(st.setMobileOpen(!1),st.element.classList.add("persona-hidden"),($=st.backdrop)==null||$.classList.add("persona-hidden")):or.artifacts.length>0&&(st.element.classList.remove("persona-hidden"),st.setMobileOpen(!0)),Io()};if(Fn(n)){ye.style.position="relative";let c=w("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=w("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(G),st=Ay(n,{onSelect:b=>{var A;return(A=Pt.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{fr=!0,gn()}}),st.element.classList.add("persona-hidden"),mn=g,g.appendChild(c),g.appendChild(st.element),st.backdrop&&ye.appendChild(st.backdrop),ye.appendChild(g),Io=()=>{var A,H,F,$;if(!mn||!st)return;if(!(((F=(H=(A=n.features)==null?void 0:A.artifacts)==null?void 0:H.layout)==null?void 0:F.resizable)===!0)){Yr==null||Yr(),Yr=null,uo(),Qt&&(Qt.remove(),Qt=null),st.element.style.removeProperty("width"),st.element.style.removeProperty("maxWidth");return}if(!Qt){let V=w("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let _=t.ownerDocument,ke=($=_.defaultView)!=null?$:window,ve=de=>{var St,Tt;if(!st||de.button!==0||t.classList.contains("persona-artifact-narrow-host")||ke.innerWidth<=640)return;de.preventDefault(),uo();let Pe=de.clientX,Ye=st.element.getBoundingClientRect().width,Ee=(Tt=(St=n.features)==null?void 0:St.artifacts)==null?void 0:Tt.layout,gt=Ue=>{let _e=mn.getBoundingClientRect().width,tt=t.classList.contains("persona-artifact-appearance-seamless"),dt=tt?0:ky(mn,ke),Nt=tt?0:V.getBoundingClientRect().width||6,O=Ye-(Ue.clientX-Pe),Ve=Ey(O,_e,dt,Nt,Ee==null?void 0:Ee.resizableMinWidth,Ee==null?void 0:Ee.resizableMaxWidth);st.element.style.width=`${Ve}px`,st.element.style.maxWidth="none",Ro()},nt=()=>{_.removeEventListener("pointermove",gt),_.removeEventListener("pointerup",nt),_.removeEventListener("pointercancel",nt),Ln=null;try{V.releasePointerCapture(de.pointerId)}catch{}};Ln=nt,_.addEventListener("pointermove",gt),_.addEventListener("pointerup",nt),_.addEventListener("pointercancel",nt);try{V.setPointerCapture(de.pointerId)}catch{}};V.addEventListener("pointerdown",ve),Qt=V,mn.insertBefore(V,st.element),Yr=()=>{V.removeEventListener("pointerdown",ve)}}if(Qt){let V=or.artifacts.length>0&&!fr;Qt.classList.toggle("persona-hidden",!V),Ro()}},Qn=()=>{var ke,ve,de,Pe,Ye,Ee,gt,nt,St,Tt,Ue,_e,tt,dt;if(!k||!st||((ve=(ke=n.launcher)==null?void 0:ke.sidebarMode)!=null?ve:!1)||Br(n)&&Nn(n).reveal==="emerge")return;let A=(de=t.ownerDocument.defaultView)!=null?de:window,H=(Ye=(Pe=n.launcher)==null?void 0:Pe.mobileFullscreen)!=null?Ye:!0,F=(gt=(Ee=n.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?gt:640;if(H&&A.innerWidth<=F||!My(n,k))return;let $=(Tt=(St=(nt=n.launcher)==null?void 0:nt.width)!=null?St:n.launcherWidth)!=null?Tt:Tn,V=(dt=(tt=(_e=(Ue=n.features)==null?void 0:Ue.artifacts)==null?void 0:_e.layout)==null?void 0:tt.expandedPanelWidth)!=null?dt:"min(720px, calc(100vw - 24px))";or.artifacts.length>0&&!fr?(ye.style.width=V,ye.style.maxWidth=V):(ye.style.width=$,ye.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Vt=new ResizeObserver(()=>{gn()}),Vt.observe(ye))}else ye.appendChild(G),W()&&ot&&(He.peekBanner&&ot.appendChild(He.peekBanner),ot.appendChild(je));t.appendChild(Re),ot&&t.appendChild(ot);let Un=()=>{var Ve,Ke,Ae,nr,Zt,mr,Ft,ur,bn,Lr,ct,jt,Rr,Bn,wn,na,oa,_a,Fa,yr,aa,$o,Uo,yo,bt,$r,Zr,Pr;if(W()){ye.style.width="100%",ye.style.maxWidth="100%";let Mt=(Ke=(Ve=n.launcher)==null?void 0:Ve.composerBar)!=null?Ke:{},Bt=Re.dataset.state==="expanded",kt=(Ae=Mt.expandedSize)!=null?Ae:"anchored";if(!(Bt&&kt!=="fullscreen")){G.style.background="",G.style.border="",G.style.borderRadius="",G.style.overflow="",G.style.boxShadow="";return}let Wr=(Zt=(nr=n.theme)==null?void 0:nr.components)==null?void 0:Zt.panel,no=Ya(n),Hr=(ia,Ii)=>{var Es;return ia==null||ia===""?Ii:(Es=Ja(no,ia))!=null?Es:ia},en="1px solid var(--persona-border)",Dn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",sa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";G.style.background="var(--persona-surface, #ffffff)",G.style.border=Hr(Wr==null?void 0:Wr.border,en),G.style.borderRadius=Hr(Wr==null?void 0:Wr.borderRadius,sa),G.style.boxShadow=Hr(Wr==null?void 0:Wr.shadow,Dn),G.style.overflow="hidden";return}let c=Br(n),g=(Ft=(mr=n.launcher)==null?void 0:mr.sidebarMode)!=null?Ft:!1,b=c||g||((bn=(ur=n.launcher)==null?void 0:ur.fullHeight)!=null?bn:!1),A=((Lr=n.launcher)==null?void 0:Lr.enabled)===!1,H=(jt=(ct=n.theme)==null?void 0:ct.components)==null?void 0:jt.panel,F=Ya(n),$=(Mt,Bt)=>{var kt;return Mt==null||Mt===""?Bt:(kt=Ja(F,Mt))!=null?kt:Mt},V=(Rr=t.ownerDocument.defaultView)!=null?Rr:window,_=(wn=(Bn=n.launcher)==null?void 0:Bn.mobileFullscreen)!=null?wn:!0,ke=(oa=(na=n.launcher)==null?void 0:na.mobileBreakpoint)!=null?oa:640,ve=V.innerWidth<=ke,de=_&&ve&&k,Pe=(Fa=(_a=n.launcher)==null?void 0:_a.position)!=null?Fa:"bottom-left",Ye=Pe==="bottom-left"||Pe==="top-left",Ee=(aa=(yr=n.launcher)==null?void 0:yr.zIndex)!=null?aa:Qr,gt=g||de?"none":"1px solid var(--persona-border)",nt=de?"none":g?Ye?"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&&!de&&(nt="none",gt="none");let St=g||de?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Tt=$(H==null?void 0:H.border,gt),Ue=$(H==null?void 0:H.shadow,nt),_e=$(H==null?void 0:H.borderRadius,St),tt=he.scrollTop;t.style.cssText="",Re.style.cssText="",ye.style.cssText="",G.style.cssText="",he.style.cssText="",je.style.cssText="";let dt=()=>{var Bt;if(tt<=0)return;((Bt=he.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(he.scrollTop===tt)return;let kt=he.scrollHeight-he.clientHeight;kt<=0||(he.scrollTop=Math.min(tt,kt))})};if(de){Re.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"),Re.style.cssText=`
81
81
  position: fixed !important;
82
82
  inset: 0 !important;
83
83
  width: 100% !important;
@@ -87,9 +87,9 @@ _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]
87
87
  padding: 0 !important;
88
88
  display: flex !important;
89
89
  flex-direction: column !important;
90
- z-index: ${Ze} !important;
90
+ z-index: ${Ee} !important;
91
91
  background-color: var(--persona-surface, #ffffff) !important;
92
- `,he.style.cssText=`
92
+ `,ye.style.cssText=`
93
93
  position: relative !important;
94
94
  display: flex !important;
95
95
  flex-direction: column !important;
@@ -102,7 +102,7 @@ _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]
102
102
  padding: 0 !important;
103
103
  box-shadow: none !important;
104
104
  border-radius: 0 !important;
105
- `,me.style.cssText=`
105
+ `,G.style.cssText=`
106
106
  display: flex !important;
107
107
  flex-direction: column !important;
108
108
  flex: 1 1 0% !important;
@@ -113,20 +113,20 @@ _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]
113
113
  overflow: hidden !important;
114
114
  border-radius: 0 !important;
115
115
  border: none !important;
116
- `,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0",E=!0,H();return}let Oe=(rn=(Bt=n==null?void 0:n.launcher)==null?void 0:Bt.width)!=null?rn:n==null?void 0:n.launcherWidth,Qe=Oe!=null?Oe:yn;if(!g&&!c)A&&b?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=Qe,he.style.maxWidth=Qe);else if(c)if(kn(n).reveal==="emerge"){let pr=kn(n).width;he.style.width=pr,he.style.maxWidth=pr}else he.style.width="100%",he.style.maxWidth="100%";if(qn(),he.style.boxShadow=qe,he.style.borderRadius=$e,me.style.border=vt,me.style.borderRadius=$e,c&&!se&&(D==null?void 0:D.border)===void 0&&(me.style.border="none",kn(n).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),b&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",A&&(t.style.width="100%"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.height="100%",A&&(Ce.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Je.style.flexShrink="0"),Ce.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!A&&!c&&((io=$n[Le])!=null?io:$n["bottom-right"]).split(" ").forEach(pr=>Ce.classList.add(pr)),g){let Zt=(nn=(Kr=n.launcher)==null?void 0:Kr.sidebarWidth)!=null?nn:"420px";Ce.style.cssText=`
116
+ `,he.style.flex="1 1 0%",he.style.minHeight="0",he.style.overflowY="auto",je.style.flexShrink="0",T=!0,dt();return}let Nt=(Uo=($o=n==null?void 0:n.launcher)==null?void 0:$o.width)!=null?Uo:n==null?void 0:n.launcherWidth,O=Nt!=null?Nt:Tn;if(!g&&!c)A&&b?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=O,ye.style.maxWidth=O);else if(c)if(Nn(n).reveal==="emerge"){let Bt=Nn(n).width;ye.style.width=Bt,ye.style.maxWidth=Bt}else ye.style.width="100%",ye.style.maxWidth="100%";if(Qn(),ye.style.boxShadow=Ue,ye.style.borderRadius=_e,G.style.border=Tt,G.style.borderRadius=_e,c&&!de&&(H==null?void 0:H.border)===void 0&&(G.style.border="none",Nn(n).side==="right"?G.style.borderLeft="1px solid var(--persona-border)":G.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%"),Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.height="100%",A&&(Re.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",G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.overflow="hidden",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.overflowY="auto",je.style.flexShrink="0"),Re.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=Xn[Pe])!=null?yo:Xn["bottom-right"]).split(" ").forEach(Bt=>Re.classList.add(Bt)),g){let Mt=($r=(bt=n.launcher)==null?void 0:bt.sidebarWidth)!=null?$r:"420px";Re.style.cssText=`
117
117
  position: fixed !important;
118
118
  top: 0 !important;
119
119
  bottom: 0 !important;
120
- width: ${Zt} !important;
120
+ width: ${Mt} !important;
121
121
  height: 100vh !important;
122
122
  max-height: 100vh !important;
123
123
  margin: 0 !important;
124
124
  padding: 0 !important;
125
125
  display: flex !important;
126
126
  flex-direction: column !important;
127
- z-index: ${Ze} !important;
128
- ${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
129
- `,he.style.cssText=`
127
+ z-index: ${Ee} !important;
128
+ ${Ye?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
129
+ `,ye.style.cssText=`
130
130
  position: relative !important;
131
131
  display: flex !important;
132
132
  flex-direction: column !important;
@@ -137,9 +137,9 @@ _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]
137
137
  min-height: 0 !important;
138
138
  margin: 0 !important;
139
139
  padding: 0 !important;
140
- box-shadow: ${qe} !important;
141
- border-radius: ${$e} !important;
142
- `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),me.style.cssText=`
140
+ box-shadow: ${Ue} !important;
141
+ border-radius: ${_e} !important;
142
+ `,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),G.style.cssText=`
143
143
  display: flex !important;
144
144
  flex-direction: column !important;
145
145
  flex: 1 1 0% !important;
@@ -148,29 +148,29 @@ _Details: ${r.message}_`:n}var Hs=t=>({isError:!0,content:[{type:"text",text:t}]
148
148
  min-height: 0 !important;
149
149
  max-height: 100% !important;
150
150
  overflow: hidden !important;
151
- border-radius: ${$e} !important;
152
- border: ${vt} !important;
153
- `,Je.style.cssText=`
151
+ border-radius: ${_e} !important;
152
+ border: ${Tt} !important;
153
+ `,je.style.cssText=`
154
154
  flex-shrink: 0 !important;
155
155
  border-top: none !important;
156
156
  padding: 8px 16px 12px 16px !important;
157
- `}if(!A&&!c){let Zt="max-height: -moz-available !important; max-height: stretch !important;",pr=g?"":"padding-top: 1.25em !important;",on=g?"":`z-index: ${(ir=(Yt=n.launcher)==null?void 0:Yt.zIndex)!=null?ir:qr} !important;`;Ce.style.cssText+=Zt+pr+on}H()};Rn(),Ro(t,n),zl(t,n),Vl(t,n);let Pt=[];Pt.push(()=>{document.removeEventListener("keydown",wn)});let gr=null,hr=null;Pt.push(()=>{gr==null||gr(),gr=null,hr==null||hr(),hr=null}),I&&Pt.push(()=>{I==null||I.disconnect(),I=null}),Pt.push(()=>{Ir==null||Ir(),Ir=null,eo(),$t&&($t.remove(),$t=null),ue==null||ue.element.style.removeProperty("width"),ue==null||ue.element.style.removeProperty("maxWidth")}),ve&&Pt.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),oe==null||oe.destroy(),oe=null,K==null||K.destroy(),K=null,X=null});let dn=null,vo=()=>{dn&&(dn(),dn=null),n.colorScheme==="auto"&&(dn=wl(()=>{Ro(t,n)}))};vo(),Pt.push(()=>{dn&&(dn(),dn=null)});let Cn=(hf=n.features)==null?void 0:hf.streamAnimation;if(Cn!=null&&Cn.type&&Cn.type!=="none"){let c=Us(Cn.type,Cn.plugins);c&&(_p(c,t),Pt.push(()=>cx(t)))}let Wn=Bx(Z),cn=null,W,pn=!1,Bn=ox(),to=new Map,zn=new Map,Ja=0,Hn=Al(),Dn=0,On=null,ro=!1,$o=!1,ni=4,Qa=24,oi=80,xa=new Map,Lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ya=(yf=(xf=n.voiceRecognition)==null?void 0:xf.autoResume)!=null?yf:!1,An=c=>{s.emit("voice:state",{active:Lt.active,source:c,timestamp:Date.now()})},tn=()=>{f(c=>({...c,voiceState:{active:Lt.active,timestamp:Date.now(),manuallyDeactivated:Lt.manuallyDeactivated}}))},ai=()=>{var A,D;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=pu(d.voiceState),g=!!c.active,b=Number((D=c.timestamp)!=null?D:0);Lt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<dC&&setTimeout(()=>{var $,U;Lt.active||(Lt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),An("restore"),W.isVoiceActive()&&q()}):Vo("restore"))},1e3)},si=()=>W?Zx(W.getMessages()).filter(c=>!c.__skipPersist):[];function ya(c){if(!(i!=null&&i.save))return;let b={messages:c?Zx(c):W?si():[],metadata:d,artifacts:ee.artifacts,selectedArtifactId:ee.selectedId};try{let A=i.save(b);A instanceof Promise&&A.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let no=null,ii=()=>Ce.querySelector("#persona-scroll-container")||J,Uo=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ro=!1},Za=()=>{On!==null&&(cancelAnimationFrame(On),On=null),$o=!1,Uo()},oo=()=>{if(!mr()||xe){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==me&&me.appendChild(Ot),Et();let c=Ns(J)>0;Ot.style.display=Hn.isFollowing()||!c?"none":""},es=()=>{Hn.pause()&&(Za(),oo())},Co=()=>{Hn.resume(),oo()},Ao=(c=!1)=>{Hn.isFollowing()&&(!c&&!pn||(On!==null&&(cancelAnimationFrame(On),On=null),$o=!0,On=requestAnimationFrame(()=>{On=null,$o=!1,Hn.isFollowing()&&li(ii(),c?220:140)})))},li=(c,g=500)=>{let b=c.scrollTop,A=Ns(c),D=A-b;if(Math.abs(D)<1){Dn=c.scrollTop;return}if(Math.abs(D)>=oi){Uo(),ro=!0,c.scrollTop=A,Dn=c.scrollTop,ro=!1;return}Uo();let $=performance.now();ro=!0;let U=F=>1-Math.pow(1-F,3),j=F=>{if(!Hn.isFollowing()){Uo();return}let We=Ns(c);We!==A&&(A=We,D=A-b);let we=F-$,se=Math.min(we/g,1),Le=U(se),De=b+D*Le;c.scrollTop=De,Dn=c.scrollTop,se<1?no=requestAnimationFrame(j):(c.scrollTop=A,Dn=c.scrollTop,no=null,ro=!1)};no=requestAnimationFrame(j)},di=c=>{let g=new Map;c.forEach(b=>{let A=xa.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!A&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(A!=null&&A.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(A?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),xa.clear(),g.forEach((b,A)=>{xa.set(A,b)})},qo=(c,g,b)=>{var ct,wt,vt,qe,$e,ot;let A=document.createElement("div"),$=(()=>{var Oe;let H=o.find(Qe=>Qe.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),U=(H,Oe)=>Oe==null?!1:typeof Oe=="string"?(H.textContent=Oe,!0):(H.appendChild(Oe),!0),j=new Set,F=new Set,We=o.some(H=>H.renderAskUserQuestion),we=[],se=[],Le=n.enableComponentStreaming!==!1;if(g.forEach(H=>{var jr,Br,pt,Ct,Gr,Fr,jo,Go,Ko,Sa,Ta,cr,Xo,Po;j.add(H.id);let Oe=We&&ho(H),Qe=!Oe&&H.role==="assistant"&&!H.variant&&Le&&Xl(H);if(!Qe&&zn.has(H.id)){let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime"),zn.delete(H.id)}let lt=ho(H)?`:${(jr=H.agentMetadata)!=null&&jr.askUserQuestionAnswered?"a":"u"}:${(Br=H.agentMetadata)!=null&&Br.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Pe=nx(H,Ja)+lt,zt=Oe||Qe?null:ax(Bn,H.id,Pe);if(zt){A.appendChild(zt.cloneNode(!0)),ho(H)&&((pt=H.toolCall)!=null&&pt.id)&&((Ct=H.agentMetadata)==null?void 0:Ct.awaitingLocalTool)===!0&&!((Gr=H.agentMetadata)!=null&&Gr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Va(H,n,_e.composerOverlay));return}let bt=null,yr=o.find(Bt=>!!(H.variant==="reasoning"&&Bt.renderReasoning||H.variant==="tool"&&Bt.renderToolCall||H.variant==="approval"&&Bt.renderApproval||!H.variant&&Bt.renderMessage)),Wr=(Fr=n.layout)==null?void 0:Fr.messages;if(ho(H)&&((jo=H.agentMetadata)==null?void 0:jo.askUserQuestionAnswered)===!0){to.delete(H.id);let Bt=c.querySelector(`#wrapper-${H.id}`);Bt==null||Bt.removeAttribute("data-preserve-runtime");return}if(ho(H)&&((Ko=(Go=n.features)==null?void 0:Go.askUserQuestion)==null?void 0:Ko.enabled)!==!1){let Bt=o.find(rn=>typeof rn.renderAskUserQuestion=="function");if(Bt&&nt.current){let rn=to.get(H.id),io=rn!==Pe,Kr=null;if(io){let{payload:ir,complete:Zt}=xo(H),pr=H.id,on=()=>{var fn;return(fn=nt.current)==null?void 0:fn.getMessages().find(Cr=>Cr.id===pr)};Kr=Bt.renderAskUserQuestion({message:H,payload:ir,complete:Zt,resolve:fn=>{var jn;let Cr=on();Cr&&((jn=nt.current)==null||jn.resolveAskUserQuestion(Cr,fn))},dismiss:()=>{var Cr,jn,lo;let fn=on();(Cr=fn==null?void 0:fn.agentMetadata)!=null&&Cr.awaitingLocalTool&&((jn=nt.current)==null||jn.markAskUserQuestionResolved(fn),(lo=nt.current)==null||lo.resolveAskUserQuestion(fn,"(dismissed)"))},config:n})}let nn=rn!=null;if(io&&Kr===null&&!nn){((Sa=H.agentMetadata)==null?void 0:Sa.awaitingLocalTool)===!0&&!((Ta=H.agentMetadata)!=null&&Ta.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Va(H,n,_e.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),A.appendChild(Yt),we.push({messageId:H.id,fingerprint:Pe,bubble:Kr});return}else{((cr=H.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Xo=H.agentMetadata)!=null&&Xo.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Va(H,n,_e.composerOverlay));return}}else if(yr)if(H.variant==="reasoning"&&H.reasoning&&yr.renderReasoning){if(!Ye)return;bt=yr.renderReasoning({message:H,defaultRenderer:()=>Xp(H,n),config:n})}else if(H.variant==="tool"&&H.toolCall&&yr.renderToolCall){if(!Ge)return;bt=yr.renderToolCall({message:H,defaultRenderer:()=>Jp(H,n),config:n})}else if(H.variant==="approval"&&H.approval&&yr.renderApproval){if(n.approval===!1)return;bt=yr.renderApproval({message:H,defaultRenderer:()=>ou(H,n),config:n})}else yr.renderMessage&&(bt=yr.renderMessage({message:H,defaultRenderer:()=>{let Bt=Fa(H,b,Wr,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n});return H.role!=="user"&&lu(Bt,H,n,W),Bt},config:n}));if(!bt&&Qe){let Bt=Jl(H);if(Bt){let rn=zn.get(H.id),io=rn!==Pe,Kr=n.wrapComponentDirectiveInBubble!==!1,nn=null;if(io){let Yt=Kl(Bt,{config:n,message:H,transform:b});if(Yt)if(Kr){let ir=document.createElement("div");if(ir.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Zt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}else{let ir=document.createElement("div");if(ir.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ir.id=`bubble-${H.id}`,ir.setAttribute("data-message-id",H.id),ir.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Zt=document.createElement("div");Zt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Zt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ir.appendChild(Zt)}ir.appendChild(Yt),nn=ir}}if(nn||rn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${H.id}`,Yt.setAttribute("data-wrapper-id",H.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),Kr||Yt.classList.add("persona-w-full"),A.appendChild(Yt),se.push({messageId:H.id,fingerprint:Pe,bubble:nn});return}}}if(!bt)if(H.variant==="reasoning"&&H.reasoning){if(!Ye)return;bt=Xp(H,n)}else if(H.variant==="tool"&&H.toolCall){if(!Ge)return;bt=Jp(H,n)}else if(H.variant==="approval"&&H.approval){if(n.approval===!1)return;bt=ou(H,n)}else{let Bt=(Po=n.layout)==null?void 0:Po.messages;Bt!=null&&Bt.renderUserMessage&&H.role==="user"?bt=Bt.renderUserMessage({message:H,config:n,streaming:!!H.streaming}):Bt!=null&&Bt.renderAssistantMessage&&H.role==="assistant"?bt=Bt.renderAssistantMessage({message:H,config:n,streaming:!!H.streaming}):bt=Fa(H,b,Bt,n.messageActions,ce,{loadingIndicatorRenderer:$,widgetConfig:n}),H.role!=="user"&&bt&&lu(bt,H,n,W)}let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-${H.id}`,Gt.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Gt.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&Gt.classList.add("persona-w-full"),Gt.appendChild(bt),sx(Bn,H.id,Pe,Gt),A.appendChild(Gt)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Qe=Oe.getAttribute("data-persona-ask-sheet-for");Qe&&!F.has(Qe)&&_o(_e.composerOverlay,Qe)}),(wt=(ct=n.features)==null?void 0:ct.toolCallDisplay)!=null&&wt.grouped){let H=[],Oe=[];g.forEach(Qe=>{if(Qe.variant==="tool"&&Qe.toolCall&&Ge){Oe.push(Qe);return}Oe.length>1&&H.push(Oe),Oe=[]}),Oe.length>1&&H.push(Oe),H.forEach((Qe,lt)=>{var Br,pt;let Pe=Qe.map(Ct=>Array.from(A.children).find(Gr=>Gr instanceof HTMLElement&&Gr.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(Pe.length<2)return;let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-tool-group-${lt}-${Qe[0].id}`,zt.setAttribute("data-wrapper-id",`tool-group-${lt}-${Qe[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let yr=document.createElement("div");yr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Wr=`Called ${Qe.length} tools`,Gt=(pt=(Br=n.toolCall)==null?void 0:Br.renderGroupedSummary)==null?void 0:pt.call(Br,{messages:Qe,toolCalls:Qe.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:Wr,config:n});U(yr,Gt)||(yr.textContent=Wr);let jr=document.createElement("div");jr.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(yr,jr),zt.appendChild(bt),Pe[0].before(zt),Pe.forEach((Ct,Gr)=>{let Fr=document.createElement("div");Fr.className="persona-tool-group-item persona-relative",Fr.setAttribute("data-persona-tool-group-item","true"),Gr<Pe.length-1&&Fr.setAttribute("data-persona-tool-group-connector","true"),Fr.appendChild(Ct),jr.appendChild(Fr)})})}ix(Bn,j);let De=g.some(H=>H.role==="assistant"&&H.streaming),Ze=g[g.length-1],ht=(Ze==null?void 0:Ze.role)==="assistant"&&!Ze.streaming&&Ze.variant!=="approval";if(pn&&g.some(H=>H.role==="user")&&!De&&!ht){let H={config:n,streaming:!0,location:"standalone",defaultRenderer:fa},Oe=o.find(lt=>lt.renderLoadingIndicator),Qe=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Qe=Oe.renderLoadingIndicator(H)),Qe===null&&((vt=n.loadingIndicator)!=null&&vt.render)&&(Qe=n.loadingIndicator.render(H)),Qe===null&&(Qe=fa()),Qe){let lt=document.createElement("div"),Pe=((qe=n.loadingIndicator)==null?void 0:qe.showBubble)!==!1;lt.className=Pe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),lt.setAttribute("data-typing-indicator","true"),lt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",lt.appendChild(Qe);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-typing-indicator",zt.setAttribute("data-wrapper-id","typing-indicator"),zt.appendChild(lt),A.appendChild(zt)}}if(!pn&&g.length>0){let H=g[g.length-1],Oe={config:n,lastMessage:H,messageCount:g.length},Qe=o.find(Pe=>Pe.renderIdleIndicator),lt=null;if(Qe!=null&&Qe.renderIdleIndicator&&(lt=Qe.renderIdleIndicator(Oe)),lt===null&&(($e=n.loadingIndicator)!=null&&$e.renderIdle)&&(lt=n.loadingIndicator.renderIdle(Oe)),lt){let Pe=document.createElement("div"),zt=((ot=n.loadingIndicator)==null?void 0:ot.showBubble)!==!1;Pe.className=zt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(lt);let bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Pe),A.appendChild(bt)}}if(vl(c,A),we.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Qe}of we){let lt=c.querySelector(`#wrapper-${H}`);lt&&Qe!==null&&(lt.replaceChildren(Qe),lt.setAttribute("data-bubble-fp",Oe),to.set(H,Oe))}if(to.size>0)for(let H of to.keys())j.has(H)||to.delete(H);if(se.length>0)for(let{messageId:H,fingerprint:Oe,bubble:Qe}of se){let lt=c.querySelector(`#wrapper-${H}`);lt&&Qe!==null&&(lt.replaceChildren(Qe),lt.setAttribute("data-bubble-fp",Oe),zn.set(H,Oe))}if(zn.size>0)for(let H of zn.keys())j.has(H)||zn.delete(H)},So=null,ci=()=>{var b;if(So)return;let c=A=>{let D=A.composedPath();D.includes(Ce)||rt&&D.includes(rt)||Kt(!1,"user")};So=c,((b=t.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},ts=()=>{var g;if(!So)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("pointerdown",So,!0),So=null};Pt.push(()=>ts());let To=null,pi=()=>{var b;if(To)return;let c=A=>{A.key==="Escape"&&(A.isComposing||Kt(!1,"user"))};To=c,((b=t.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},rs=()=>{var g;if(!To)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("keydown",To,!0),To=null};Pt.push(()=>rs());let Mo=!1,ns=new Set,ui=()=>{var g,b,A,D;let c=(A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:A.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},ao=()=>{var wt,vt,qe,$e;if(!B())return;let c=_e.peekBanner,g=_e.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(wt=W==null?void 0:W.getMessages())!=null?wt:[],A;for(let ot=b.length-1;ot>=0;ot--){let H=b[ot];if(H.role==="assistant"&&H.content){A=H;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let D=A.content,$=!!A.streaming,U=ui(),j=Ml(U),F=j.type!=="none"?Us(j.type,U==null?void 0:U.plugins):null,We=((vt=F==null?void 0:F.isAnimating)==null?void 0:vt.call(F,A))===!0,we=F!==null&&($||We);we&&F&&!ns.has(F.name)&&(_p(F,t),ns.add(F.name));let se=we&&(F!=null&&F.containerClass)?F.containerClass:null,Le=(qe=g.dataset.personaPeekStreamClass)!=null?qe:null;Le&&Le!==se&&(g.classList.remove(Le),delete g.dataset.personaPeekStreamClass),se&&Le!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),we?(g.style.setProperty("--persona-stream-step",`${j.speed}ms`),g.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let De=we?kl(D,j.buffer,F,A,$):D;if(we&&j.placeholder==="skeleton"&&$&&(!De||!De.trim())){let ot=document.createElement("div"),H=zs();H.classList.add("persona-pill-peek__skeleton"),ot.appendChild(H),vl(g,ot)}else{let ot=Math.max(0,De.length-100),H=De.length>100?De.slice(-100):De,Oe=oa(H);if(!we||!F){let Qe=De.length>100?`\u2026${H}`:H;g.textContent!==Qe&&(g.textContent=Qe)}else{let Qe=Oe;(F.wrap==="char"||F.wrap==="word")&&(Qe=qs(Oe,F.wrap,`peek-${A.id}`,{skipTags:F.skipTags,startIndex:ot}));let lt=document.createElement("div");if(lt.innerHTML=Qe,F.useCaret&&H.length>0){let Pe=El(),zt=lt.querySelectorAll(".persona-stream-char, .persona-stream-word"),bt=zt[zt.length-1];bt!=null&&bt.parentNode?bt.parentNode.insertBefore(Pe,bt.nextSibling):lt.appendChild(Pe)}vl(g,lt),($e=F.onAfterRender)==null||$e.call(F,{container:g,bubble:c,messageId:A.id,message:A,speed:j.speed,duration:j.duration})}}let ct=pn||Mo;c.classList.toggle("persona-pill-peek--visible",ct)};if(B()){let c=_e.peekBanner;if(c){let A=D=>{D.preventDefault(),D.stopPropagation(),Kt(!0,"user")};c.addEventListener("pointerdown",A),Pt.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{Mo||(Mo=!0,ao())},b=()=>{Mo&&(Mo=!1,ao())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",b),Pt.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",b)}),rt&&(rt.addEventListener("pointerenter",g),rt.addEventListener("pointerleave",b),Pt.push(()=>{rt.removeEventListener("pointerenter",g),rt.removeEventListener("pointerleave",b)}))}let fi=c=>{var Le,De,Ze,ht,ct,wt,vt,qe;let g=(De=(Le=n.launcher)==null?void 0:Le.composerBar)!=null?De:{},b=(Ze=g.expandedSize)!=null?Ze:"anchored",A=(ht=g.bottomOffset)!=null?ht:"16px",D=g.collapsedMaxWidth,$=(ct=g.expandedMaxWidth)!=null?ct:"880px",U=(wt=g.expandedTopOffset)!=null?wt:"5vh",j=(vt=g.modalMaxWidth)!=null?vt:"880px",F=(qe=g.modalMaxHeight)!=null?qe:"min(90vh, 800px)",We="calc(100vw - 32px)",we="var(--persona-pill-area-height, 80px)",se=Ce.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",rt){let $e=rt.style;$e.bottom=A,$e.width=D!=null?D:""}if(c&&b!=="fullscreen"){if(b==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=j,se.maxWidth=We,se.maxHeight=F,se.height=F;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${A} + ${we})`,se.top=U,se.width=$,se.maxWidth=We}},ko=()=>{var F,We,we,se,Le,De,Ze,ht;if(!P())return;if(B()){let wt=(we=((We=(F=n.launcher)==null?void 0:F.composerBar)!=null?We:{}).expandedSize)!=null?we:"anchored",vt=R?"expanded":"collapsed";Ce.dataset.state=vt,Ce.dataset.expandedSize=wt,rt&&(rt.dataset.state=vt,rt.dataset.expandedSize=wt),Ce.style.removeProperty("display"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),fi(R),me.style.display=R?"flex":"none",Rn(),R?(ci(),pi()):(ts(),rs()),ao();return}let c=Ar(n),g=(se=t.ownerDocument.defaultView)!=null?se:window,b=(De=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?De:640,A=(ht=(Ze=n.launcher)==null?void 0:Ze.mobileFullscreen)!=null?ht:!0,D=g.innerWidth<=b,$=A&&D&&k,U=kn(n).reveal;R?(Ce.style.removeProperty("display"),Ce.style.display=c?"flex":"",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),Fe?Fe.element.style.display="none":dt&&(dt.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Ce.style.removeProperty("display"),Ce.style.display="flex",Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.setProperty("display","none","important"),Ce.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ce.style.display="",Ce.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),Fe?Fe.element.style.display=c?"none":"":dt&&(dt.style.display=c?"none":""))},Kt=(c,g="user")=>{var $,U;if(!P()||R===c)return;let b=R;R=c,ko();let A=(()=>{var Ze,ht,ct,wt,vt,qe,$e,ot,H,Oe;let j=(ht=(Ze=n.launcher)==null?void 0:Ze.sidebarMode)!=null?ht:!1,F=(ct=t.ownerDocument.defaultView)!=null?ct:window,We=(vt=(wt=n.launcher)==null?void 0:wt.mobileFullscreen)!=null?vt:!0,we=($e=(qe=n.launcher)==null?void 0:qe.mobileBreakpoint)!=null?$e:640,se=F.innerWidth<=we,Le=Ar(n)&&We&&se,De=B()&&((Oe=(H=(ot=n.launcher)==null?void 0:ot.composerBar)==null?void 0:H.expandedSize)!=null?Oe:"fullscreen")==="fullscreen";return j||We&&se&&k||Le||De})();if(R&&A){if(!gr){let j=t.getRootNode(),F=j instanceof ShadowRoot?j.host:t.closest(".persona-host");F&&(gr=Fp(F,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:qr))}hr||(hr=$p(t.ownerDocument))}else R||(gr==null||gr(),gr=null,hr==null||hr(),hr=null);R&&(jt(),Ao(!0));let D={open:R,source:g,timestamp:Date.now()};R&&!b?s.emit("widget:opened",D):!R&&b&&s.emit("widget:closed",D),s.emit("widget:state",{open:R,launcherEnabled:k,voiceActive:Lt.active,streaming:W.isStreaming()})},ba=c=>{Xt(c?"stop":"send"),G&&(G.disabled=c),Wn.buttons.forEach(g=>{g.disabled=c}),Je.dataset.personaComposerStreaming=c?"true":"false",Je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},wa=()=>{Lt.active||ge&&ge.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>wa(),200)});let os=()=>{var b,A,D,$,U,j,F,We,we,se,Le;pe.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",Be.textContent=($=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ge.placeholder=(j=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?j:"How can I help...";let c=J.querySelector("[data-persona-intro-card]");if(c){let De=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=De?"":"none",De?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}!((we=(We=n.sendButton)==null?void 0:We.useIcon)!=null&&we)&&!(W!=null&&W.isStreaming())&&(z.textContent=(Le=(se=n.copy)==null?void 0:se.sendButtonLabel)!=null?Le:"Send"),ge.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ge.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let Vn=null,mi=()=>{Vn==null&&(Vn=setInterval(()=>{let c=ze.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Vn),Vn=null;return}let g=Date.now();c.forEach(b=>{let A=Number(b.getAttribute("data-tool-elapsed"));A&&(b.textContent=Vi(g-A))})},100))};if(W=new Ba(n,{onMessagesChanged(c){qo(ze,c,be),mi(),W&&(c.some(D=>D.role==="user")?Wn.render([],W,ge,c):Wn.render(n.suggestionChips,W,ge,c,n.suggestionChipsConfig)),Ao(!pn),di(c);let g=[...c].reverse().find(A=>A.role==="user"),b=Lt.lastUserMessageId;g&&g.id!==b&&(Lt.lastUserMessageId=g.id,s.emit("user:message",g)),Lt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ya(c),ao()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};ut(fe,(D=>{var $,U,j,F;return D==="idle"?($=g.idleText)!=null?$:Ur.idle:D==="connecting"?(U=g.connectingText)!=null?U:Ur.connecting:D==="connected"?(j=g.connectedText)!=null?j:Ur.connected:D==="error"?(F=g.errorText)!=null?F:Ur.error:Ur[D]})(c),g,c)},onStreamingChanged(c){pn=c,ba(c),W&&qo(ze,W.getMessages(),be),c||Ao(!0),ao()},onVoiceStatusChanged(c){var g,b;if(((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":ie(),N();break;case"speaking":ie(),ae();break;default:c==="idle"&&W.isBargeInActive()?(ie(),q(),G==null||G.setAttribute("aria-label","End voice session")):(Lt.active=!1,ie(),An("system"),tn());break}},onArtifactsState(c){ee=c,ln(),ya()}}),nt.current=W,((wf=(bf=n.voiceRecognition)==null?void 0:bf.provider)==null?void 0:wf.type)==="runtype")try{W.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&W.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||n.onSSEEvent)&&W.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,c,g),Te==null||Te.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,A;c&&(c.metadata&&(d=pu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length&&W.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&W.hydrateArtifacts(c.artifacts,(A=c.selectedArtifactId)!=null?A:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let as=()=>{var g,b,A;!B()||R||!((A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||A)||Kt(!0,"auto")},ss=c=>{var D;if(c.preventDefault(),W.isStreaming()){W.cancel(),Te==null||Te.reset(),oe==null||oe.update();return}let g=ge.value.trim(),b=(D=ft==null?void 0:ft.hasAttachments())!=null?D:!1;if(!g&&!b)return;as();let A;b&&(A=[],A.push(...ft.getContentParts()),g&&A.push(Rs(g))),ge.value="",ge.style.height="auto",zo(),W.sendMessage(g,{contentParts:A}),b&&ft.clearAttachments()},gi=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},va={...Cl},Ca=!1,zo=()=>{va={...Cl}},hi=()=>W.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),xi=c=>{if(!ge)return;Ca=!0,ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),Ca=!1;let g=ge.value.length;ge.setSelectionRange(g,g)},is=()=>{Ca||zo()},ls=c=>{if(ge){if(gi()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ge.selectionStart===0&&ge.selectionEnd===0,b=rx({direction:c.key==="ArrowUp"?"up":"down",history:hi(),currentValue:ge.value,atStart:g,state:va});if(va=b.state,b.handled){c.preventDefault(),b.value!==void 0&&xi(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(W.isStreaming()){c.preventDefault();return}zo(),c.preventDefault(),z.click()}}},ds=c=>{c.key!=="Escape"||c.isComposing||W.isStreaming()&&c.composedPath().includes(me)&&(W.cancel(),Te==null||Te.reset(),oe==null||oe.update(),zo(),c.preventDefault(),c.stopImmediatePropagation())},cs=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!ft)return;let g=pC(c.clipboardData);g.length!==0&&(c.preventDefault(),await ft.handleFiles(g))},zr=null,un=!1,so=null,yt=null,ps=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Vo=(c="user")=>{var $,U,j,F,We,we,se;if(un||W.isStreaming())return;let g=ps();if(!g)return;zr=new g;let A=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;zr.continuous=!0,zr.interimResults=!0,zr.lang="en-US";let D=ge.value;zr.onresult=Le=>{let De="",Ze="";for(let ct=0;ct<Le.results.length;ct++){let wt=Le.results[ct],vt=wt[0].transcript;wt.isFinal?De+=vt+" ":Ze=vt}let ht=D+De+Ze;ge.value=ht,so&&clearTimeout(so),(De||Ze)&&(so=window.setTimeout(()=>{let ct=ge.value.trim();ct&&zr&&un&&(Nn(),ge.value="",ge.style.height="auto",W.sendMessage(ct,{viaVoice:!0}))},A))},zr.onerror=Le=>{Le.error!=="no-speech"&&Nn()},zr.onend=()=>{if(un){let Le=ge.value.trim();Le&&Le!==D.trim()&&(ge.value="",ge.style.height="auto",W.sendMessage(Le,{viaVoice:!0})),Nn()}};try{if(zr.start(),un=!0,Lt.active=!0,c!=="system"&&(Lt.manuallyDeactivated=!1),An(c),tn(),G){let Le=(j=n.voiceRecognition)!=null?j:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(F=Le.iconName)!=null?F:"mic",iconSize:parseFloat((se=(we=Le.iconSize)!=null?we:(We=n.sendButton)==null?void 0:We.size)!=null?se:"40")||24};let De=Le.recordingBackgroundColor,Ze=Le.recordingIconColor,ht=Le.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Ze!=null?Ze:"var(--persona-voice-recording-indicator, #ffffff)",Ze){let ct=G.querySelector("svg");ct&&ct.setAttribute("stroke",Ze)}ht&&(G.style.borderColor=ht),G.setAttribute("aria-label","Stop voice recognition")}}catch{Nn("system")}},Nn=(c="user")=>{if(un){if(un=!1,so&&(clearTimeout(so),so=null),zr){try{zr.stop()}catch{}zr=null}if(Lt.active=!1,An(c),tn(),G){if(G.classList.remove("persona-voice-recording"),yt){G.style.backgroundColor=yt.backgroundColor,G.style.color=yt.color,G.style.borderColor=yt.borderColor;let g=G.querySelector("svg");g&&g.setAttribute("stroke",yt.color||"currentColor"),yt=null}G.setAttribute("aria-label","Start voice recognition")}}},yi=(c,g)=>{var wt,vt,qe,$e,ot,H,Oe,Qe;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((wt=c==null?void 0:c.provider)==null?void 0:wt.type)==="runtype";if(!(b||A))return null;let $=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let j=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",F=(qe=g==null?void 0:g.size)!=null?qe:"40px",We=($e=c==null?void 0:c.iconSize)!=null?$e:F,we=parseFloat(We)||24,se=(ot=c==null?void 0:c.backgroundColor)!=null?ot:g==null?void 0:g.backgroundColor,Le=(H=c==null?void 0:c.iconColor)!=null?H:g==null?void 0:g.textColor;U.style.width=We,U.style.height=We,U.style.minWidth=We,U.style.minHeight=We,U.style.fontSize="18px",U.style.lineHeight="1",Le?U.style.color=Le:U.style.color="var(--persona-text, #111827)";let Ze=Ie(j,we,Le||"currentColor",1.5);Ze?U.appendChild(Ze):U.textContent="\u{1F3A4}",se?U.style.backgroundColor=se:U.style.backgroundColor="",c!=null&&c.borderWidth&&(U.style.borderWidth=c.borderWidth,U.style.borderStyle="solid"),c!=null&&c.borderColor&&(U.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(U.style.paddingLeft=c.paddingX,U.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(U.style.paddingTop=c.paddingY,U.style.paddingBottom=c.paddingY),$.appendChild(U);let ht=(Oe=c==null?void 0:c.tooltipText)!=null?Oe:"Start voice recognition";if(((Qe=c==null?void 0:c.showTooltip)!=null?Qe:!1)&&ht){let lt=v("div","persona-send-button-tooltip");lt.textContent=ht,$.appendChild(lt)}return{micButton:U,micButtonWrapper:$}},Eo=()=>{var g,b,A,D,$;if(!G||yt)return;let c=(g=n.voiceRecognition)!=null?g:{};yt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat(($=(D=c.iconSize)!=null?D:(A=n.sendButton)==null?void 0:A.size)!=null?$:"40")||24}},it=(c,g)=>{var $,U,j,F,We;if(!G)return;let b=G.querySelector("svg");b&&b.remove();let A=(We=yt==null?void 0:yt.iconSize)!=null?We:parseFloat((F=(j=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?j:(U=n.sendButton)==null?void 0:U.size)!=null?F:"40")||24,D=Ie(c,A,g,1.5);D&&G.appendChild(D)},L=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},q=()=>{var D;if(!G)return;Eo();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,A=c.recordingBorderColor;if(L(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let $=G.querySelector("svg");$&&$.setAttribute("stroke",b)}A&&(G.style.borderColor=A),G.setAttribute("aria-label","Stop voice recognition")},N=()=>{var j,F,We,we,se,Le,De,Ze;if(!G)return;Eo();let c=(j=n.voiceRecognition)!=null?j:{},g=W.getVoiceInterruptionMode(),b=(F=c.processingIconName)!=null?F:"loader",A=(we=(We=c.processingIconColor)!=null?We:yt==null?void 0:yt.color)!=null?we:"",D=(Le=(se=c.processingBackgroundColor)!=null?se:yt==null?void 0:yt.backgroundColor)!=null?Le:"",$=(Ze=(De=c.processingBorderColor)!=null?De:yt==null?void 0:yt.borderColor)!=null?Ze:"";L(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=D,G.style.borderColor=$;let U=A||"currentColor";G.style.color=U,it(b,U),G.setAttribute("aria-label","Processing voice input"),g==="none"&&(G.style.cursor="default")},ae=()=>{var We,we,se,Le,De,Ze,ht,ct,wt,vt,qe,$e;if(!G)return;Eo();let c=(We=n.voiceRecognition)!=null?We:{},g=W.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(we=c.speakingIconName)!=null?we:b,D=(Ze=c.speakingIconColor)!=null?Ze:g==="barge-in"?(Le=(se=c.recordingIconColor)!=null?se:yt==null?void 0:yt.color)!=null?Le:"":(De=yt==null?void 0:yt.color)!=null?De:"",$=(wt=c.speakingBackgroundColor)!=null?wt:g==="barge-in"?(ht=c.recordingBackgroundColor)!=null?ht:"var(--persona-voice-recording-bg, #ef4444)":(ct=yt==null?void 0:yt.backgroundColor)!=null?ct:"",U=($e=c.speakingBorderColor)!=null?$e:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(qe=yt==null?void 0:yt.borderColor)!=null?qe:"";L(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=$,G.style.borderColor=U;let j=D||"currentColor";G.style.color=j,it(A,j);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",F),g==="none"&&(G.style.cursor="default"),g==="barge-in"&&G.classList.add("persona-voice-recording")},ie=()=>{var c,g,b;G&&(L(),yt&&(G.style.backgroundColor=(c=yt.backgroundColor)!=null?c:"",G.style.color=(g=yt.color)!=null?g:"",G.style.borderColor=(b=yt.borderColor)!=null?b:"",it(yt.iconName,yt.color||"currentColor"),yt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Y=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=W.getVoiceStatus(),A=W.getVoiceInterruptionMode();if(A==="none"&&(b==="processing"||b==="speaking"))return;if(A==="cancel"&&(b==="processing"||b==="speaking")){W.stopVoicePlayback();return}if(W.isBargeInActive()){W.stopVoicePlayback(),W.deactivateBargeIn().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),ie()});return}W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),Lt.manuallyDeactivated=!W.isVoiceActive(),tn(),An("user"),W.isVoiceActive()?q():ie()});return}if(un){let b=ge.value.trim();Lt.manuallyDeactivated=!0,tn(),Nn("user"),b&&(ge.value="",ge.style.height="auto",W.sendMessage(b))}else Lt.manuallyDeactivated=!1,tn(),Vo("user")};dr=Y,G&&(G.addEventListener("click",Y),Pt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(W.isVoiceActive()&&W.toggleVoice(),ie()):Nn("system"),G&&G.removeEventListener("click",Y)}));let je=s.on("assistant:complete",()=>{Ya&&(Lt.active||Lt.manuallyDeactivated||Ya==="assistant"&&!Lt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Lt.active&&!Lt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),An("auto"),W.isVoiceActive()&&q()}):Vo("auto"))},600))});Pt.push(je);let tt=s.on("action:resubmit",()=>{setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)});Pt.push(tt);let mt=()=>{Kt(!R,"user")},Fe=null,dt=null;if(k&&!B()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>js(n,mt).element,onToggle:mt});g&&(dt=g)}dt||(Fe=js(n,mt))}Fe?t.appendChild(Fe.element):dt&&t.appendChild(dt),ko(),Wn.render(n.suggestionChips,W,ge,void 0,n.suggestionChipsConfig),os(),ba(W.isStreaming()),Ao(!0),ai(),M&&(!k||B()?setTimeout(()=>wa(),0):R&&setTimeout(()=>wa(),200));let jt=()=>{var F,We,we,se,Le,De,Ze,ht,ct,wt,vt,qe,$e,ot,H,Oe,Qe,lt,Pe,zt,bt,yr;if(B()){Et(),ko();return}let c=Ar(n),g=(We=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?We:!1,b=c||g||((se=(we=n.launcher)==null?void 0:we.fullHeight)!=null?se:!1),A=(Le=t.ownerDocument.defaultView)!=null?Le:window,D=(Ze=(De=n.launcher)==null?void 0:De.mobileFullscreen)!=null?Ze:!0,$=(ct=(ht=n.launcher)==null?void 0:ht.mobileBreakpoint)!=null?ct:640,U=A.innerWidth<=$,j=D&&U&&k;try{if(j){Rn(),Ro(t,n);return}if(E&&(E=!1,Rn(),Ro(t,n)),!k&&!c){he.style.height="",he.style.width="";return}if(!g&&!c){let Wr=(vt=(wt=n==null?void 0:n.launcher)==null?void 0:wt.width)!=null?vt:n==null?void 0:n.launcherWidth,Gt=Wr!=null?Wr:yn;he.style.width=Gt,he.style.maxWidth=Gt}if(qn(),!b){let Wr=A.innerHeight,Gt=64,jr=($e=(qe=n.launcher)==null?void 0:qe.heightOffset)!=null?$e:0,Br=Math.max(200,Wr-Gt),pt=Math.min(640,Br),Ct=Math.max(200,pt-jr);he.style.height=`${Ct}px`}}finally{if(Et(),ko(),R&&k){let Gt=((ot=t.ownerDocument.defaultView)!=null?ot:window).innerWidth<=((Oe=(H=n.launcher)==null?void 0:H.mobileBreakpoint)!=null?Oe:640),jr=(lt=(Qe=n.launcher)==null?void 0:Qe.sidebarMode)!=null?lt:!1,Br=(zt=(Pe=n.launcher)==null?void 0:Pe.mobileFullscreen)!=null?zt:!0,pt=Ar(n)&&Br&&Gt,Ct=jr||Br&&Gt&&k||pt;if(Ct&&!hr){let Gr=t.getRootNode(),Fr=Gr instanceof ShadowRoot?Gr.host:t.closest(".persona-host");Fr&&!gr&&(gr=Fp(Fr,(yr=(bt=n.launcher)==null?void 0:bt.zIndex)!=null?yr:qr)),hr=$p(t.ownerDocument)}else Ct||(gr==null||gr(),gr=null,hr==null||hr(),hr=null)}}};jt();let Sr=(vf=t.ownerDocument.defaultView)!=null?vf:window;if(Sr.addEventListener("resize",jt),Pt.push(()=>Sr.removeEventListener("resize",jt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Et()});c.observe(Je),Pt.push(()=>c.disconnect())}Dn=J.scrollTop;let Nt=J.scrollHeight,qt=()=>{let c=J.scrollTop,g=J.scrollHeight,b=g<Nt;Nt=g;let{action:A,nextLastScrollTop:D}=Sl({following:Hn.isFollowing(),currentScrollTop:c,lastScrollTop:Dn,nearBottom:_s(J,Qa),userScrollThreshold:ni,isAutoScrolling:ro||$o||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=D,A==="resume"){Co();return}A==="pause"&&es()};J.addEventListener("scroll",qt,{passive:!0}),Pt.push(()=>J.removeEventListener("scroll",qt));let Tr=c=>{let g=Tl({following:Hn.isFollowing(),deltaY:c.deltaY,nearBottom:_s(J,Qa),resumeWhenNearBottom:!0});g==="pause"?es():g==="resume"&&Co()};J.addEventListener("wheel",Tr,{passive:!0}),Pt.push(()=>J.removeEventListener("wheel",Tr)),Ot.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,Dn=J.scrollTop,Co(),Ao(!0)}),Pt.push(()=>Ot.remove()),Pt.push(()=>{Za()});let _r=()=>{Q&&(cn&&(Q.removeEventListener("click",cn),cn=null),P()?(Q.style.display="",cn=()=>{Kt(!1,"user")},Q.addEventListener("click",cn)):Q.style.display="none")};_r(),(()=>{let{clearChatButton:c}=_e;c&&c.addEventListener("click",()=>{W.clearMessages(),Bn.clear(),Co(),_o(_e.composerOverlay);try{localStorage.removeItem(Ka),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ka}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ka)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},S.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),oe==null||oe.update()})})(),Ae&&Ae.addEventListener("submit",ss),ge==null||ge.addEventListener("keydown",ls),ge==null||ge.addEventListener("input",is),ge==null||ge.addEventListener("paste",cs);let xr=(Cf=t.ownerDocument)!=null?Cf:document;xr.addEventListener("keydown",ds,!0);let Sn="persona-attachment-drop-active",us=0,od=()=>{us=0,me.classList.remove(Sn)},Aa=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&ft!==null},Eu=c=>{!Zl(c.dataTransfer)||!Aa()||(us++,us===1&&me.classList.add(Sn))},Lu=c=>{!Zl(c.dataTransfer)||!Aa()||(us--,us<=0&&od())},Pu=c=>{!Zl(c.dataTransfer)||!Aa()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Iu=c=>{var b;if(!Zl(c.dataTransfer)||!Aa())return;c.preventDefault(),c.stopPropagation(),od();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&ft.handleFiles(g)},Lo=!0;me.addEventListener("dragenter",Eu,Lo),me.addEventListener("dragleave",Lu,Lo),t.addEventListener("dragover",Pu,Lo),t.addEventListener("drop",Iu,Lo);let bi=t.ownerDocument,Ru=c=>{Aa()&&c.preventDefault()},Wu=c=>{Aa()&&c.preventDefault()};bi.addEventListener("dragover",Ru),bi.addEventListener("drop",Wu),Pt.push(()=>{Ae&&Ae.removeEventListener("submit",ss),ge==null||ge.removeEventListener("keydown",ls),ge==null||ge.removeEventListener("input",is),ge==null||ge.removeEventListener("paste",cs),xr.removeEventListener("keydown",ds,!0)}),Pt.push(()=>{me.removeEventListener("dragenter",Eu,Lo),me.removeEventListener("dragleave",Lu,Lo),t.removeEventListener("dragover",Pu,Lo),t.removeEventListener("drop",Iu,Lo),bi.removeEventListener("dragover",Ru),bi.removeEventListener("drop",Wu),od()}),Pt.push(()=>{W.cancel()}),Fe?Pt.push(()=>{Fe==null||Fe.destroy()}):dt&&Pt.push(()=>{dt==null||dt.remove()});let vr={update(c){var Cr,jn,lo,wi,vi,Ci,Jo,Ai,fs,Lf,Pf,If,Rf,Wf,Bf,Hf,Df,Of,Nf,_f,Ff,$f,Uf,qf,zf,Vf,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,wm,vm,Cm,Am,Sm,Tm,Mm,km,Em,Lm,Pm,Im,Rm,Wm,Bm,Hm,Dm,Om,Nm,_m,Fm,$m,Um,qm,zm,Vm,jm,Gm,Km,Xm,Jm,Qm,Ym,Zm,eg,tg,rg,ng,og,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,wg,vg,Cg,Ag,Sg;let g=n.toolCall,b=n.messageActions,A=(Cr=n.layout)==null?void 0:Cr.messages,D=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,j=(jn=n.features)==null?void 0:jn.showReasoning,F=(lo=n.features)==null?void 0:lo.showToolCalls,We=(wi=n.features)==null?void 0:wi.toolCallDisplay,we=(vi=n.features)==null?void 0:vi.reasoningDisplay;n={...n,...c},Rn(),Ro(t,n),zl(t,n),Vl(t,n),ln(),n.colorScheme!==D&&vo();let se=Ys.getForInstance(n.plugins);o.length=0,o.push(...se),k=(Jo=(Ci=n.launcher)==null?void 0:Ci.enabled)!=null?Jo:!0,T=(fs=(Ai=n.launcher)==null?void 0:Ai.autoExpand)!=null?fs:!1,Ye=(Pf=(Lf=n.features)==null?void 0:Lf.showReasoning)!=null?Pf:!0,Ge=(Rf=(If=n.features)==null?void 0:If.showToolCalls)!=null?Rf:!0,Ee=(Bf=(Wf=n.features)==null?void 0:Wf.scrollToBottom)!=null?Bf:{},sr(),oo();let Le=ve;if(ve=(Df=(Hf=n.features)==null?void 0:Hf.showEventStreamToggle)!=null?Df:!1,ve&&!Le){if(K||(X=new Js(Ne),K=new Xs(Ue,X),Te=Te!=null?Te:new Qs,X.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),W.setSSEEventCallback((re,Dt)=>{var rr;(rr=n.onSSEEvent)==null||rr.call(n,re,Dt),Te==null||Te.processEvent(re,Dt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Dt)})})),!xt&&Ve){let re=(Nf=(Of=n.features)==null?void 0:Of.eventStream)==null?void 0:Nf.classNames,Dt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");xt=v("button",Dt),xt.style.width="28px",xt.style.height="28px",xt.style.color=en.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let rr=Ie("activity","18px","currentColor",1.5);rr&&xt.appendChild(rr);let At=_e.clearChatButtonWrapper,Ut=_e.closeButtonWrapper,Mr=At||Ut;Mr&&Mr.parentNode===Ve?Ve.insertBefore(xt,Mr):Ve.appendChild(xt),xt.addEventListener("click",()=>{xe?Or():Lr()})}}else!ve&&Le&&(Or(),xt&&(xt.remove(),xt=null),K==null||K.clear(),X==null||X.destroy(),K=null,X=null,Te==null||Te.reset(),Te=null);if(((_f=n.launcher)==null?void 0:_f.enabled)===!1&&Fe&&(Fe.destroy(),Fe=null),((Ff=n.launcher)==null?void 0:Ff.enabled)===!1&&dt&&(dt.remove(),dt=null),(($f=n.launcher)==null?void 0:$f.enabled)!==!1&&!Fe&&!dt){let re=o.find(Dt=>Dt.renderLauncher);if(re!=null&&re.renderLauncher){let Dt=re.renderLauncher({config:n,defaultRenderer:()=>js(n,mt).element,onToggle:mt});Dt&&(dt=Dt,t.appendChild(dt))}dt||(Fe=js(n,mt),t.appendChild(Fe.element))}Fe&&Fe.update(n),ke&&((Uf=n.launcher)==null?void 0:Uf.title)!==void 0&&(ke.textContent=n.launcher.title),He&&((qf=n.launcher)==null?void 0:qf.subtitle)!==void 0&&(He.textContent=n.launcher.subtitle);let De=(zf=n.layout)==null?void 0:zf.header;if((De==null?void 0:De.layout)!==y&&Ve){let re=De?Na(n,De,{showClose:P(),onClose:()=>Kt(!1,"user")}):go({config:n,showClose:P(),onClose:()=>Kt(!1,"user")});Ve.replaceWith(re.header),Ve=re.header,_=re.iconHolder,ke=re.headerTitle,He=re.headerSubtitle,Q=re.closeButton,y=De==null?void 0:De.layout}else if(De&&(_&&(_.style.display=De.showIcon===!1?"none":""),ke&&(ke.style.display=De.showTitle===!1?"none":""),He&&(He.style.display=De.showSubtitle===!1?"none":""),Q&&(Q.style.display=De.showCloseButton===!1?"none":""),_e.clearChatButtonWrapper)){let re=De.showClearChat;if(re!==void 0){_e.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Dt}=_e;Dt&&!Dt.classList.contains("persona-absolute")&&(re?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"))}}let ht=((Vf=n.layout)==null?void 0:Vf.showHeader)!==!1;Ve&&(Ve.style.display=ht?"":"none");let ct=((jf=n.layout)==null?void 0:jf.showFooter)!==!1;Je&&(Je.style.display=ct?"":"none"),Et(),oo(),k!==w?k?Kt(T,"auto"):(R=!0,ko()):T!==h&&Kt(T,"auto"),h=T,w=k,jt(),_r();let qe=JSON.stringify(c.toolCall)!==JSON.stringify(g),$e=JSON.stringify(n.messageActions)!==JSON.stringify(b),ot=JSON.stringify((Gf=n.layout)==null?void 0:Gf.messages)!==JSON.stringify(A),H=((Kf=n.loadingIndicator)==null?void 0:Kf.render)!==($==null?void 0:$.render)||((Xf=n.loadingIndicator)==null?void 0:Xf.renderIdle)!==($==null?void 0:$.renderIdle)||((Jf=n.loadingIndicator)==null?void 0:Jf.showBubble)!==($==null?void 0:$.showBubble),Oe=n.iterationDisplay!==U,Qe=((Yf=(Qf=n.features)==null?void 0:Qf.showReasoning)!=null?Yf:!0)!==(j!=null?j:!0)||((em=(Zf=n.features)==null?void 0:Zf.showToolCalls)!=null?em:!0)!==(F!=null?F:!0)||JSON.stringify((tm=n.features)==null?void 0:tm.toolCallDisplay)!==JSON.stringify(We)||JSON.stringify((rm=n.features)==null?void 0:rm.reasoningDisplay)!==JSON.stringify(we);(qe||$e||ot||H||Oe||Qe)&&W&&(Ja++,qo(ze,W.getMessages(),be));let Pe=(nm=n.launcher)!=null?nm:{},zt=(om=Pe.headerIconHidden)!=null?om:!1,bt=(sm=(am=n.layout)==null?void 0:am.header)==null?void 0:sm.showIcon,yr=zt||bt===!1,Wr=Pe.headerIconName,Gt=(im=Pe.headerIconSize)!=null?im:"48px";if(_){let re=me.querySelector(".persona-border-b-persona-divider"),Dt=re==null?void 0:re.querySelector(".persona-flex-col");if(yr)_.style.display="none",re&&Dt&&!re.contains(Dt)&&re.insertBefore(Dt,re.firstChild);else{if(_.style.display="",_.style.height=Gt,_.style.width=Gt,re&&Dt&&(re.contains(_)?_.nextSibling!==Dt&&(_.remove(),re.insertBefore(_,Dt)):re.insertBefore(_,Dt)),Wr){let At=parseFloat(Gt)||24,Ut=Ie(Wr,At*.6,"#ffffff",2);Ut?_.replaceChildren(Ut):_.textContent=(lm=Pe.agentIconText)!=null?lm:"\u{1F4AC}"}else if(Pe.iconUrl){let At=_.querySelector("img");if(At)At.src=Pe.iconUrl,At.style.height=Gt,At.style.width=Gt;else{let Ut=document.createElement("img");Ut.src=Pe.iconUrl,Ut.alt="",Ut.className="persona-rounded-xl persona-object-cover",Ut.style.height=Gt,Ut.style.width=Gt,_.replaceChildren(Ut)}}else{let At=_.querySelector("svg"),Ut=_.querySelector("img");(At||Ut)&&_.replaceChildren(),_.textContent=(dm=Pe.agentIconText)!=null?dm:"\u{1F4AC}"}let rr=_.querySelector("img");rr&&(rr.style.height=Gt,rr.style.width=Gt)}}let jr=(pm=(cm=n.layout)==null?void 0:cm.header)==null?void 0:pm.showTitle,Br=(fm=(um=n.layout)==null?void 0:um.header)==null?void 0:fm.showSubtitle;if(ke&&(ke.style.display=jr===!1?"none":""),He&&(He.style.display=Br===!1?"none":""),Q){((gm=(mm=n.layout)==null?void 0:mm.header)==null?void 0:gm.showCloseButton)===!1?Q.style.display="none":Q.style.display="";let Dt=(hm=Pe.closeButtonSize)!=null?hm:"32px",rr=(xm=Pe.closeButtonPlacement)!=null?xm:"inline";Q.style.height=Dt,Q.style.width=Dt;let{closeButtonWrapper:At}=_e,Ut=rr==="top-right",Mr=At==null?void 0:At.classList.contains("persona-absolute");if(At&&Ut!==Mr)if(At.remove(),Ut)At.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(At);else{let Tt=(bm=(ym=Pe.clearChat)==null?void 0:ym.placement)!=null?bm:"inline",kr=(vm=(wm=Pe.clearChat)==null?void 0:wm.enabled)!=null?vm:!0;At.className=kr&&Tt==="inline"?"":"persona-ml-auto";let an=me.querySelector(".persona-border-b-persona-divider");an&&an.appendChild(At)}if(Q.style.color=Pe.closeButtonColor||en.actionIconColor,Pe.closeButtonBackgroundColor?(Q.style.backgroundColor=Pe.closeButtonBackgroundColor,Q.classList.remove("hover:persona-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Tt=Pe.closeButtonBorderWidth||"0px",kr=Pe.closeButtonBorderColor||"transparent";Q.style.border=`${Tt} solid ${kr}`,Q.classList.remove("persona-border-none")}else Q.style.border="",Q.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Q.style.borderRadius=Pe.closeButtonBorderRadius,Q.classList.remove("persona-rounded-full")):(Q.style.borderRadius="",Q.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Q.style.paddingLeft=Pe.closeButtonPaddingX,Q.style.paddingRight=Pe.closeButtonPaddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),Pe.closeButtonPaddingY?(Q.style.paddingTop=Pe.closeButtonPaddingY,Q.style.paddingBottom=Pe.closeButtonPaddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let $r=(Cm=Pe.closeButtonIconName)!=null?Cm:"x",_n=(Am=Pe.closeButtonIconText)!=null?Am:"\xD7";Q.innerHTML="";let Xr=Ie($r,"28px","currentColor",1);Xr?Q.appendChild(Xr):Q.textContent=_n;let br=(Sm=Pe.closeButtonTooltipText)!=null?Sm:"Close chat",mn=(Tm=Pe.closeButtonShowTooltip)!=null?Tm:!0;if(Q.setAttribute("aria-label",br),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),mn&&br)){let Tt=null,kr=()=>{if(Tt||!Q)return;let Qo=Q.ownerDocument,ms=Qo.body;if(!ms)return;Tt=Qn(Qo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let gs=Qn(Qo,"div");gs.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(gs);let Yo=Q.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Wo),Tt.style.left=`${Yo.left+Yo.width/2}px`,Tt.style.top=`${Yo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",ms.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};At.addEventListener("mouseenter",kr),At.addEventListener("mouseleave",an),Q.addEventListener("focus",kr),Q.addEventListener("blur",an),At._cleanupTooltip=()=>{an(),At&&(At.removeEventListener("mouseenter",kr),At.removeEventListener("mouseleave",an)),Q&&(Q.removeEventListener("focus",kr),Q.removeEventListener("blur",an))}}}let{clearChatButton:pt,clearChatButtonWrapper:Ct}=_e;if(pt){let re=(Mm=Pe.clearChat)!=null?Mm:{},Dt=(km=re.enabled)!=null?km:!0,rr=(Lm=(Em=n.layout)==null?void 0:Em.header)==null?void 0:Lm.showClearChat,At=rr!==void 0?rr:Dt,Ut=(Pm=re.placement)!=null?Pm:"inline";if(Ct){Ct.style.display=At?"":"none";let{closeButtonWrapper:Mr}=_e;!B()&&Mr&&!Mr.classList.contains("persona-absolute")&&(At?Mr.classList.remove("persona-ml-auto"):Mr.classList.add("persona-ml-auto"));let $r=Ut==="top-right",_n=Ct.classList.contains("persona-absolute");if(!B()&&$r!==_n&&At){if(Ct.remove(),$r)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",me.style.position="relative",me.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let br=me.querySelector(".persona-border-b-persona-divider"),mn=_e.closeButtonWrapper;br&&mn&&mn.parentElement===br?br.insertBefore(Ct,mn):br&&br.appendChild(Ct)}let Xr=_e.closeButtonWrapper;Xr&&!Xr.classList.contains("persona-absolute")&&($r?Xr.classList.add("persona-ml-auto"):Xr.classList.remove("persona-ml-auto"))}}if(At){if(!B()){let Tt=(Im=re.size)!=null?Im:"32px";pt.style.height=Tt,pt.style.width=Tt}let Mr=(Rm=re.iconName)!=null?Rm:"refresh-cw",$r=(Wm=re.iconColor)!=null?Wm:"";pt.style.color=$r||en.actionIconColor,pt.innerHTML="";let _n=B()?"14px":"20px",Xr=Ie(Mr,_n,"currentColor",2);if(Xr&&pt.appendChild(Xr),re.backgroundColor?(pt.style.backgroundColor=re.backgroundColor,pt.classList.remove("hover:persona-bg-gray-100")):(pt.style.backgroundColor="",pt.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let Tt=re.borderWidth||"0px",kr=re.borderColor||"transparent";pt.style.border=`${Tt} solid ${kr}`,pt.classList.remove("persona-border-none")}else pt.style.border="",pt.classList.add("persona-border-none");re.borderRadius?(pt.style.borderRadius=re.borderRadius,pt.classList.remove("persona-rounded-full")):(pt.style.borderRadius="",pt.classList.add("persona-rounded-full")),re.paddingX?(pt.style.paddingLeft=re.paddingX,pt.style.paddingRight=re.paddingX):(pt.style.paddingLeft="",pt.style.paddingRight=""),re.paddingY?(pt.style.paddingTop=re.paddingY,pt.style.paddingBottom=re.paddingY):(pt.style.paddingTop="",pt.style.paddingBottom="");let br=(Bm=re.tooltipText)!=null?Bm:"Clear chat",mn=(Hm=re.showTooltip)!=null?Hm:!0;if(pt.setAttribute("aria-label",br),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),mn&&br)){let Tt=null,kr=()=>{if(Tt||!pt)return;let Qo=pt.ownerDocument,ms=Qo.body;if(!ms)return;Tt=Qn(Qo,"div","persona-clear-chat-tooltip"),Tt.textContent=br;let gs=Qn(Qo,"div");gs.className="persona-clear-chat-tooltip-arrow",Tt.appendChild(gs);let Yo=pt.getBoundingClientRect();Tt.style.position="fixed",Tt.style.zIndex=String(Wo),Tt.style.left=`${Yo.left+Yo.width/2}px`,Tt.style.top=`${Yo.top-8}px`,Tt.style.transform="translate(-50%, -100%)",ms.appendChild(Tt)},an=()=>{Tt&&Tt.parentNode&&(Tt.parentNode.removeChild(Tt),Tt=null)};Ct.addEventListener("mouseenter",kr),Ct.addEventListener("mouseleave",an),pt.addEventListener("focus",kr),pt.addEventListener("blur",an),Ct._cleanupTooltip=()=>{an(),Ct&&(Ct.removeEventListener("mouseenter",kr),Ct.removeEventListener("mouseleave",an)),pt&&(pt.removeEventListener("focus",kr),pt.removeEventListener("blur",an))}}}}let Gr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Zs],Fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ha.message,ha.messageAndClick];S=ei({parsers:Gr,handlers:Fr,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),be=ey(n,S,ne),W.updateConfig(n),qo(ze,W.getMessages(),be),Wn.render(n.suggestionChips,W,ge,void 0,n.suggestionChipsConfig),os(),ba(W.isStreaming());let jo=((Dm=n.voiceRecognition)==null?void 0:Dm.enabled)===!0,Go=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ko=((Nm=(Om=n.voiceRecognition)==null?void 0:Om.provider)==null?void 0:Nm.type)==="runtype";if(jo&&(Go||Ko))if(!G||!Jt){let re=yi(n.voiceRecognition,n.sendButton);re&&(G=re.micButton,Jt=re.micButtonWrapper,Mt.insertBefore(Jt,Re),G.addEventListener("click",Y),G.disabled=W.isStreaming())}else{let re=(_m=n.voiceRecognition)!=null?_m:{},Dt=(Fm=n.sendButton)!=null?Fm:{},rr=($m=re.iconName)!=null?$m:"mic",At=(Um=Dt.size)!=null?Um:"40px",Ut=(qm=re.iconSize)!=null?qm:At,Mr=parseFloat(Ut)||24;G.style.width=Ut,G.style.height=Ut,G.style.minWidth=Ut,G.style.minHeight=Ut;let $r=(Vm=(zm=re.iconColor)!=null?zm:Dt.textColor)!=null?Vm:"currentColor";G.innerHTML="";let _n=Ie(rr,Mr,$r,2);_n?G.appendChild(_n):G.textContent="\u{1F3A4}";let Xr=(jm=re.backgroundColor)!=null?jm:Dt.backgroundColor;Xr?G.style.backgroundColor=Xr:G.style.backgroundColor="",$r?G.style.color=$r:G.style.color="var(--persona-text, #111827)",re.borderWidth?(G.style.borderWidth=re.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),re.borderColor?G.style.borderColor=re.borderColor:G.style.borderColor="",re.paddingX?(G.style.paddingLeft=re.paddingX,G.style.paddingRight=re.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),re.paddingY?(G.style.paddingTop=re.paddingY,G.style.paddingBottom=re.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let br=Jt==null?void 0:Jt.querySelector(".persona-send-button-tooltip"),mn=(Gm=re.tooltipText)!=null?Gm:"Start voice recognition";if(((Km=re.showTooltip)!=null?Km:!1)&&mn)if(br)br.textContent=mn,br.style.display="";else{let kr=document.createElement("div");kr.className="persona-send-button-tooltip",kr.textContent=mn,Jt==null||Jt.insertBefore(kr,G)}else br&&(br.style.display="none");Jt.style.display="",G.disabled=W.isStreaming()}else G&&Jt&&(Jt.style.display="none",((Jm=(Xm=n.voiceRecognition)==null?void 0:Xm.provider)==null?void 0:Jm.type)==="runtype"?W.isVoiceActive()&&W.toggleVoice():un&&Nn());if(((Qm=n.attachments)==null?void 0:Qm.enabled)===!0)if(!_t||!st){let re=(Ym=n.attachments)!=null?Ym:{},rr=(eg=((Zm=n.sendButton)!=null?Zm:{}).size)!=null?eg:"40px";ye||(ye=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ye.style.display="none",Ae.insertBefore(ye,ge)),de||(de=document.createElement("input"),de.type="file",de.accept=((tg=re.allowedTypes)!=null?tg:mo).join(","),de.multiple=((rg=re.maxFiles)!=null?rg:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Ae.insertBefore(de,ge)),_t=v("div","persona-send-button-wrapper"),st=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),st.type="button",st.setAttribute("aria-label",(ng=re.buttonTooltipText)!=null?ng:"Attach file");let At=(og=re.buttonIconName)!=null?og:"paperclip",Ut=rr,Mr=parseFloat(Ut)||40,$r=Math.round(Mr*.6);st.style.width=Ut,st.style.height=Ut,st.style.minWidth=Ut,st.style.minHeight=Ut,st.style.fontSize="18px",st.style.lineHeight="1",st.style.backgroundColor="transparent",st.style.color="var(--persona-primary, #111827)",st.style.border="none",st.style.borderRadius="6px",st.style.transition="background-color 0.15s ease",st.addEventListener("mouseenter",()=>{st.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),st.addEventListener("mouseleave",()=>{st.style.backgroundColor="transparent"});let _n=Ie(At,$r,"currentColor",1.5);_n?st.appendChild(_n):st.textContent="\u{1F4CE}",st.addEventListener("click",mn=>{mn.preventDefault(),de==null||de.click()}),_t.appendChild(st);let Xr=(ag=re.buttonTooltipText)!=null?ag:"Attach file",br=v("div","persona-send-button-tooltip");br.textContent=Xr,_t.appendChild(br),at.append(_t),!ft&&de&&ye&&(ft=ca.fromConfig(re),ft.setPreviewsContainer(ye),de.addEventListener("change",async()=>{ft&&(de!=null&&de.files)&&(await ft.handleFileSelect(de.files),de.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(ty(re.dropOverlay))}else{_t.style.display="";let re=(sg=n.attachments)!=null?sg:{};de&&(de.accept=((ig=re.allowedTypes)!=null?ig:mo).join(","),de.multiple=((lg=re.maxFiles)!=null?lg:4)>1),ft&&ft.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else _t&&(_t.style.display="none"),ft&&ft.clearAttachments(),(dg=me.querySelector(".persona-attachment-drop-overlay"))==null||dg.remove();let cr=(cg=n.sendButton)!=null?cg:{},Xo=(pg=cr.useIcon)!=null?pg:!1,Po=(ug=cr.iconText)!=null?ug:"\u2191",Bt=cr.iconName,rn=(fg=cr.tooltipText)!=null?fg:"Send message",io=(mg=cr.showTooltip)!=null?mg:!1,Kr=(gg=cr.size)!=null?gg:"40px",nn=cr.backgroundColor,Yt=cr.textColor;if(Xo){if(z.style.width=Kr,z.style.height=Kr,z.style.minWidth=Kr,z.style.minHeight=Kr,z.style.fontSize="18px",z.style.lineHeight="1",z.innerHTML="",Yt?z.style.color=Yt:z.style.color="var(--persona-button-primary-fg, #ffffff)",Bt){let re=parseFloat(Kr)||24,Dt=(Yt==null?void 0:Yt.trim())||"currentColor",rr=Ie(Bt,re,Dt,2);rr?z.appendChild(rr):z.textContent=Po}else z.textContent=Po;z.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nn?(z.style.backgroundColor=nn,z.classList.remove("persona-bg-persona-primary")):(z.style.backgroundColor="",z.classList.add("persona-bg-persona-primary"))}else z.textContent=(xg=(hg=n.copy)==null?void 0:hg.sendButtonLabel)!=null?xg:"Send",z.style.width="",z.style.height="",z.style.minWidth="",z.style.minHeight="",z.style.fontSize="",z.style.lineHeight="",z.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nn?(z.style.backgroundColor=nn,z.classList.remove("persona-bg-persona-accent")):z.classList.add("persona-bg-persona-accent"),Yt?z.style.color=Yt:z.classList.add("persona-text-white");cr.borderWidth?(z.style.borderWidth=cr.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),cr.borderColor?z.style.borderColor=cr.borderColor:z.style.borderColor="",cr.paddingX?(z.style.paddingLeft=cr.paddingX,z.style.paddingRight=cr.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),cr.paddingY?(z.style.paddingTop=cr.paddingY,z.style.paddingBottom=cr.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let ir=Re==null?void 0:Re.querySelector(".persona-send-button-tooltip");if(io&&rn)if(ir)ir.textContent=rn,ir.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=rn,Re==null||Re.insertBefore(re,z)}else ir&&(ir.style.display="none");let Zt=(Cg=(yg=n.layout)==null?void 0:yg.contentMaxWidth)!=null?Cg:B()?(vg=(wg=(bg=n.launcher)==null?void 0:bg.composerBar)==null?void 0:wg.contentMaxWidth)!=null?vg:"720px":void 0;Zt?(ze.style.maxWidth=Zt,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%",Ae&&(Ae.style.maxWidth=Zt,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),Z&&(Z.style.maxWidth=Zt,Z.style.marginLeft="auto",Z.style.marginRight="auto")):(ze.style.maxWidth="",ze.style.marginLeft="",ze.style.marginRight="",ze.style.width="",Ae&&(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight=""),Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight=""));let pr=(Ag=n.statusIndicator)!=null?Ag:{},on=(Sg=pr.visible)!=null?Sg:!0;if(fe.style.display=on?"":"none",W){let re=W.getStatus();ut(fe,(rr=>{var At,Ut,Mr,$r;return rr==="idle"?(At=pr.idleText)!=null?At:Ur.idle:rr==="connecting"?(Ut=pr.connectingText)!=null?Ut:Ur.connecting:rr==="connected"?(Mr=pr.connectedText)!=null?Mr:Ur.connected:rr==="error"?($r=pr.errorText)!=null?$r:Ur.error:Ur[rr]})(re),pr,re)}fe.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=pr.align==="left"?"persona-text-left":pr.align==="center"?"persona-text-center":"persona-text-right";fe.classList.add(fn)},open(){P()&&Kt(!0,"api")},close(){P()&&Kt(!1,"api")},toggle(){P()&&Kt(!R,"api")},clearChat(){Se=!1,W.clearMessages(),Bn.clear(),Co();try{localStorage.removeItem(Ka),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ka}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ka)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},S.syncFromMetadata(),K==null||K.clear(),Te==null||Te.reset(),oe==null||oe.update()},setMessage(c){return!ge||W.isStreaming()?!1:(!R&&P()&&Kt(!0,"system"),ge.value=c,ge.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(W.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ge.value.trim();return g?(!R&&P()&&Kt(!0,"system"),ge.value="",ge.style.height="auto",W.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return W.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(W.isVoiceActive()||(!R&&P()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),W.toggleVoice().then(()=>{Lt.active=W.isVoiceActive(),An("user"),W.isVoiceActive()&&q()})),!0):un?!0:ps()?(!R&&P()&&Kt(!0,"system"),Lt.manuallyDeactivated=!1,tn(),Vo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?W.isVoiceActive()?(W.toggleVoice().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,tn(),An("user"),ie()}),!0):!1:un?(Lt.manuallyDeactivated=!0,tn(),Nn("user"),!0):!1},injectMessage(c){return!R&&P()&&Kt(!0,"system"),W.injectMessage(c)},injectAssistantMessage(c){!R&&P()&&Kt(!0,"system");let g=W.injectAssistantMessage(c);return O&&(O=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)),g},injectUserMessage(c){return!R&&P()&&Kt(!0,"system"),W.injectUserMessage(c)},injectSystemMessage(c){return!R&&P()&&Kt(!0,"system"),W.injectSystemMessage(c)},injectMessageBatch(c){return!R&&P()&&Kt(!0,"system"),W.injectMessageBatch(c)},injectComponentDirective(c){return!R&&P()&&Kt(!0,"system"),W.injectComponentDirective(c)},injectTestMessage(c){!R&&P()&&Kt(!0,"system"),W.injectTestEvent(c)},async connectStream(c,g){return W.connectStream(c,g)},__pushEventStreamEvent(c){K&&(Te==null||Te.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ve||!K||Lr()},hideEventStream(){xe&&Or()},isEventStreamVisible(){return xe},showArtifacts(){Ln(n)&&(Se=!1,ln(),ue==null||ue.setMobileOpen(!0))},hideArtifacts(){Ln(n)&&(Se=!0,ln())},upsertArtifact(c){return Ln(n)?(Se=!1,W.upsertArtifact(c)):null},selectArtifact(c){Ln(n)&&W.selectArtifact(c)},clearArtifacts(){Ln(n)&&W.clearArtifacts()},getArtifacts(){var c;return(c=W==null?void 0:W.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=W==null?void 0:W.getSelectedArtifactId())!=null?c:null},focusInput(){return k&&!R&&!B()||!ge?!1:(ge.focus(),!0)},async resolveApproval(c,g){let A=W.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===c});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${c}`);if(A.approval.toolType==="webmcp"){W.resolveWebMcpApproval(A.id,g);return}return W.resolveApproval(A.approval,g)},getMessages(){return W.getMessages()},getStatus(){return W.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return P()&&R},isVoiceActive(){return Lt.active},getState(){return{open:P()&&R,launcherEnabled:k,voiceActive:Lt.active,streaming:W.isStreaming()}},showCSATFeedback(c){!R&&P()&&Kt(!0,"system");let g=ze.querySelector(".persona-feedback-container");g&&g.remove();let b=Ql({onSubmit:async(A,D)=>{var $;W.isClientTokenMode()&&await W.submitCSATFeedback(A,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,A,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ze.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&P()&&Kt(!0,"system");let g=ze.querySelector(".persona-feedback-container");g&&g.remove();let b=Yl({onSubmit:async(A,D)=>{var $;W.isClientTokenMode()&&await W.submitNPSFeedback(A,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,A,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ze.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return W.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return W.submitNPSFeedback(c,g)},destroy(){Vn!=null&&(clearInterval(Vn),Vn=null),Pt.forEach(c=>c()),Ce.remove(),rt==null||rt.remove(),Fe==null||Fe.destroy(),dt==null||dt.remove(),cn&&Q.removeEventListener("click",cn)}};if((((Af=r==null?void 0:r.debugTools)!=null?Af:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:vr,getMessages:vr.getMessages,getStatus:vr.getStatus,getMetadata:vr.getPersistentMetadata,updateMetadata:vr.updatePersistentMetadata,clearHistory:()=>vr.clearChat(),setVoiceActive:b=>b?vr.startVoiceRecognition():vr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Pt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.focusInput()};if(window.addEventListener("persona:focusInput",g),Pt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ve){let j=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.showEventStream()},F=We=>{let we=We.detail;(!(we!=null&&we.instanceId)||we.instanceId===c)&&vr.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",F),Pt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",F)})}let b=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.showArtifacts()},A=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.hideArtifacts()},D=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&vr.upsertArtifact(F.artifact)},$=j=>{let F=j.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&vr.selectArtifact(F.id)},U=j=>{let F=j.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&vr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),Pt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Tn=uC(n.persistState);if(Tn&&P()){let c=fC(Tn.storage),g=`${Tn.keyPrefix}widget-open`,b=`${Tn.keyPrefix}widget-voice`,A=`${Tn.keyPrefix}widget-voice-mode`;if(c){let D=((Sf=Tn.persist)==null?void 0:Sf.openState)&&c.getItem(g)==="true",$=((Tf=Tn.persist)==null?void 0:Tf.voiceState)&&c.getItem(b)==="true",U=((Mf=Tn.persist)==null?void 0:Mf.voiceState)&&c.getItem(A)==="true";if(D&&setTimeout(()=>{vr.open(),setTimeout(()=>{var j;if($||U)vr.startVoiceRecognition();else if((j=Tn.persist)!=null&&j.focusInput){let F=t.querySelector("textarea");F&&F.focus()}},100)},0),(kf=Tn.persist)!=null&&kf.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Ef=Tn.persist)!=null&&Ef.voiceState&&(s.on("voice:state",j=>{c.setItem(b,j.active?"true":"false")}),s.on("user:message",j=>{c.setItem(A,j.viaVoice?"true":"false")})),Tn.clearOnChatClear){let j=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(A)},F=()=>j();window.addEventListener("persona:clear-chat",F),Pt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return p&&P()&&setTimeout(()=>{vr.open()},0),ao(),vr};var mC=(t,e)=>{let r=t.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,e*parseFloat(o[1])/100):420},ry=(t,e)=>{var n,o;let r=(o=(n=e==null?void 0:e.launcher)==null?void 0:n.enabled)!=null?o:!0;t.className="persona-host",t.style.height=r?"":"100%",t.style.display=r?"":"flex",t.style.flexDirection=r?"":"column",t.style.flex=r?"":"1 1 auto",t.style.minHeight=r?"":"0"},gu=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},ny=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.minWidth="",gu(t)},uu=t=>{t.style.transition=""},fu=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform=""},mu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},td=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},gC=(t,e,r,n,o)=>{o?r.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(r,n),t.appendChild(e)):r.parentElement===e&&(e.replaceChildren(),t.appendChild(r),t.appendChild(n))},hC=(t,e,r,n,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==n&&a.replaceChildren(n,r):a.lastElementChild!==n&&a.replaceChildren(r,n)},oy=(t,e,r,n,o,s,a)=>{var x,C,S,k,T,M;let i=kn(s),d=i.reveal==="push";gC(t,e,r,n,d),hC(t,e,r,n,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=t.ownerDocument.defaultView,p=(C=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,m=(k=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?k:640,u=l!=null?l.innerWidth<=m:!1;if(p&&u&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),fu(e),uu(n),ny(n),mu(r),td(o,n),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((M=(T=s==null?void 0:s.launcher)==null?void 0:T.zIndex)!=null?M:qr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),ny(n),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",fu(e),uu(n),mu(r),td(o,n);let h=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",y=a?"translateX(0)":w;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=h,n.style.transform=y,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",uu(n),gu(n),td(o,n);let h=mC(i.width,t.clientWidth),w=Math.max(0,t.clientWidth),y=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${h}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${h}px)`;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${w+h}px`,e.style.transition=y,e.style.transform=E,r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",fu(e),gu(n),mu(r),td(o,n);let h=i.reveal==="emerge";h?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let w=a?i.width:"0px",y=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${w}`,n.style.width=w,n.style.maxWidth=w,n.style.minWidth=w,n.style.minHeight="0",n.style.position="relative",n.style.overflow=h||E?"hidden":"visible",n.style.transition=y,h&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},xC=(t,e)=>{let r=t.ownerDocument.createElement("div");return ry(r,e),t.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){ry(r,n)},destroy(){r.remove()}}},yC=(t,e)=>{var T,M,h,w;let{ownerDocument:r}=t,n=t.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=t.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=r.createElement("div"),i=r.createElement("div"),d=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),m=(M=(T=e==null?void 0:e.launcher)==null?void 0:T.enabled)==null||M?(w=(h=e==null?void 0:e.launcher)==null?void 0:h.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),n.insertBefore(a,t),d.appendChild(t);let u=null,f=()=>{u==null||u.disconnect(),u=null},x=()=>{f(),kn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{oy(a,i,d,l,p,e,m)}),u.observe(a))},C=()=>{oy(a,i,d,l,p,e,m),x()},S=a.ownerDocument.defaultView,k=()=>{C()};return S==null||S.addEventListener("resize",k),kn(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:p,shell:a,syncWidgetState(y){let E=y.launcherEnabled?y.open:!0;m!==E&&(m=E,C())},updateConfig(y){var E,B;e=y,((B=(E=e==null?void 0:e.launcher)==null?void 0:E.enabled)!=null?B:!0)===!1&&(m=!0),C()},destroy(){S==null||S.removeEventListener("resize",k),f(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(t,s):n.appendChild(t)),a.remove()}}},ti=(t,e)=>Ar(e)?yC(t,e):xC(t,e);var hu={},ay=!1,bC=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let e=document.querySelector(t);if(!e)throw new Error(`Chat widget target "${t}" was not found`);return e}return t},wC=()=>{try{if(typeof hu!="undefined"&&hu.url)return new URL("../widget.css",hu.url).href}catch{}return null},sy=(t,e)=>{let r=wC(),n=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let o=e.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);t.insertBefore(s,t.firstChild)};if(t instanceof ShadowRoot)if(r){let o=e.createElement("link");o.rel="stylesheet",o.href=r,o.setAttribute("data-persona","true"),t.insertBefore(o,t.firstChild)}else n();else if(!e.head.querySelector("link[data-persona]")&&r){let s=e.createElement("link");s.rel="stylesheet",s.href=r,s.setAttribute("data-persona","true"),e.head.appendChild(s)}},iy=t=>{let e=bC(t.target),r=t.useShadowDom===!0,n=e.ownerDocument,o=t.config,s=ti(e,o),a,i=[],d=(S,k)=>{var w,y;let M=!((y=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?y:!0)||Ar(k),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),M&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),r){let E=S.attachShadow({mode:"open"});E.appendChild(h),sy(E,n)}else S.appendChild(h),sy(S,n);return e.id&&h.setAttribute("data-persona-instance",e.id),h},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let S=d(s.host,o);a=ed(S,o,{debugTools:t.debugTools}),p()},u=()=>{i.forEach(S=>S()),i=[],a.destroy()};m(),t.onChatReady?t.onChatReady():t.onReady&&(ay||(ay=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),t.onReady());let f=S=>{u(),s.destroy(),s=ti(e,S),o=S,m()},x={update(S){var y,E,B,P,R,O;let k={...o,...S,launcher:{...(y=o==null?void 0:o.launcher)!=null?y:{},...(E=S==null?void 0:S.launcher)!=null?E:{},dock:{...(P=(B=o==null?void 0:o.launcher)==null?void 0:B.dock)!=null?P:{},...(O=(R=S==null?void 0:S.launcher)==null?void 0:R.dock)!=null?O:{}}}},T=Ar(o),M=Ar(k),h=Ho(o),w=Ho(k);if(T!==M||h!==w){f(k);return}o=k,s.updateConfig(o),a.update(S),l()},destroy(){u(),s.destroy(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}},C=new Proxy(x,{get(S,k,T){if(k==="host")return s.host;if(k in S)return Reflect.get(S,k,T);let M=a[k];return typeof M=="function"?M.bind(a):M}});return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=C),C};var uy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),vC=new Set(["button","a","input","select","textarea","details","summary"]),CC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xu=/\b(product|card|item|listing|result)\b/i,bu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,AC=3e3,SC=100;function fy(t){let e=typeof t.className=="string"?t.className:"";if(xu.test(e)||t.id&&xu.test(t.id))return!0;for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];if(n.name.startsWith("data-")&&xu.test(n.value))return!0}return!1}function my(t){var e;return bu.test(((e=t.textContent)!=null?e:"").trim())}function gy(t){var r;let e=t.querySelectorAll("a[href]");for(let n=0;n<e.length;n++){let o=(r=e[n].getAttribute("href"))!=null?r:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function TC(t){return!!t.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ly(t){let e=t.match(bu);return e?e[0]:null}function dy(t){var n,o,s;let e=(n=t.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:t.querySelector("a[href]");if(e&&((o=e.textContent)!=null&&o.trim())){let a=e.getAttribute("href");return{title:e.textContent.trim(),href:a&&a!=="#"?a:null}}let r=t.querySelector("h1, h2, h3, h4, h5, h6");return(s=r==null?void 0:r.textContent)!=null&&s.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function MC(t){let e=[],r=n=>{let o=n.trim();o&&!e.includes(o)&&e.push(o)};return t.querySelectorAll("button").forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('[role="button"]').forEach(n=>{var o;return r((o=n.textContent)!=null?o:"")}),t.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;r((o=n.value)!=null?o:"")}),e.slice(0,6)}var kC="commerce-card",EC="result-card";function cy(t){return!fy(t)||!my(t)||!gy(t)&&!TC(t)?0:5200}function py(t){var n;return!fy(t)||my(t)||!gy(t)||((n=t.textContent)!=null?n:"").trim().length<20||!(!!t.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!t.querySelector(".snippet, .description, p"))?0:2800}var wu=[{id:kC,scoreElement(t){return cy(t)},shouldSuppressDescendant(t,e,r){if(e===t||!t.contains(e))return!1;if(r.interactivity==="static"){let n=r.text.trim();return!!(n.length===0||bu.test(n)&&n.length<32)}return!0},formatSummary(t,e){var d,l,p;if(cy(t)===0)return null;let{title:r,href:n}=dy(t),o=(p=(l=ly(((d=t.textContent)!=null?d:"").trim()))!=null?l:ly(e.text))!=null?p:"",s=MC(t);return[n&&r?`[${r}](${n})${o?` \u2014 ${o}`:""}`:r?`${r}${o?` \u2014 ${o}`:""}`:o||e.text.trim().slice(0,120),`selector: ${e.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
158
- `)}},{id:EC,scoreElement(t){return py(t)},formatSummary(t,e){if(py(t)===0)return null;let{title:r,href:n}=dy(t);return[n&&r?`[${r}](${n})`:r||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
159
- `)}}];function LC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function PC(t){var p,m,u,f,x,C,S,k,T,M,h,w,y;let e=(p=t.options)!=null?p:{},r=(u=(m=e.maxElements)!=null?m:t.maxElements)!=null?u:80,n=(x=(f=e.excludeSelector)!=null?f:t.excludeSelector)!=null?x:".persona-host",o=(S=(C=e.maxTextLength)!=null?C:t.maxTextLength)!=null?S:200,s=(T=(k=e.visibleOnly)!=null?k:t.visibleOnly)!=null?T:!0,a=(M=e.root)!=null?M:t.root,i=(h=e.mode)!=null?h:"structured",d=(w=e.maxCandidates)!=null?w:Math.max(500,r*10),l=(y=t.rules)!=null?y:wu;return i==="simple"&&t.rules&&t.rules.length>0?(LC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function yu(t){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/([^\w-])/g,"\\$1")}var IC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function RC(t){let e=t.tagName.toLowerCase(),r=t.getAttribute("role");return e==="a"&&t.hasAttribute("href")?"navigable":e==="input"||e==="select"||e==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":e==="button"||r==="button"||vC.has(e)||r&&CC.has(r)||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||t.getAttribute("contenteditable")==="true"?"clickable":"static"}function hy(t){if(t.hidden)return!1;try{let e=getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden")return!1}catch{}return!(t.style.display==="none"||t.style.visibility==="hidden")}function WC(t){let e={},r=t.id;r&&(e.id=r);let n=t.getAttribute("href");n&&(e.href=n);let o=t.getAttribute("aria-label");o&&(e["aria-label"]=o);let s=t.getAttribute("type");s&&(e.type=s);let a=t.getAttribute("value");a&&(e.value=a);let i=t.getAttribute("name");i&&(e.name=i);let d=t.getAttribute("role");d&&(e.role=d);for(let l=0;l<t.attributes.length;l++){let p=t.attributes[l];p.name.startsWith("data-")&&(e[p.name]=p.value)}return e}function vu(t){let e=t.tagName.toLowerCase();if(t.id){let o=`#${yu(t.id)}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of IC){let s=t.getAttribute(o);if(s){let a=`${e}[${o}="${yu(s)}"]`;try{if(t.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let r=Array.from(t.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${e}.${r.map(a=>yu(a)).join(".")}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=t.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${e}`)).indexOf(t);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(t.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=t.parentElement;if(n){let s=Array.from(n.querySelectorAll(`:scope > ${e}`)).indexOf(t);if(s>=0)return`${e}:nth-of-type(${s+1})`}return e}function BC(t){return t==="static"?SC:AC}function xy(t,e){var o;let r=t.tagName.toLowerCase(),n=((o=t.textContent)!=null?o:"").trim().substring(0,e);return{selector:vu(t),tagName:r,text:n,role:t.getAttribute("role"),interactivity:RC(t),attributes:WC(t)}}function HC(t,e,r,n){let o=BC(e.interactivity),s=null;for(let a of r){let i=a.scoreElement(t,e,n);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function DC(t,e){var r;for(let n of t)if(e.el!==n.el&&(r=n.formattingRule)!=null&&r.shouldSuppressDescendant&&n.el.contains(e.el)&&n.formattingRule.shouldSuppressDescendant(n.el,e.el,e.enriched))return!0;return!1}function OC(t,e){let r={doc:e.ownerDocument,maxTextLength:t.maxTextLength},n=new Set,o=[],s=0,a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<t.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(uy.has(p)){i=a.nextNode();continue}if(t.excludeSelector)try{if(l.closest(t.excludeSelector)){i=a.nextNode();continue}}catch{}if(t.visibleOnly&&!hy(l)){i=a.nextNode();continue}let m=xy(l,t.maxTextLength),u=m.text.length>0,f=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(S=>S==="role");if(!u&&!f){i=a.nextNode();continue}if(n.has(m.selector)){i=a.nextNode();continue}n.add(m.selector);let{score:x,formattingRule:C}=HC(l,m,t.rules,r);o.push({el:l,domIndex:s,enriched:m,score:x,formattingRule:C}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return m!==u?m-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=t.maxElements)break;DC(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return m!==u?m-u:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var u;let p;if((u=l.formattingRule)!=null&&u.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,r);f&&(p=f)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function NC(t,e){let r=[],n=new Set,o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&r.length<t.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(uy.has(l)){s=o.nextNode();continue}if(t.excludeSelector)try{if(d.closest(t.excludeSelector)){s=o.nextNode();continue}}catch{}if(t.visibleOnly&&!hy(d)){s=o.nextNode();continue}let p=xy(d,t.maxTextLength),m=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!m&&!u){s=o.nextNode();continue}n.has(p.selector)||(n.add(p.selector),r.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of r)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,t.maxElements)}function yy(t={}){var n;let e=PC(t),r=(n=e.root)!=null?n:document.body;return r?e.mode==="simple"?NC(e,r):OC(e,r):[]}var rd=100;function by(t,e={}){var s;if(t.length===0)return"No page elements found.";let r=(s=e.mode)!=null?s:"structured",n=[];if(r==="structured"){let a=t.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
157
+ `}if(!A&&!c){let Mt="max-height: -moz-available !important; max-height: stretch !important;",Bt=g?"":"padding-top: 1.25em !important;",kt=g?"":`z-index: ${(Pr=(Zr=n.launcher)==null?void 0:Zr.zIndex)!=null?Pr:Qr} !important;`;Re.style.cssText+=Mt+Bt+kt}dt()};Un(),zo(t,n),td(t,n),rd(t,n);let Ht=[];Ht.push(()=>{document.removeEventListener("keydown",Po)});let Ar=null,Sr=null;Ht.push(()=>{Ar==null||Ar(),Ar=null,Sr==null||Sr(),Sr=null}),Vt&&Ht.push(()=>{Vt==null||Vt.disconnect(),Vt=null}),Ht.push(()=>{Yr==null||Yr(),Yr=null,uo(),Qt&&(Qt.remove(),Qt=null),st==null||st.element.style.removeProperty("width"),st==null||st.element.style.removeProperty("maxWidth")}),Ne&&Ht.push(()=>{Le!==null&&(cancelAnimationFrame(Le),Le=null),X==null||X.destroy(),X=null,we==null||we.destroy(),we=null,ne=null});let hn=null,Wo=()=>{hn&&(hn(),hn=null),n.colorScheme==="auto"&&(hn=Ll(()=>{zo(t,n)}))};Wo(),Ht.push(()=>{hn&&(hn(),hn=null)});let Me=($f=n.features)==null?void 0:$f.streamAnimation;if(Me!=null&&Me.type&&Me.type!=="none"){let c=ei(Me.type,Me.plugins);c&&(eu(c,t),Ht.push(()=>Ux(t)))}let Pn=hy(wt),In=null,q,Yn=!1,fo=Wx(),mo=new Map,Zn=new Map,qn=new Map,ps=0,xn=Rl(),yn=0,zn=null,Vn=!1,Zo=!1,go=0,Gr=null,eo=null,La=!1,ea=!1,Pa=null,gi=4,Ia=24,hi=80,Ra=new Map,Ot={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},us=(qf=(Uf=n.voiceRecognition)==null?void 0:Uf.autoResume)!=null?qf:!1,Rn=c=>{s.emit("voice:state",{active:Ot.active,source:c,timestamp:Date.now()})},dn=()=>{m(c=>({...c,voiceState:{active:Ot.active,timestamp:Date.now(),manuallyDeactivated:Ot.manuallyDeactivated}}))},xi=()=>{var A,H;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=Tu(d.voiceState),g=!!c.active,b=Number((H=c.timestamp)!=null?H:0);Ot.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<QC&&setTimeout(()=>{var F,$;Ot.active||(Ot.manuallyDeactivated=!1,(($=(F=n.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?q.toggleVoice().then(()=>{Ot.active=q.isVoiceActive(),Rn("restore"),q.isVoiceActive()&&Ts()}):Or("restore"))},1e3)},yi=()=>q?By(q.getMessages()).filter(c=>!c.__skipPersist):[];function Wa(c){if(!(i!=null&&i.save))return;let b={messages:c?By(c):q?yi():[],metadata:d,artifacts:or.artifacts,selectedArtifactId:or.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 ho=null,fs=()=>Re.querySelector("#persona-scroll-container")||he,Ho=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),Vn=!1},ms=()=>{zn!==null&&(cancelAnimationFrame(zn),zn=null),Zo=!1,Ho()},gs=()=>{go>0?(pr.textContent=String(go),pr.style.display="",it.setAttribute("aria-label",`${xt()||"Jump to latest"} (${go} new)`)):(pr.textContent="",pr.style.display="none",it.setAttribute("aria-label",xt()||"Jump to latest"))},hs=()=>{go!==0&&(go=0,gs())},xs=()=>yt()==="follow"?!xn.isFollowing():!Ca(he,Ia),cn=()=>{if(!Dr()||fe){it.parentNode&&it.remove(),it.style.display="none";return}it.parentNode!==G&&G.appendChild(it),Er();let g=To(he)>0&&xs();g||hs(),it.style.display=g?"":"none"},Ha=()=>{xn.pause()&&(ms(),cn())},to=()=>{xn.resume(),hs(),cn()},ro=(c=!1)=>{yt()==="follow"&&xn.isFollowing()&&(!c&&!Yn||(zn!==null&&(cancelAnimationFrame(zn),zn=null),Zo=!0,zn=requestAnimationFrame(()=>{zn=null,Zo=!1,xn.isFollowing()&&bi(fs(),c?220:140)})))},ys=(c,g,b,A=()=>!0)=>{let H=c.scrollTop,F=g(),$=F-H;Ho();let V=performance.now();Vn=!0;let _=ve=>1-Math.pow(1-ve,3),ke=ve=>{if(!A()){Ho();return}let de=g();de!==F&&(F=de,$=F-H);let Pe=ve-V,Ye=Math.min(Pe/b,1),Ee=_(Ye),gt=H+$*Ee;c.scrollTop=gt,yn=c.scrollTop,Ye<1?ho=requestAnimationFrame(ke):(c.scrollTop=F,yn=c.scrollTop,ho=null,Vn=!1)};ho=requestAnimationFrame(ke)},bi=(c,g=500)=>{let b=To(c)-c.scrollTop;if(Math.abs(b)<1){yn=c.scrollTop;return}if(Math.abs(b)>=hi){Ho(),Vn=!0,c.scrollTop=To(c),yn=c.scrollTop,Vn=!1;return}ys(c,()=>To(c),g,()=>xn.isFollowing())},bs=()=>{let c=fs();Vn=!0,c.scrollTop=To(c),yn=c.scrollTop,Vn=!1,cn()},ws=c=>{xr.style.height=`${Math.max(0,Math.round(c))}px`,Gr&&(Gr.spacerHeight=Math.max(0,c))},ta=()=>{eo!==null&&(cancelAnimationFrame(eo),eo=null),Ho(),Gr=null,xr.style.height="0px"},wi=c=>{eo!==null&&cancelAnimationFrame(eo),eo=requestAnimationFrame(()=>{var ke;eo=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=he.querySelector(`[data-message-id="${g}"]`);if(!b)return;let A=0,H=b;for(;H&&H!==he;)A+=H.offsetTop,H=H.offsetParent;let F=(ke=Gr==null?void 0:Gr.spacerHeight)!=null?ke:0,$=he.scrollHeight-F,{targetScrollTop:V,spacerHeight:_}=Nx({anchorOffsetTop:A,topOffset:Dt(),viewportHeight:he.clientHeight,contentHeight:$});Gr={initialSpacerHeight:_,contentHeightAtAnchor:$,spacerHeight:_},ws(_),ys(he,()=>V,220)})},vi=()=>{if(yt()==="follow"){if(!xn.isFollowing()||Ca(he,1))return;ro(!Yn);return}if(Gr&&Gr.initialSpacerHeight>0){let c=he.scrollHeight-Gr.spacerHeight,g=_x({initialSpacerHeight:Gr.initialSpacerHeight,contentHeightAtAnchor:Gr.contentHeightAtAnchor,currentContentHeight:c});g!==Gr.spacerHeight&&ws(g)}cn()},Ci=c=>{let g=yt();g==="follow"?(to(),ro(!0)):g==="anchor-top"&&wi(c)},Ai=c=>{let g=new Map;c.forEach(b=>{let A=Ra.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!A&&b.role==="assistant"&&(s.emit("assistant:message",b),!ea&&yt()!=="anchor-top"&&xs()&&(go+=1,gs(),cn())),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}))}),Ra.clear(),g.forEach((b,A)=>{Ra.set(A,b)})},ra=(c,g,b)=>{var Tt,Ue,_e,tt,dt,Nt;let A=document.createElement("div"),F=(()=>{var Ve;let O=o.find(Ke=>Ke.renderLoadingIndicator);if(O!=null&&O.renderLoadingIndicator)return O.renderLoadingIndicator;if((Ve=n.loadingIndicator)!=null&&Ve.render)return n.loadingIndicator.render})(),$=(O,Ve)=>Ve==null?!1:typeof Ve=="string"?(O.textContent=Ve,!0):(O.appendChild(Ve),!0),V=new Set,_=new Set,ke=o.some(O=>O.renderAskUserQuestion),ve=[],de=[],Pe=n.enableComponentStreaming!==!1,Ye=o.some(O=>O.renderApproval)&&n.approval!==!1,Ee=[];if(g.forEach(O=>{var ct,jt,Rr,Bn,wn,na,oa,_a,Fa,yr,aa,$o,Uo,yo;V.add(O.id);let Ve=ke&&ko(O),Ke=Ye&&O.variant==="approval"&&!!O.approval,Ae=!Ve&&O.role==="assistant"&&!O.variant&&Pe&&sd(O);if(!Ke&&qn.has(O.id)){let bt=c.querySelector(`#wrapper-${O.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),qn.delete(O.id)}if(!Ae&&Zn.has(O.id)){let bt=c.querySelector(`#wrapper-${O.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),Zn.delete(O.id)}let nr=ko(O)?`:${(ct=O.agentMetadata)!=null&&ct.askUserQuestionAnswered?"a":"u"}:${(jt=O.agentMetadata)!=null&&jt.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Zt=Rx(O,ps)+nr,mr=Ve||Ke||Ae?null:Hx(fo,O.id,Zt);if(mr){A.appendChild(mr.cloneNode(!0)),ko(O)&&((Rr=O.toolCall)!=null&&Rr.id)&&((Bn=O.agentMetadata)==null?void 0:Bn.awaitingLocalTool)===!0&&!((wn=O.agentMetadata)!=null&&wn.askUserQuestionAnswered)&&(_.add(O.toolCall.id),ss(O,n,He.composerOverlay));return}let Ft=null,ur=o.find(bt=>!!(O.variant==="reasoning"&&bt.renderReasoning||O.variant==="tool"&&bt.renderToolCall||!O.variant&&bt.renderMessage)),bn=(na=n.layout)==null?void 0:na.messages;if(ko(O)&&((oa=O.agentMetadata)==null?void 0:oa.askUserQuestionAnswered)===!0){mo.delete(O.id);let bt=c.querySelector(`#wrapper-${O.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if(ko(O)&&((Fa=(_a=n.features)==null?void 0:_a.askUserQuestion)==null?void 0:Fa.enabled)!==!1){let bt=o.find($r=>typeof $r.renderAskUserQuestion=="function");if(bt&&Pt.current){let $r=mo.get(O.id),Zr=$r!==Zt,Pr=null;if(Zr){let{payload:kt,complete:pn}=Eo(O),Wr=O.id,no=()=>{var Hr;return(Hr=Pt.current)==null?void 0:Hr.getMessages().find(en=>en.id===Wr)};Pr=bt.renderAskUserQuestion({message:O,payload:kt,complete:pn,resolve:Hr=>{var Dn;let en=no();en&&((Dn=Pt.current)==null||Dn.resolveAskUserQuestion(en,Hr))},dismiss:()=>{var en,Dn,sa;let Hr=no();(en=Hr==null?void 0:Hr.agentMetadata)!=null&&en.awaitingLocalTool&&((Dn=Pt.current)==null||Dn.markAskUserQuestionResolved(Hr),(sa=Pt.current)==null||sa.resolveAskUserQuestion(Hr,"(dismissed)"))},config:n})}let Mt=$r!=null;if(Zr&&Pr===null&&!Mt){((yr=O.agentMetadata)==null?void 0:yr.awaitingLocalTool)===!0&&!((aa=O.agentMetadata)!=null&&aa.askUserQuestionAnswered)&&(_.add(O.toolCall.id),ss(O,n,He.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${O.id}`,Bt.setAttribute("data-wrapper-id",O.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),A.appendChild(Bt),ve.push({messageId:O.id,fingerprint:Zt,bubble:Pr});return}else{(($o=O.agentMetadata)==null?void 0:$o.awaitingLocalTool)===!0&&!((Uo=O.agentMetadata)!=null&&Uo.askUserQuestionAnswered)&&(_.add(O.toolCall.id),ss(O,n,He.composerOverlay));return}}else if(Ke){let bt=o.find(Mt=>typeof Mt.renderApproval=="function"),Zr=qn.get(O.id)!==Zt,Pr=null;if(Zr&&(bt!=null&&bt.renderApproval)){let Mt=O.id,Bt=(kt,pn)=>{var no,Hr,en;let Wr=(no=Pt.current)==null?void 0:no.getMessages().find(Dn=>Dn.id===Mt);Wr!=null&&Wr.approval&&(Wr.approval.toolType==="webmcp"?(Hr=Pt.current)==null||Hr.resolveWebMcpApproval(Wr.id,kt):(en=Pt.current)==null||en.resolveApproval(Wr.approval,kt,pn))};Pr=bt.renderApproval({message:O,defaultRenderer:()=>Zl(O,n),config:n,approve:kt=>Bt("approved",kt),deny:kt=>Bt("denied",kt)})}if(Zr&&Pr===null){let Mt=c.querySelector(`#wrapper-${O.id}`);Mt==null||Mt.removeAttribute("data-preserve-runtime"),qn.delete(O.id),Ft=Zl(O,n)}else{let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-${O.id}`,Mt.setAttribute("data-wrapper-id",O.id),Mt.setAttribute("data-approval-plugin-stub","true"),Mt.setAttribute("data-preserve-runtime","true"),A.appendChild(Mt),Ee.push({messageId:O.id,fingerprint:Zt,bubble:Pr});return}}else if(ur)if(O.variant==="reasoning"&&O.reasoning&&ur.renderReasoning){if(!Ze)return;Ft=ur.renderReasoning({message:O,defaultRenderer:()=>cu(O,n),config:n})}else if(O.variant==="tool"&&O.toolCall&&ur.renderToolCall){if(!Se)return;Ft=ur.renderToolCall({message:O,defaultRenderer:()=>pu(O,n),config:n})}else ur.renderMessage&&(Ft=ur.renderMessage({message:O,defaultRenderer:()=>{let bt=ts(O,b,bn,n.messageActions,te,{loadingIndicatorRenderer:F,widgetConfig:n});return O.role!=="user"&&Cu(bt,O,n,q),bt},config:n}));if(!Ft&&Ae){let bt=id(O);if(bt){let $r=Zn.get(O.id),Zr=$r!==Zt,Pr=n.wrapComponentDirectiveInBubble!==!1,Mt=null;if(Zr){let Bt=ad(bt,{config:n,message:O,transform:b});if(Bt)if(Pr){let kt=document.createElement("div");if(kt.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(" "),kt.id=`bubble-${O.id}`,kt.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=b({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),kt.appendChild(pn)}kt.appendChild(Bt),Mt=kt}else{let kt=document.createElement("div");if(kt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",kt.id=`bubble-${O.id}`,kt.setAttribute("data-message-id",O.id),kt.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=b({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),kt.appendChild(pn)}kt.appendChild(Bt),Mt=kt}}if(Mt||$r!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${O.id}`,Bt.setAttribute("data-wrapper-id",O.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),Pr||Bt.classList.add("persona-w-full"),A.appendChild(Bt),de.push({messageId:O.id,fingerprint:Zt,bubble:Mt});return}}}if(!Ft)if(O.variant==="reasoning"&&O.reasoning){if(!Ze)return;Ft=cu(O,n)}else if(O.variant==="tool"&&O.toolCall){if(!Se)return;Ft=pu(O,n)}else if(O.variant==="approval"&&O.approval){if(n.approval===!1)return;Ft=Zl(O,n)}else{let bt=(yo=n.layout)==null?void 0:yo.messages;bt!=null&&bt.renderUserMessage&&O.role==="user"?Ft=bt.renderUserMessage({message:O,config:n,streaming:!!O.streaming}):bt!=null&&bt.renderAssistantMessage&&O.role==="assistant"?Ft=bt.renderAssistantMessage({message:O,config:n,streaming:!!O.streaming}):Ft=ts(O,b,bt,n.messageActions,te,{loadingIndicatorRenderer:F,widgetConfig:n}),O.role!=="user"&&Ft&&Cu(Ft,O,n,q)}let Lr=document.createElement("div");Lr.className="persona-flex",Lr.id=`wrapper-${O.id}`,Lr.setAttribute("data-wrapper-id",O.id),O.role==="user"&&Lr.classList.add("persona-justify-end"),(Ft==null?void 0:Ft.getAttribute("data-persona-component-directive"))==="true"&&Lr.classList.add("persona-w-full"),Lr.appendChild(Ft),Bx(fo,O.id,Zt,Lr),A.appendChild(Lr)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ve=>{let Ke=Ve.getAttribute("data-persona-ask-sheet-for");Ke&&!_.has(Ke)&&Qo(He.composerOverlay,Ke)}),(Ue=(Tt=n.features)==null?void 0:Tt.toolCallDisplay)!=null&&Ue.grouped){let O=[],Ve=[];g.forEach(Ke=>{if(Ke.variant==="tool"&&Ke.toolCall&&Se){Ve.push(Ke);return}Ve.length>1&&O.push(Ve),Ve=[]}),Ve.length>1&&O.push(Ve),O.forEach((Ke,Ae)=>{var ct,jt;let nr=Ke.map(Rr=>Array.from(A.children).find(Bn=>Bn instanceof HTMLElement&&Bn.getAttribute("data-wrapper-id")===Rr.id)).filter(Rr=>!!Rr);if(nr.length<2)return;let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-tool-group-${Ae}-${Ke[0].id}`,Zt.setAttribute("data-wrapper-id",`tool-group-${Ae}-${Ke[0].id}`);let mr=document.createElement("div");mr.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",mr.setAttribute("data-persona-tool-group","true");let Ft=document.createElement("div");Ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ur=`Called ${Ke.length} tools`,bn=(jt=(ct=n.toolCall)==null?void 0:ct.renderGroupedSummary)==null?void 0:jt.call(ct,{messages:Ke,toolCalls:Ke.map(Rr=>Rr.toolCall).filter(Rr=>!!Rr),defaultSummary:ur,config:n});$(Ft,bn)||(Ft.textContent=ur);let Lr=document.createElement("div");Lr.className="persona-tool-group-stack persona-flex persona-flex-col",mr.append(Ft,Lr),Zt.appendChild(mr),nr[0].before(Zt),nr.forEach((Rr,Bn)=>{let wn=document.createElement("div");wn.className="persona-tool-group-item persona-relative",wn.setAttribute("data-persona-tool-group-item","true"),Bn<nr.length-1&&wn.setAttribute("data-persona-tool-group-connector","true"),wn.appendChild(Rr),Lr.appendChild(wn)})})}Dx(fo,V);let gt=g.some(O=>O.role==="assistant"&&O.streaming),nt=g[g.length-1],St=(nt==null?void 0:nt.role)==="assistant"&&!nt.streaming&&nt.variant!=="approval";if(Yn&&g.some(O=>O.role==="user")&&!gt&&!St){let O={config:n,streaming:!0,location:"standalone",defaultRenderer:Ta},Ve=o.find(Ae=>Ae.renderLoadingIndicator),Ke=null;if(Ve!=null&&Ve.renderLoadingIndicator&&(Ke=Ve.renderLoadingIndicator(O)),Ke===null&&((_e=n.loadingIndicator)!=null&&_e.render)&&(Ke=n.loadingIndicator.render(O)),Ke===null&&(Ke=Ta()),Ke){let Ae=document.createElement("div"),nr=((tt=n.loadingIndicator)==null?void 0:tt.showBubble)!==!1;Ae.className=nr?["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(" "),Ae.setAttribute("data-typing-indicator","true"),Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ae.appendChild(Ke);let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id="wrapper-typing-indicator",Zt.setAttribute("data-wrapper-id","typing-indicator"),Zt.appendChild(Ae),A.appendChild(Zt)}}if(!Yn&&g.length>0){let O=g[g.length-1],Ve={config:n,lastMessage:O,messageCount:g.length},Ke=o.find(nr=>nr.renderIdleIndicator),Ae=null;if(Ke!=null&&Ke.renderIdleIndicator&&(Ae=Ke.renderIdleIndicator(Ve)),Ae===null&&((dt=n.loadingIndicator)!=null&&dt.renderIdle)&&(Ae=n.loadingIndicator.renderIdle(Ve)),Ae){let nr=document.createElement("div"),Zt=((Nt=n.loadingIndicator)==null?void 0:Nt.showBubble)!==!1;nr.className=Zt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),nr.setAttribute("data-idle-indicator","true"),nr.appendChild(Ae);let mr=document.createElement("div");mr.className="persona-flex",mr.id="wrapper-idle-indicator",mr.setAttribute("data-wrapper-id","idle-indicator"),mr.appendChild(nr),A.appendChild(mr)}}if(Pl(c,A),ve.length>0)for(let{messageId:O,fingerprint:Ve,bubble:Ke}of ve){let Ae=c.querySelector(`#wrapper-${O}`);Ae&&Ke!==null&&(Ae.replaceChildren(Ke),Ae.setAttribute("data-bubble-fp",Ve),mo.set(O,Ve))}if(mo.size>0)for(let O of mo.keys())V.has(O)||mo.delete(O);if(de.length>0)for(let{messageId:O,fingerprint:Ve,bubble:Ke}of de){let Ae=c.querySelector(`#wrapper-${O}`);Ae&&Ke!==null&&(Ae.replaceChildren(Ke),Ae.setAttribute("data-bubble-fp",Ve),Zn.set(O,Ve))}if(Zn.size>0)for(let O of Zn.keys())V.has(O)||Zn.delete(O);if(Ee.length>0)for(let{messageId:O,fingerprint:Ve,bubble:Ke}of Ee){let Ae=c.querySelector(`#wrapper-${O}`);Ae&&Ke!==null&&(Ae.replaceChildren(Ke),Ae.setAttribute("data-bubble-fp",Ve),qn.set(O,Ve))}if(qn.size>0)for(let O of qn.keys())V.has(O)||qn.delete(O)},Bo=null,Si=()=>{var b;if(Bo)return;let c=A=>{let H=A.composedPath();H.includes(Re)||ot&&H.includes(ot)||Yt(!1,"user")};Bo=c,((b=t.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},vs=()=>{var g;if(!Bo)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Bo,!0),Bo=null};Ht.push(()=>vs());let Do=null,Ti=()=>{var b;if(Do)return;let c=A=>{A.key==="Escape"&&(A.isComposing||Yt(!1,"user"))};Do=c,((b=t.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Cs=()=>{var g;if(!Do)return;((g=t.ownerDocument)!=null?g:document).removeEventListener("keydown",Do,!0),Do=null};Ht.push(()=>Cs());let Oo=!1,As=new Set,Mi=()=>{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)},xo=()=>{var St,Tt,Ue,_e;if(!W())return;let c=He.peekBanner,g=He.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(St=q==null?void 0:q.getMessages())!=null?St:[],A;for(let tt=b.length-1;tt>=0;tt--){let dt=b[tt];if(dt.role==="assistant"&&dt.content){A=dt;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let H=A.content,F=!!A.streaming,$=Mi(),V=Bl($),_=V.type!=="none"?ei(V.type,$==null?void 0:$.plugins):null,ke=((Tt=_==null?void 0:_.isAnimating)==null?void 0:Tt.call(_,A))===!0,ve=_!==null&&(F||ke);ve&&_&&!As.has(_.name)&&(eu(_,t),As.add(_.name));let de=ve&&(_!=null&&_.containerClass)?_.containerClass:null,Pe=(Ue=g.dataset.personaPeekStreamClass)!=null?Ue:null;Pe&&Pe!==de&&(g.classList.remove(Pe),delete g.dataset.personaPeekStreamClass),de&&Pe!==de&&(g.classList.add(de),g.dataset.personaPeekStreamClass=de),ve?(g.style.setProperty("--persona-stream-step",`${V.speed}ms`),g.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ye=ve?Dl(H,V.buffer,_,A,F):H;if(ve&&V.placeholder==="skeleton"&&F&&(!Ye||!Ye.trim())){let tt=document.createElement("div"),dt=ri();dt.classList.add("persona-pill-peek__skeleton"),tt.appendChild(dt),Pl(g,tt)}else{let tt=Math.max(0,Ye.length-100),dt=Ye.length>100?Ye.slice(-100):Ye,Nt=ga(dt);if(!ve||!_){let O=Ye.length>100?`\u2026${dt}`:dt;g.textContent!==O&&(g.textContent=O)}else{let O=Nt;(_.wrap==="char"||_.wrap==="word")&&(O=ti(Nt,_.wrap,`peek-${A.id}`,{skipTags:_.skipTags,startIndex:tt}));let Ve=document.createElement("div");if(Ve.innerHTML=O,_.useCaret&&dt.length>0){let Ke=Ol(),Ae=Ve.querySelectorAll(".persona-stream-char, .persona-stream-word"),nr=Ae[Ae.length-1];nr!=null&&nr.parentNode?nr.parentNode.insertBefore(Ke,nr.nextSibling):Ve.appendChild(Ke)}Pl(g,Ve),(_e=_.onAfterRender)==null||_e.call(_,{container:g,bubble:c,messageId:A.id,message:A,speed:V.speed,duration:V.duration})}}let nt=Yn||Oo;c.classList.toggle("persona-pill-peek--visible",nt)};if(W()){let c=He.peekBanner;if(c){let A=H=>{H.preventDefault(),H.stopPropagation(),Yt(!0,"user")};c.addEventListener("pointerdown",A),Ht.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{Oo||(Oo=!0,xo())},b=()=>{Oo&&(Oo=!1,xo())};ye.addEventListener("pointerenter",g),ye.addEventListener("pointerleave",b),Ht.push(()=>{ye.removeEventListener("pointerenter",g),ye.removeEventListener("pointerleave",b)}),ot&&(ot.addEventListener("pointerenter",g),ot.addEventListener("pointerleave",b),Ht.push(()=>{ot.removeEventListener("pointerenter",g),ot.removeEventListener("pointerleave",b)}))}let ki=c=>{var Pe,Ye,Ee,gt,nt,St,Tt,Ue;let g=(Ye=(Pe=n.launcher)==null?void 0:Pe.composerBar)!=null?Ye:{},b=(Ee=g.expandedSize)!=null?Ee:"anchored",A=(gt=g.bottomOffset)!=null?gt:"16px",H=g.collapsedMaxWidth,F=(nt=g.expandedMaxWidth)!=null?nt:"880px",$=(St=g.expandedTopOffset)!=null?St:"5vh",V=(Tt=g.modalMaxWidth)!=null?Tt:"880px",_=(Ue=g.modalMaxHeight)!=null?Ue:"min(90vh, 800px)",ke="calc(100vw - 32px)",ve="var(--persona-pill-area-height, 80px)",de=Re.style;if(de.left="",de.right="",de.top="",de.bottom="",de.transform="",de.width="",de.maxWidth="",de.height="",de.maxHeight="",ot){let _e=ot.style;_e.bottom=A,_e.width=H!=null?H:""}if(c&&b!=="fullscreen"){if(b==="modal"){de.top="50%",de.left="50%",de.transform="translate(-50%, -50%)",de.bottom="auto",de.right="auto",de.width=V,de.maxWidth=ke,de.maxHeight=_,de.height=_;return}de.left="50%",de.transform="translateX(-50%)",de.bottom=`calc(${A} + ${ve})`,de.top=$,de.width=F,de.maxWidth=ke}},No=()=>{var _,ke,ve,de,Pe,Ye,Ee,gt;if(!P())return;if(W()){let St=(ve=((ke=(_=n.launcher)==null?void 0:_.composerBar)!=null?ke:{}).expandedSize)!=null?ve:"anchored",Tt=R?"expanded":"collapsed";Re.dataset.state=Tt,Re.dataset.expandedSize=St,ot&&(ot.dataset.state=Tt,ot.dataset.expandedSize=St),Re.style.removeProperty("display"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ki(R),G.style.display=R?"flex":"none",Un(),R?(Si(),Ti()):(vs(),Cs()),xo();return}let c=Br(n),g=(de=t.ownerDocument.defaultView)!=null?de:window,b=(Ye=(Pe=n.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Ye:640,A=(gt=(Ee=n.launcher)==null?void 0:Ee.mobileFullscreen)!=null?gt:!0,H=g.innerWidth<=b,F=A&&H&&k,$=Nn(n).reveal;R?(Re.style.removeProperty("display"),Re.style.display=c?"flex":"",Re.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"),Tr?Tr.element.style.display="none":Mr&&(Mr.style.display="none")):(c?c&&($==="overlay"||$==="push")&&!F?(Re.style.removeProperty("display"),Re.style.display="flex",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.setProperty("display","none","important"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.display="",Re.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")),Tr?Tr.element.style.display=c?"none":"":Mr&&(Mr.style.display=c?"none":""))},Yt=(c,g="user")=>{var F,$;if(!P()||R===c)return;let b=R;R=c,No();let A=(()=>{var Ee,gt,nt,St,Tt,Ue,_e,tt,dt,Nt;let V=(gt=(Ee=n.launcher)==null?void 0:Ee.sidebarMode)!=null?gt:!1,_=(nt=t.ownerDocument.defaultView)!=null?nt:window,ke=(Tt=(St=n.launcher)==null?void 0:St.mobileFullscreen)!=null?Tt:!0,ve=(_e=(Ue=n.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?_e:640,de=_.innerWidth<=ve,Pe=Br(n)&&ke&&de,Ye=W()&&((Nt=(dt=(tt=n.launcher)==null?void 0:tt.composerBar)==null?void 0:dt.expandedSize)!=null?Nt:"fullscreen")==="fullscreen";return V||ke&&de&&k||Pe||Ye})();if(R&&A){if(!Ar){let V=t.getRootNode(),_=V instanceof ShadowRoot?V.host:t.closest(".persona-host");_&&(Ar=tu(_,($=(F=n.launcher)==null?void 0:F.zIndex)!=null?$:Qr))}Sr||(Sr=ru(t.ownerDocument))}else R||(Ar==null||Ar(),Ar=null,Sr==null||Sr(),Sr=null);R&&(Ms(),yt()==="follow"?ro(!0):bs());let H={open:R,source:g,timestamp:Date.now()};R&&!b?s.emit("widget:opened",H):!R&&b&&s.emit("widget:closed",H),s.emit("widget:state",{open:R,launcherEnabled:k,voiceActive:Ot.active,streaming:q.isStreaming()})},Ba=c=>{cr(c?"stop":"send"),Y&&(Y.disabled=c),Pn.buttons.forEach(g=>{g.disabled=c}),je.dataset.personaComposerStreaming=c?"true":"false",je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Da=()=>{Ot.active||U&&U.focus()};s.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Da(),200)});let Ss=()=>{var b,A,H,F,$,V,_,ke,ve,de,Pe;Be.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",Xe.textContent=(F=(H=n.copy)==null?void 0:H.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",U.placeholder=(V=($=n.copy)==null?void 0:$.inputPlaceholder)!=null?V:"How can I help...";let c=he.querySelector("[data-persona-intro-card]");if(c){let Ye=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=Ye?"":"none",Ye?(he.classList.remove("persona-gap-3"),he.classList.add("persona-gap-6")):(he.classList.remove("persona-gap-6"),he.classList.add("persona-gap-3"))}!((ve=(ke=n.sendButton)==null?void 0:ke.useIcon)!=null&&ve)&&!(q!=null&&q.isStreaming())&&(J.textContent=(Pe=(de=n.copy)==null?void 0:de.sendButtonLabel)!=null?Pe:"Send"),U.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',U.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Wn=null,lt=()=>{Wn==null&&(Wn=setInterval(()=>{let c=K.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Wn),Wn=null;return}let g=Date.now();c.forEach(b=>{let A=Number(b.getAttribute("data-tool-elapsed"));A&&(b.textContent=el(g-A))})},100))};if(q=new Xa(n,{onMessagesChanged(c){var A;ra(K,c,be),lt(),q&&(c.some(F=>F.role==="user")?Pn.render([],q,U,c):Pn.render(n.suggestionChips,q,U,c,n.suggestionChipsConfig)),ro(!Yn),Ai(c);let g=[...c].reverse().find(H=>H.role==="user");c.length===0&&ta(),!La||ea?(La=!0,Pa=(A=g==null?void 0:g.id)!=null?A:null):g&&g.id!==Pa&&(Pa=g.id,Ci(g.id));let b=Ot.lastUserMessageId;g&&g.id!==b&&(Ot.lastUserMessageId=g.id,s.emit("user:message",g)),Ot.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wa(c),xo()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};mt(ie,(H=>{var F,$,V,_;return H==="idle"?(F=g.idleText)!=null?F:Jr.idle:H==="connecting"?($=g.connectingText)!=null?$:Jr.connecting:H==="connected"?(V=g.connectedText)!=null?V:Jr.connected:H==="error"?(_=g.errorText)!=null?_:Jr.error:Jr[H]})(c),g,c)},onStreamingChanged(c){Yn=c,Ba(c),q&&ra(K,q.getMessages(),be),c||ro(!0),xo()},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":_o(),vb();break;case"speaking":_o(),Cb();break;default:c==="idle"&&q.isBargeInActive()?(_o(),Ts(),Y==null||Y.setAttribute("aria-label","End voice session")):(Ot.active=!1,_o(),Rn("system"),dn());break}},onArtifactsState(c){or=c,gn(),Wa()}}),Pt.current=q,La=!0,((Vf=(zf=n.voiceRecognition)==null?void 0:zf.provider)==null?void 0:Vf.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)}),(we||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var b;(b=n.onSSEEvent)==null||b.call(n,c,g),Q==null||Q.processEvent(c,g),we==null||we.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=Tu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length){ea=!0;try{q.hydrateMessages(c.messages)}finally{ea=!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()||R||!((A=(b=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||A)||Yt(!0,"auto")},z=c=>{var H;if(c.preventDefault(),q.isStreaming()){q.cancel(),Q==null||Q.reset(),X==null||X.update();return}let g=U.value.trim(),b=(H=Wt==null?void 0:Wt.hasAttachments())!=null?H:!1;if(!g&&!b)return;L();let A;b&&(A=[],A.push(...Wt.getContentParts()),g&&A.push(js(g))),U.value="",U.style.height="auto",re(),q.sendMessage(g,{contentParts:A}),b&&Wt.clearAttachments()},D=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},ae={...Il},ge=!1,re=()=>{ae={...Il}},$e=()=>q.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Qe=c=>{if(!U)return;ge=!0,U.value=c,U.dispatchEvent(new Event("input",{bubbles:!0})),ge=!1;let g=U.value.length;U.setSelectionRange(g,g)},Ct=()=>{ge||re()},ft=c=>{if(U){if(D()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=U.selectionStart===0&&U.selectionEnd===0,b=Ix({direction:c.key==="ArrowUp"?"up":"down",history:$e(),currentValue:U.value,atStart:g,state:ae});if(ae=b.state,b.handled){c.preventDefault(),b.value!==void 0&&Qe(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(q.isStreaming()){c.preventDefault();return}re(),c.preventDefault(),J.click()}}},Kt=c=>{c.key!=="Escape"||c.isComposing||q.isStreaming()&&c.composedPath().includes(G)&&(q.cancel(),Q==null||Q.reset(),X==null||X.update(),re(),c.preventDefault(),c.stopImmediatePropagation())},ar=async c=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!Wt)return;let g=ZC(c.clipboardData);g.length!==0&&(c.preventDefault(),await Wt.handleFiles(g))},rr=null,At=!1,Ut=null,et=null,Kr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Or=(c="user")=>{var F,$,V,_,ke,ve,de;if(At||q.isStreaming())return;let g=Kr();if(!g)return;rr=new g;let A=($=((F=n.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;rr.continuous=!0,rr.interimResults=!0,rr.lang="en-US";let H=U.value;rr.onresult=Pe=>{let Ye="",Ee="";for(let nt=0;nt<Pe.results.length;nt++){let St=Pe.results[nt],Tt=St[0].transcript;St.isFinal?Ye+=Tt+" ":Ee=Tt}let gt=H+Ye+Ee;U.value=gt,Ut&&clearTimeout(Ut),(Ye||Ee)&&(Ut=window.setTimeout(()=>{let nt=U.value.trim();nt&&rr&&At&&(sr(),U.value="",U.style.height="auto",q.sendMessage(nt,{viaVoice:!0}))},A))},rr.onerror=Pe=>{Pe.error!=="no-speech"&&sr()},rr.onend=()=>{if(At){let Pe=U.value.trim();Pe&&Pe!==H.trim()&&(U.value="",U.style.height="auto",q.sendMessage(Pe,{viaVoice:!0})),sr()}};try{if(rr.start(),At=!0,Ot.active=!0,c!=="system"&&(Ot.manuallyDeactivated=!1),Rn(c),dn(),Y){let Pe=(V=n.voiceRecognition)!=null?V:{};et={backgroundColor:Y.style.backgroundColor,color:Y.style.color,borderColor:Y.style.borderColor,iconName:(_=Pe.iconName)!=null?_:"mic",iconSize:parseFloat((de=(ve=Pe.iconSize)!=null?ve:(ke=n.sendButton)==null?void 0:ke.size)!=null?de:"40")||24};let Ye=Pe.recordingBackgroundColor,Ee=Pe.recordingIconColor,gt=Pe.recordingBorderColor;if(Y.classList.add("persona-voice-recording"),Y.style.backgroundColor=Ye!=null?Ye:"var(--persona-voice-recording-bg, #ef4444)",Y.style.color=Ee!=null?Ee:"var(--persona-voice-recording-indicator, #ffffff)",Ee){let nt=Y.querySelector("svg");nt&&nt.setAttribute("stroke",Ee)}gt&&(Y.style.borderColor=gt),Y.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(c="user")=>{if(At){if(At=!1,Ut&&(clearTimeout(Ut),Ut=null),rr){try{rr.stop()}catch{}rr=null}if(Ot.active=!1,Rn(c),dn(),Y){if(Y.classList.remove("persona-voice-recording"),et){Y.style.backgroundColor=et.backgroundColor,Y.style.color=et.color,Y.style.borderColor=et.borderColor;let g=Y.querySelector("svg");g&&g.setAttribute("stroke",et.color||"currentColor"),et=null}Y.setAttribute("aria-label","Start voice recognition")}}},jn=(c,g)=>{var St,Tt,Ue,_e,tt,dt,Nt,O;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((St=c==null?void 0:c.provider)==null?void 0:St.type)==="runtype";if(!(b||A))return null;let F=w("div","persona-send-button-wrapper"),$=w("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 V=(Tt=c==null?void 0:c.iconName)!=null?Tt:"mic",_=(Ue=g==null?void 0:g.size)!=null?Ue:"40px",ke=(_e=c==null?void 0:c.iconSize)!=null?_e:_,ve=parseFloat(ke)||24,de=(tt=c==null?void 0:c.backgroundColor)!=null?tt:g==null?void 0:g.backgroundColor,Pe=(dt=c==null?void 0:c.iconColor)!=null?dt:g==null?void 0:g.textColor;$.style.width=ke,$.style.height=ke,$.style.minWidth=ke,$.style.minHeight=ke,$.style.fontSize="18px",$.style.lineHeight="1",Pe?$.style.color=Pe:$.style.color="var(--persona-text, #111827)";let Ee=Ie(V,ve,Pe||"currentColor",1.5);Ee?$.appendChild(Ee):$.textContent="\u{1F3A4}",de?$.style.backgroundColor=de:$.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 gt=(Nt=c==null?void 0:c.tooltipText)!=null?Nt:"Start voice recognition";if(((O=c==null?void 0:c.showTooltip)!=null?O:!1)&&gt){let Ve=w("div","persona-send-button-tooltip");Ve.textContent=gt,F.appendChild(Ve)}return{micButton:$,micButtonWrapper:F}},gd=()=>{var g,b,A,H,F;if(!Y||et)return;let c=(g=n.voiceRecognition)!=null?g:{};et={backgroundColor:Y.style.backgroundColor,color:Y.style.color,borderColor:Y.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((F=(H=c.iconSize)!=null?H:(A=n.sendButton)==null?void 0:A.size)!=null?F:"40")||24}},hd=(c,g)=>{var F,$,V,_,ke;if(!Y)return;let b=Y.querySelector("svg");b&&b.remove();let A=(ke=et==null?void 0:et.iconSize)!=null?ke:parseFloat((_=(V=(F=n.voiceRecognition)==null?void 0:F.iconSize)!=null?V:($=n.sendButton)==null?void 0:$.size)!=null?_:"40")||24,H=Ie(c,A,g,1.5);H&&Y.appendChild(H)},Ei=()=>{Y&&Y.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ts=()=>{var H;if(!Y)return;gd();let c=(H=n.voiceRecognition)!=null?H:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,A=c.recordingBorderColor;if(Ei(),Y.classList.add("persona-voice-recording"),Y.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",Y.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let F=Y.querySelector("svg");F&&F.setAttribute("stroke",b)}A&&(Y.style.borderColor=A),Y.setAttribute("aria-label","Stop voice recognition")},vb=()=>{var V,_,ke,ve,de,Pe,Ye,Ee;if(!Y)return;gd();let c=(V=n.voiceRecognition)!=null?V:{},g=q.getVoiceInterruptionMode(),b=(_=c.processingIconName)!=null?_:"loader",A=(ve=(ke=c.processingIconColor)!=null?ke:et==null?void 0:et.color)!=null?ve:"",H=(Pe=(de=c.processingBackgroundColor)!=null?de:et==null?void 0:et.backgroundColor)!=null?Pe:"",F=(Ee=(Ye=c.processingBorderColor)!=null?Ye:et==null?void 0:et.borderColor)!=null?Ee:"";Ei(),Y.classList.add("persona-voice-processing"),Y.style.backgroundColor=H,Y.style.borderColor=F;let $=A||"currentColor";Y.style.color=$,hd(b,$),Y.setAttribute("aria-label","Processing voice input"),g==="none"&&(Y.style.cursor="default")},Cb=()=>{var ke,ve,de,Pe,Ye,Ee,gt,nt,St,Tt,Ue,_e;if(!Y)return;gd();let c=(ke=n.voiceRecognition)!=null?ke:{},g=q.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(ve=c.speakingIconName)!=null?ve:b,H=(Ee=c.speakingIconColor)!=null?Ee:g==="barge-in"?(Pe=(de=c.recordingIconColor)!=null?de:et==null?void 0:et.color)!=null?Pe:"":(Ye=et==null?void 0:et.color)!=null?Ye:"",F=(St=c.speakingBackgroundColor)!=null?St:g==="barge-in"?(gt=c.recordingBackgroundColor)!=null?gt:"var(--persona-voice-recording-bg, #ef4444)":(nt=et==null?void 0:et.backgroundColor)!=null?nt:"",$=(_e=c.speakingBorderColor)!=null?_e:g==="barge-in"?(Tt=c.recordingBorderColor)!=null?Tt:"":(Ue=et==null?void 0:et.borderColor)!=null?Ue:"";Ei(),Y.classList.add("persona-voice-speaking"),Y.style.backgroundColor=F,Y.style.borderColor=$;let V=H||"currentColor";Y.style.color=V,hd(A,V);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";Y.setAttribute("aria-label",_),g==="none"&&(Y.style.cursor="default"),g==="barge-in"&&Y.classList.add("persona-voice-recording")},_o=()=>{var c,g,b;Y&&(Ei(),et&&(Y.style.backgroundColor=(c=et.backgroundColor)!=null?c:"",Y.style.color=(g=et.color)!=null?g:"",Y.style.borderColor=(b=et.borderColor)!=null?b:"",hd(et.iconName,et.color||"currentColor"),et=null),Y.style.cursor="",Y.setAttribute("aria-label","Start voice recognition"))},Li=()=>{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(()=>{Ot.active=!1,Ot.manuallyDeactivated=!0,dn(),Rn("user"),_o()});return}q.toggleVoice().then(()=>{Ot.active=q.isVoiceActive(),Ot.manuallyDeactivated=!q.isVoiceActive(),dn(),Rn("user"),q.isVoiceActive()?Ts():_o()});return}if(At){let b=U.value.trim();Ot.manuallyDeactivated=!0,dn(),sr("user"),b&&(U.value="",U.style.height="auto",q.sendMessage(b))}else Ot.manuallyDeactivated=!1,dn(),Or("user")};zr=Li,Y&&(Y.addEventListener("click",Li),Ht.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),_o()):sr("system"),Y&&Y.removeEventListener("click",Li)}));let Ab=s.on("assistant:complete",()=>{us&&(Ot.active||Ot.manuallyDeactivated||us==="assistant"&&!Ot.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Ot.active&&!Ot.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{Ot.active=q.isVoiceActive(),Rn("auto"),q.isVoiceActive()&&Ts()}):Or("auto"))},600))});Ht.push(Ab);let Sb=s.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Ht.push(Sb);let Oa=()=>{Yt(!R,"user")},Tr=null,Mr=null;if(k&&!W()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>oi(n,Oa).element,onToggle:Oa});g&&(Mr=g)}Mr||(Tr=oi(n,Oa))}Tr?t.appendChild(Tr.element):Mr&&t.appendChild(Mr),No(),Pn.render(n.suggestionChips,q,U,void 0,n.suggestionChipsConfig),Ss(),Ba(q.isStreaming()),yt()==="follow"?ro(!0):bs(),xi(),M&&(!k||W()?setTimeout(()=>Da(),0):R&&setTimeout(()=>Da(),200));let Ms=()=>{var _,ke,ve,de,Pe,Ye,Ee,gt,nt,St,Tt,Ue,_e,tt,dt,Nt,O,Ve,Ke,Ae,nr,Zt;if(W()){Er(),No();return}let c=Br(n),g=(ke=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?ke:!1,b=c||g||((de=(ve=n.launcher)==null?void 0:ve.fullHeight)!=null?de:!1),A=(Pe=t.ownerDocument.defaultView)!=null?Pe:window,H=(Ee=(Ye=n.launcher)==null?void 0:Ye.mobileFullscreen)!=null?Ee:!0,F=(nt=(gt=n.launcher)==null?void 0:gt.mobileBreakpoint)!=null?nt:640,$=A.innerWidth<=F,V=H&&$&&k;try{if(V){Un(),zo(t,n);return}if(T&&(T=!1,Un(),zo(t,n)),!k&&!c){ye.style.height="",ye.style.width="";return}if(!g&&!c){let mr=(Tt=(St=n==null?void 0:n.launcher)==null?void 0:St.width)!=null?Tt:n==null?void 0:n.launcherWidth,Ft=mr!=null?mr:Tn;ye.style.width=Ft,ye.style.maxWidth=Ft}if(Qn(),!b){let mr=A.innerHeight,Ft=64,ur=(_e=(Ue=n.launcher)==null?void 0:Ue.heightOffset)!=null?_e:0,bn=Math.max(200,mr-Ft),Lr=Math.min(640,bn),ct=Math.max(200,Lr-ur);ye.style.height=`${ct}px`}}finally{if(Er(),No(),R&&k){let Ft=((tt=t.ownerDocument.defaultView)!=null?tt:window).innerWidth<=((Nt=(dt=n.launcher)==null?void 0:dt.mobileBreakpoint)!=null?Nt:640),ur=(Ve=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?Ve:!1,bn=(Ae=(Ke=n.launcher)==null?void 0:Ke.mobileFullscreen)!=null?Ae:!0,Lr=Br(n)&&bn&&Ft,ct=ur||bn&&Ft&&k||Lr;if(ct&&!Sr){let jt=t.getRootNode(),Rr=jt instanceof ShadowRoot?jt.host:t.closest(".persona-host");Rr&&!Ar&&(Ar=tu(Rr,(Zt=(nr=n.launcher)==null?void 0:nr.zIndex)!=null?Zt:Qr)),Sr=ru(t.ownerDocument)}else ct||(Ar==null||Ar(),Ar=null,Sr==null||Sr(),Sr=null)}}};Ms();let Uu=(jf=t.ownerDocument.defaultView)!=null?jf:window;if(Uu.addEventListener("resize",Ms),Ht.push(()=>Uu.removeEventListener("resize",Ms)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Er()});c.observe(je),Ht.push(()=>c.disconnect())}yn=he.scrollTop;let qu=To(he),Tb=()=>{let c=he.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:he.ownerDocument.getSelection()},xd=()=>Ox(Tb(),he),zu=()=>{let c=he.scrollTop,g=To(he),b=g<qu;if(qu=g,yt()!=="follow"){yn=c,cn();return}let{action:A,nextLastScrollTop:H}=Wl({following:xn.isFollowing(),currentScrollTop:c,lastScrollTop:yn,nearBottom:Ca(he,Ia),userScrollThreshold:gi,isAutoScrolling:Vn||Zo||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(yn=H,A==="resume"){xd()||to();return}A==="pause"&&Ha()};if(he.addEventListener("scroll",zu,{passive:!0}),Ht.push(()=>he.removeEventListener("scroll",zu)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{vi()});c.observe(K),c.observe(he),Ht.push(()=>c.disconnect())}let Vu=()=>{yt()==="follow"&&xn.isFollowing()&&xd()&&Ha()},ju=he.ownerDocument;ju.addEventListener("selectionchange",Vu),Ht.push(()=>{ju.removeEventListener("selectionchange",Vu)});let Gu=c=>{if(yt()!=="follow")return;let g=Hl({following:xn.isFollowing(),deltaY:c.deltaY,nearBottom:Ca(he,Ia),resumeWhenNearBottom:!0});g==="pause"?Ha():g==="resume"&&!xd()&&to()};he.addEventListener("wheel",Gu,{passive:!0}),Ht.push(()=>he.removeEventListener("wheel",Gu)),it.addEventListener("click",()=>{ta(),he.scrollTop=he.scrollHeight,yn=he.scrollTop,to(),ro(!0),cn()}),Ht.push(()=>it.remove()),Ht.push(()=>{ms(),ta()});let Ku=()=>{B&&(In&&(B.removeEventListener("click",In),In=null),P()?(B.style.display="",In=()=>{Yt(!1,"user")},B.addEventListener("click",In)):B.style.display="none")};Ku(),(()=>{let{clearChatButton:c}=He;c&&c.addEventListener("click",()=>{q.clearMessages(),fo.clear(),to(),Qo(He.composerOverlay);try{localStorage.removeItem(ds),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ds}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ds)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(),we==null||we.clear(),Q==null||Q.reset(),X==null||X.update()})})(),se&&se.addEventListener("submit",z),U==null||U.addEventListener("keydown",ft),U==null||U.addEventListener("input",Ct),U==null||U.addEventListener("paste",ar);let Xu=(Gf=t.ownerDocument)!=null?Gf:document;Xu.addEventListener("keydown",Kt,!0);let Ju="persona-attachment-drop-active",ks=0,yd=()=>{ks=0,G.classList.remove(Ju)},Na=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&Wt!==null},Qu=c=>{!cd(c.dataTransfer)||!Na()||(ks++,ks===1&&G.classList.add(Ju))},Yu=c=>{!cd(c.dataTransfer)||!Na()||(ks--,ks<=0&&yd())},Zu=c=>{!cd(c.dataTransfer)||!Na()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},ef=c=>{var b;if(!cd(c.dataTransfer)||!Na())return;c.preventDefault(),c.stopPropagation(),yd();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&Wt.handleFiles(g)},Fo=!0;G.addEventListener("dragenter",Qu,Fo),G.addEventListener("dragleave",Yu,Fo),t.addEventListener("dragover",Zu,Fo),t.addEventListener("drop",ef,Fo);let Pi=t.ownerDocument,tf=c=>{Na()&&c.preventDefault()},rf=c=>{Na()&&c.preventDefault()};Pi.addEventListener("dragover",tf),Pi.addEventListener("drop",rf),Ht.push(()=>{se&&se.removeEventListener("submit",z),U==null||U.removeEventListener("keydown",ft),U==null||U.removeEventListener("input",Ct),U==null||U.removeEventListener("paste",ar),Xu.removeEventListener("keydown",Kt,!0)}),Ht.push(()=>{G.removeEventListener("dragenter",Qu,Fo),G.removeEventListener("dragleave",Yu,Fo),t.removeEventListener("dragover",Zu,Fo),t.removeEventListener("drop",ef,Fo),Pi.removeEventListener("dragover",tf),Pi.removeEventListener("drop",rf),yd()}),Ht.push(()=>{q.cancel()}),Tr?Ht.push(()=>{Tr==null||Tr.destroy()}):Mr&&Ht.push(()=>{Mr==null||Mr.remove()});let Ir={update(c){var no,Hr,en,Dn,sa,ia,Ii,Es,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,Hm,Bm,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,Lg,Pg,Ig,Rg,Wg,Hg,Bg,Dg,Og,Ng,_g,Fg,$g,Ug,qg,zg,Vg,jg,Gg,Kg,Xg,Jg,Qg,Yg;let g=n.toolCall,b=n.messageActions,A=(no=n.layout)==null?void 0:no.messages,H=n.colorScheme,F=n.loadingIndicator,$=n.iterationDisplay,V=(Hr=n.features)==null?void 0:Hr.showReasoning,_=(en=n.features)==null?void 0:en.showToolCalls,ke=(Dn=n.features)==null?void 0:Dn.toolCallDisplay,ve=(sa=n.features)==null?void 0:sa.reasoningDisplay;n={...n,...c},Un(),zo(t,n),td(t,n),rd(t,n),gn(),n.colorScheme!==H&&Wo();let de=ci.getForInstance(n.plugins);o.length=0,o.push(...de),k=(Ii=(ia=n.launcher)==null?void 0:ia.enabled)!=null?Ii:!0,E=(em=(Es=n.launcher)==null?void 0:Es.autoExpand)!=null?em:!1,Ze=(rm=(tm=n.features)==null?void 0:tm.showReasoning)!=null?rm:!0,Se=(om=(nm=n.features)==null?void 0:nm.showToolCalls)!=null?om:!0,Ce=(sm=(am=n.features)==null?void 0:am.scrollToBottom)!=null?sm:{};let Pe=yt();Fe=(lm=(im=n.features)==null?void 0:im.scrollBehavior)!=null?lm:{},Pe!==yt()&&(ta(),to()),fn(),cn();let Ye=Ne;if(Ne=(cm=(dm=n.features)==null?void 0:dm.showEventStreamToggle)!=null?cm:!1,Ne&&!Ye){if(we||(ne=new li(Z),we=new ii(ee,ne),Q=Q!=null?Q:new di,ne.open().then(()=>we==null?void 0:we.restore()).catch(()=>{}),q.setSSEEventCallback((oe,qt)=>{var ir;(ir=n.onSSEEvent)==null||ir.call(n,oe,qt),Q==null||Q.processEvent(oe,qt),we.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:oe,timestamp:Date.now(),payload:JSON.stringify(qt)})})),!Lt&&ze){let oe=(um=(pm=n.features)==null?void 0:pm.eventStream)==null?void 0:um.classNames,qt="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"+(oe!=null&&oe.toggleButton?" "+oe.toggleButton:"");Lt=w("button",qt),Lt.style.width="28px",Lt.style.height="28px",Lt.style.color=sn.actionIconColor,Lt.type="button",Lt.setAttribute("aria-label","Event Stream"),Lt.title="Event Stream";let ir=Ie("activity","18px","currentColor",1.5);ir&&Lt.appendChild(ir);let Et=He.clearChatButtonWrapper,Gt=He.closeButtonWrapper,Nr=Et||Gt;Nr&&Nr.parentNode===ze?ze.insertBefore(Lt,Nr):ze.appendChild(Lt),Lt.addEventListener("click",()=>{fe?ln():kn()})}}else!Ne&&Ye&&(ln(),Lt&&(Lt.remove(),Lt=null),we==null||we.clear(),ne==null||ne.destroy(),we=null,ne=null,Q==null||Q.reset(),Q=null);if(((fm=n.launcher)==null?void 0:fm.enabled)===!1&&Tr&&(Tr.destroy(),Tr=null),((mm=n.launcher)==null?void 0:mm.enabled)===!1&&Mr&&(Mr.remove(),Mr=null),((gm=n.launcher)==null?void 0:gm.enabled)!==!1&&!Tr&&!Mr){let oe=o.find(qt=>qt.renderLauncher);if(oe!=null&&oe.renderLauncher){let qt=oe.renderLauncher({config:n,defaultRenderer:()=>oi(n,Oa).element,onToggle:Oa});qt&&(Mr=qt,t.appendChild(Mr))}Mr||(Tr=oi(n,Oa),t.appendChild(Tr.element))}Tr&&Tr.update(n),De&&((hm=n.launcher)==null?void 0:hm.title)!==void 0&&(De.textContent=n.launcher.title),rt&&((xm=n.launcher)==null?void 0:xm.subtitle)!==void 0&&(rt.textContent=n.launcher.subtitle);let Ee=(ym=n.layout)==null?void 0:ym.header;if((Ee==null?void 0:Ee.layout)!==v&&ze){let oe=Ee?Za(n,Ee,{showClose:P(),onClose:()=>Yt(!1,"user")}):Mo({config:n,showClose:P(),onClose:()=>Yt(!1,"user")});ze.replaceWith(oe.header),ze=oe.header,xe=oe.iconHolder,De=oe.headerTitle,rt=oe.headerSubtitle,B=oe.closeButton,v=Ee==null?void 0:Ee.layout}else if(Ee&&(xe&&(xe.style.display=Ee.showIcon===!1?"none":""),De&&(De.style.display=Ee.showTitle===!1?"none":""),rt&&(rt.style.display=Ee.showSubtitle===!1?"none":""),B&&(B.style.display=Ee.showCloseButton===!1?"none":""),He.clearChatButtonWrapper)){let oe=Ee.showClearChat;if(oe!==void 0){He.clearChatButtonWrapper.style.display=oe?"":"none";let{closeButtonWrapper:qt}=He;qt&&!qt.classList.contains("persona-absolute")&&(oe?qt.classList.remove("persona-ml-auto"):qt.classList.add("persona-ml-auto"))}}let nt=((bm=n.layout)==null?void 0:bm.showHeader)!==!1;ze&&(ze.style.display=nt?"":"none");let St=((wm=n.layout)==null?void 0:wm.showFooter)!==!1;je&&(je.style.display=St?"":"none"),Er(),cn(),k!==C?k?Yt(E,"auto"):(R=!0,No()):E!==h&&Yt(E,"auto"),h=E,C=k,Ms(),Ku();let _e=JSON.stringify(c.toolCall)!==JSON.stringify(g),tt=JSON.stringify(n.messageActions)!==JSON.stringify(b),dt=JSON.stringify((vm=n.layout)==null?void 0:vm.messages)!==JSON.stringify(A),Nt=((Cm=n.loadingIndicator)==null?void 0:Cm.render)!==(F==null?void 0:F.render)||((Am=n.loadingIndicator)==null?void 0:Am.renderIdle)!==(F==null?void 0:F.renderIdle)||((Sm=n.loadingIndicator)==null?void 0:Sm.showBubble)!==(F==null?void 0:F.showBubble),O=n.iterationDisplay!==$,Ve=((Mm=(Tm=n.features)==null?void 0:Tm.showReasoning)!=null?Mm:!0)!==(V!=null?V:!0)||((Em=(km=n.features)==null?void 0:km.showToolCalls)!=null?Em:!0)!==(_!=null?_:!0)||JSON.stringify((Lm=n.features)==null?void 0:Lm.toolCallDisplay)!==JSON.stringify(ke)||JSON.stringify((Pm=n.features)==null?void 0:Pm.reasoningDisplay)!==JSON.stringify(ve);(_e||tt||dt||Nt||O||Ve)&&q&&(ps++,ra(K,q.getMessages(),be));let Ae=(Im=n.launcher)!=null?Im:{},nr=(Rm=Ae.headerIconHidden)!=null?Rm:!1,Zt=(Hm=(Wm=n.layout)==null?void 0:Wm.header)==null?void 0:Hm.showIcon,mr=nr||Zt===!1,Ft=Ae.headerIconName,ur=(Bm=Ae.headerIconSize)!=null?Bm:"48px";if(xe){let oe=G.querySelector(".persona-border-b-persona-divider"),qt=oe==null?void 0:oe.querySelector(".persona-flex-col");if(mr)xe.style.display="none",oe&&qt&&!oe.contains(qt)&&oe.insertBefore(qt,oe.firstChild);else{if(xe.style.display="",xe.style.height=ur,xe.style.width=ur,oe&&qt&&(oe.contains(xe)?xe.nextSibling!==qt&&(xe.remove(),oe.insertBefore(xe,qt)):oe.insertBefore(xe,qt)),Ft){let Et=parseFloat(ur)||24,Gt=Ie(Ft,Et*.6,"#ffffff",2);Gt?xe.replaceChildren(Gt):xe.textContent=(Dm=Ae.agentIconText)!=null?Dm:"\u{1F4AC}"}else if(Ae.iconUrl){let Et=xe.querySelector("img");if(Et)Et.src=Ae.iconUrl,Et.style.height=ur,Et.style.width=ur;else{let Gt=document.createElement("img");Gt.src=Ae.iconUrl,Gt.alt="",Gt.className="persona-rounded-xl persona-object-cover",Gt.style.height=ur,Gt.style.width=ur,xe.replaceChildren(Gt)}}else{let Et=xe.querySelector("svg"),Gt=xe.querySelector("img");(Et||Gt)&&xe.replaceChildren(),xe.textContent=(Om=Ae.agentIconText)!=null?Om:"\u{1F4AC}"}let ir=xe.querySelector("img");ir&&(ir.style.height=ur,ir.style.width=ur)}}let bn=(_m=(Nm=n.layout)==null?void 0:Nm.header)==null?void 0:_m.showTitle,Lr=($m=(Fm=n.layout)==null?void 0:Fm.header)==null?void 0:$m.showSubtitle;if(De&&(De.style.display=bn===!1?"none":""),rt&&(rt.style.display=Lr===!1?"none":""),B){((qm=(Um=n.layout)==null?void 0:Um.header)==null?void 0:qm.showCloseButton)===!1?B.style.display="none":B.style.display="";let qt=(zm=Ae.closeButtonSize)!=null?zm:"32px",ir=(Vm=Ae.closeButtonPlacement)!=null?Vm:"inline";B.style.height=qt,B.style.width=qt;let{closeButtonWrapper:Et}=He,Gt=ir==="top-right",Nr=Et==null?void 0:Et.classList.contains("persona-absolute");if(Et&&Gt!==Nr)if(Et.remove(),Gt)Et.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",G.style.position="relative",G.appendChild(Et);else{let It=(Gm=(jm=Ae.clearChat)==null?void 0:jm.placement)!=null?Gm:"inline",_r=(Xm=(Km=Ae.clearChat)==null?void 0:Km.enabled)!=null?Xm:!0;Et.className=_r&&It==="inline"?"":"persona-ml-auto";let un=G.querySelector(".persona-border-b-persona-divider");un&&un.appendChild(Et)}if(B.style.color=Ae.closeButtonColor||sn.actionIconColor,Ae.closeButtonBackgroundColor?(B.style.backgroundColor=Ae.closeButtonBackgroundColor,B.classList.remove("hover:persona-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:persona-bg-gray-100")),Ae.closeButtonBorderWidth||Ae.closeButtonBorderColor){let It=Ae.closeButtonBorderWidth||"0px",_r=Ae.closeButtonBorderColor||"transparent";B.style.border=`${It} solid ${_r}`,B.classList.remove("persona-border-none")}else B.style.border="",B.classList.add("persona-border-none");Ae.closeButtonBorderRadius?(B.style.borderRadius=Ae.closeButtonBorderRadius,B.classList.remove("persona-rounded-full")):(B.style.borderRadius="",B.classList.add("persona-rounded-full")),Ae.closeButtonPaddingX?(B.style.paddingLeft=Ae.closeButtonPaddingX,B.style.paddingRight=Ae.closeButtonPaddingX):(B.style.paddingLeft="",B.style.paddingRight=""),Ae.closeButtonPaddingY?(B.style.paddingTop=Ae.closeButtonPaddingY,B.style.paddingBottom=Ae.closeButtonPaddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Xr=(Jm=Ae.closeButtonIconName)!=null?Jm:"x",Gn=(Qm=Ae.closeButtonIconText)!=null?Qm:"\xD7";B.innerHTML="";let tn=Ie(Xr,"28px","currentColor",1);tn?B.appendChild(tn):B.textContent=Gn;let kr=(Ym=Ae.closeButtonTooltipText)!=null?Ym:"Close chat",vn=(Zm=Ae.closeButtonShowTooltip)!=null?Zm:!0;if(B.setAttribute("aria-label",kr),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),vn&&kr)){let It=null,_r=()=>{if(It||!B)return;let la=B.ownerDocument,Ls=la.body;if(!Ls)return;It=lo(la,"div","persona-clear-chat-tooltip"),It.textContent=kr;let Ps=lo(la,"div");Ps.className="persona-clear-chat-tooltip-arrow",It.appendChild(Ps);let da=B.getBoundingClientRect();It.style.position="fixed",It.style.zIndex=String(Vo),It.style.left=`${da.left+da.width/2}px`,It.style.top=`${da.top-8}px`,It.style.transform="translate(-50%, -100%)",Ls.appendChild(It)},un=()=>{It&&It.parentNode&&(It.parentNode.removeChild(It),It=null)};Et.addEventListener("mouseenter",_r),Et.addEventListener("mouseleave",un),B.addEventListener("focus",_r),B.addEventListener("blur",un),Et._cleanupTooltip=()=>{un(),Et&&(Et.removeEventListener("mouseenter",_r),Et.removeEventListener("mouseleave",un)),B&&(B.removeEventListener("focus",_r),B.removeEventListener("blur",un))}}}let{clearChatButton:ct,clearChatButtonWrapper:jt}=He;if(ct){let oe=(eg=Ae.clearChat)!=null?eg:{},qt=(tg=oe.enabled)!=null?tg:!0,ir=(ng=(rg=n.layout)==null?void 0:rg.header)==null?void 0:ng.showClearChat,Et=ir!==void 0?ir:qt,Gt=(og=oe.placement)!=null?og:"inline";if(jt){jt.style.display=Et?"":"none";let{closeButtonWrapper:Nr}=He;!W()&&Nr&&!Nr.classList.contains("persona-absolute")&&(Et?Nr.classList.remove("persona-ml-auto"):Nr.classList.add("persona-ml-auto"));let Xr=Gt==="top-right",Gn=jt.classList.contains("persona-absolute");if(!W()&&Xr!==Gn&&Et){if(jt.remove(),Xr)jt.className="persona-absolute persona-top-4 persona-z-50",jt.style.right="48px",G.style.position="relative",G.appendChild(jt);else{jt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",jt.style.right="";let kr=G.querySelector(".persona-border-b-persona-divider"),vn=He.closeButtonWrapper;kr&&vn&&vn.parentElement===kr?kr.insertBefore(jt,vn):kr&&kr.appendChild(jt)}let tn=He.closeButtonWrapper;tn&&!tn.classList.contains("persona-absolute")&&(Xr?tn.classList.add("persona-ml-auto"):tn.classList.remove("persona-ml-auto"))}}if(Et){if(!W()){let It=(ag=oe.size)!=null?ag:"32px";ct.style.height=It,ct.style.width=It}let Nr=(sg=oe.iconName)!=null?sg:"refresh-cw",Xr=(ig=oe.iconColor)!=null?ig:"";ct.style.color=Xr||sn.actionIconColor,ct.innerHTML="";let Gn=W()?"14px":"20px",tn=Ie(Nr,Gn,"currentColor",2);if(tn&&ct.appendChild(tn),oe.backgroundColor?(ct.style.backgroundColor=oe.backgroundColor,ct.classList.remove("hover:persona-bg-gray-100")):(ct.style.backgroundColor="",ct.classList.add("hover:persona-bg-gray-100")),oe.borderWidth||oe.borderColor){let It=oe.borderWidth||"0px",_r=oe.borderColor||"transparent";ct.style.border=`${It} solid ${_r}`,ct.classList.remove("persona-border-none")}else ct.style.border="",ct.classList.add("persona-border-none");oe.borderRadius?(ct.style.borderRadius=oe.borderRadius,ct.classList.remove("persona-rounded-full")):(ct.style.borderRadius="",ct.classList.add("persona-rounded-full")),oe.paddingX?(ct.style.paddingLeft=oe.paddingX,ct.style.paddingRight=oe.paddingX):(ct.style.paddingLeft="",ct.style.paddingRight=""),oe.paddingY?(ct.style.paddingTop=oe.paddingY,ct.style.paddingBottom=oe.paddingY):(ct.style.paddingTop="",ct.style.paddingBottom="");let kr=(lg=oe.tooltipText)!=null?lg:"Clear chat",vn=(dg=oe.showTooltip)!=null?dg:!0;if(ct.setAttribute("aria-label",kr),jt&&(jt._cleanupTooltip&&(jt._cleanupTooltip(),delete jt._cleanupTooltip),vn&&kr)){let It=null,_r=()=>{if(It||!ct)return;let la=ct.ownerDocument,Ls=la.body;if(!Ls)return;It=lo(la,"div","persona-clear-chat-tooltip"),It.textContent=kr;let Ps=lo(la,"div");Ps.className="persona-clear-chat-tooltip-arrow",It.appendChild(Ps);let da=ct.getBoundingClientRect();It.style.position="fixed",It.style.zIndex=String(Vo),It.style.left=`${da.left+da.width/2}px`,It.style.top=`${da.top-8}px`,It.style.transform="translate(-50%, -100%)",Ls.appendChild(It)},un=()=>{It&&It.parentNode&&(It.parentNode.removeChild(It),It=null)};jt.addEventListener("mouseenter",_r),jt.addEventListener("mouseleave",un),ct.addEventListener("focus",_r),ct.addEventListener("blur",un),jt._cleanupTooltip=()=>{un(),jt&&(jt.removeEventListener("mouseenter",_r),jt.removeEventListener("mouseleave",un)),ct&&(ct.removeEventListener("focus",_r),ct.removeEventListener("blur",un))}}}}let Rr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[pi],Bn=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ea.message,Ea.messageAndClick];S=ui({parsers:Rr,handlers:Bn,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),be=Dy(n,S,ce),q.updateConfig(n),ra(K,q.getMessages(),be),Pn.render(n.suggestionChips,q,U,void 0,n.suggestionChipsConfig),Ss(),Ba(q.isStreaming());let wn=((cg=n.voiceRecognition)==null?void 0:cg.enabled)===!0,na=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),oa=((ug=(pg=n.voiceRecognition)==null?void 0:pg.provider)==null?void 0:ug.type)==="runtype";if(wn&&(na||oa))if(!Y||!vt){let oe=jn(n.voiceRecognition,n.sendButton);oe&&(Y=oe.micButton,vt=oe.micButtonWrapper,tr.insertBefore(vt,qe),Y.addEventListener("click",Li),Y.disabled=q.isStreaming())}else{let oe=(fg=n.voiceRecognition)!=null?fg:{},qt=(mg=n.sendButton)!=null?mg:{},ir=(gg=oe.iconName)!=null?gg:"mic",Et=(hg=qt.size)!=null?hg:"40px",Gt=(xg=oe.iconSize)!=null?xg:Et,Nr=parseFloat(Gt)||24;Y.style.width=Gt,Y.style.height=Gt,Y.style.minWidth=Gt,Y.style.minHeight=Gt;let Xr=(bg=(yg=oe.iconColor)!=null?yg:qt.textColor)!=null?bg:"currentColor";Y.innerHTML="";let Gn=Ie(ir,Nr,Xr,2);Gn?Y.appendChild(Gn):Y.textContent="\u{1F3A4}";let tn=(wg=oe.backgroundColor)!=null?wg:qt.backgroundColor;tn?Y.style.backgroundColor=tn:Y.style.backgroundColor="",Xr?Y.style.color=Xr:Y.style.color="var(--persona-text, #111827)",oe.borderWidth?(Y.style.borderWidth=oe.borderWidth,Y.style.borderStyle="solid"):(Y.style.borderWidth="",Y.style.borderStyle=""),oe.borderColor?Y.style.borderColor=oe.borderColor:Y.style.borderColor="",oe.paddingX?(Y.style.paddingLeft=oe.paddingX,Y.style.paddingRight=oe.paddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),oe.paddingY?(Y.style.paddingTop=oe.paddingY,Y.style.paddingBottom=oe.paddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kr=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip"),vn=(vg=oe.tooltipText)!=null?vg:"Start voice recognition";if(((Cg=oe.showTooltip)!=null?Cg:!1)&&vn)if(kr)kr.textContent=vn,kr.style.display="";else{let _r=document.createElement("div");_r.className="persona-send-button-tooltip",_r.textContent=vn,vt==null||vt.insertBefore(_r,Y)}else kr&&(kr.style.display="none");vt.style.display="",Y.disabled=q.isStreaming()}else Y&&vt&&(vt.style.display="none",((Sg=(Ag=n.voiceRecognition)==null?void 0:Ag.provider)==null?void 0:Sg.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():At&&sr());if(((Tg=n.attachments)==null?void 0:Tg.enabled)===!0)if(!Te||!ut){let oe=(Mg=n.attachments)!=null?Mg:{},ir=(Eg=((kg=n.sendButton)!=null?kg:{}).size)!=null?Eg:"40px";pt||(pt=w("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),pt.style.display="none",se.insertBefore(pt,U)),ue||(ue=document.createElement("input"),ue.type="file",ue.accept=((Lg=oe.allowedTypes)!=null?Lg:So).join(","),ue.multiple=((Pg=oe.maxFiles)!=null?Pg:4)>1,ue.style.display="none",ue.setAttribute("aria-label","Attach files"),se.insertBefore(ue,U)),Te=w("div","persona-send-button-wrapper"),ut=w("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ut.type="button",ut.setAttribute("aria-label",(Ig=oe.buttonTooltipText)!=null?Ig:"Attach file");let Et=(Rg=oe.buttonIconName)!=null?Rg:"paperclip",Gt=ir,Nr=parseFloat(Gt)||40,Xr=Math.round(Nr*.6);ut.style.width=Gt,ut.style.height=Gt,ut.style.minWidth=Gt,ut.style.minHeight=Gt,ut.style.fontSize="18px",ut.style.lineHeight="1",ut.style.backgroundColor="transparent",ut.style.color="var(--persona-primary, #111827)",ut.style.border="none",ut.style.borderRadius="6px",ut.style.transition="background-color 0.15s ease",ut.addEventListener("mouseenter",()=>{ut.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ut.addEventListener("mouseleave",()=>{ut.style.backgroundColor="transparent"});let Gn=Ie(Et,Xr,"currentColor",1.5);Gn?ut.appendChild(Gn):ut.textContent="\u{1F4CE}",ut.addEventListener("click",vn=>{vn.preventDefault(),ue==null||ue.click()}),Te.appendChild(ut);let tn=(Wg=oe.buttonTooltipText)!=null?Wg:"Attach file",kr=w("div","persona-send-button-tooltip");kr.textContent=tn,Te.appendChild(kr),Rt.append(Te),!Wt&&ue&&pt&&(Wt=va.fromConfig(oe),Wt.setPreviewsContainer(pt),ue.addEventListener("change",async()=>{Wt&&(ue!=null&&ue.files)&&(await Wt.handleFileSelect(ue.files),ue.value="")})),G.querySelector(".persona-attachment-drop-overlay")||G.appendChild(Oy(oe.dropOverlay))}else{Te.style.display="";let oe=(Hg=n.attachments)!=null?Hg:{};ue&&(ue.accept=((Bg=oe.allowedTypes)!=null?Bg:So).join(","),ue.multiple=((Dg=oe.maxFiles)!=null?Dg:4)>1),Wt&&Wt.updateConfig({allowedTypes:oe.allowedTypes,maxFileSize:oe.maxFileSize,maxFiles:oe.maxFiles})}else Te&&(Te.style.display="none"),Wt&&Wt.clearAttachments(),(Og=G.querySelector(".persona-attachment-drop-overlay"))==null||Og.remove();let yr=(Ng=n.sendButton)!=null?Ng:{},aa=(_g=yr.useIcon)!=null?_g:!1,$o=(Fg=yr.iconText)!=null?Fg:"\u2191",Uo=yr.iconName,yo=($g=yr.tooltipText)!=null?$g:"Send message",bt=(Ug=yr.showTooltip)!=null?Ug:!1,$r=(qg=yr.size)!=null?qg:"40px",Zr=yr.backgroundColor,Pr=yr.textColor;if(aa){if(J.style.width=$r,J.style.height=$r,J.style.minWidth=$r,J.style.minHeight=$r,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",Pr?J.style.color=Pr:J.style.color="var(--persona-button-primary-fg, #ffffff)",Uo){let oe=parseFloat($r)||24,qt=(Pr==null?void 0:Pr.trim())||"currentColor",ir=Ie(Uo,oe,qt,2);ir?J.appendChild(ir):J.textContent=$o}else J.textContent=$o;J.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Zr?(J.style.backgroundColor=Zr,J.classList.remove("persona-bg-persona-primary")):(J.style.backgroundColor="",J.classList.add("persona-bg-persona-primary"))}else J.textContent=(Vg=(zg=n.copy)==null?void 0:zg.sendButtonLabel)!=null?Vg:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.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",Zr?(J.style.backgroundColor=Zr,J.classList.remove("persona-bg-persona-accent")):J.classList.add("persona-bg-persona-accent"),Pr?J.style.color=Pr:J.classList.add("persona-text-white");yr.borderWidth?(J.style.borderWidth=yr.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),yr.borderColor?J.style.borderColor=yr.borderColor:J.style.borderColor="",yr.paddingX?(J.style.paddingLeft=yr.paddingX,J.style.paddingRight=yr.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),yr.paddingY?(J.style.paddingTop=yr.paddingY,J.style.paddingBottom=yr.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Mt=qe==null?void 0:qe.querySelector(".persona-send-button-tooltip");if(bt&&yo)if(Mt)Mt.textContent=yo,Mt.style.display="";else{let oe=document.createElement("div");oe.className="persona-send-button-tooltip",oe.textContent=yo,qe==null||qe.insertBefore(oe,J)}else Mt&&(Mt.style.display="none");let Bt=(Jg=(jg=n.layout)==null?void 0:jg.contentMaxWidth)!=null?Jg:W()?(Xg=(Kg=(Gg=n.launcher)==null?void 0:Gg.composerBar)==null?void 0:Kg.contentMaxWidth)!=null?Xg:"720px":void 0;Bt?(K.style.maxWidth=Bt,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",se&&(se.style.maxWidth=Bt,se.style.marginLeft="auto",se.style.marginRight="auto"),wt&&(wt.style.maxWidth=Bt,wt.style.marginLeft="auto",wt.style.marginRight="auto")):(K.style.maxWidth="",K.style.marginLeft="",K.style.marginRight="",K.style.width="",se&&(se.style.maxWidth="",se.style.marginLeft="",se.style.marginRight=""),wt&&(wt.style.maxWidth="",wt.style.marginLeft="",wt.style.marginRight=""));let kt=(Qg=n.statusIndicator)!=null?Qg:{},pn=(Yg=kt.visible)!=null?Yg:!0;if(ie.style.display=pn?"":"none",q){let oe=q.getStatus();mt(ie,(ir=>{var Et,Gt,Nr,Xr;return ir==="idle"?(Et=kt.idleText)!=null?Et:Jr.idle:ir==="connecting"?(Gt=kt.connectingText)!=null?Gt:Jr.connecting:ir==="connected"?(Nr=kt.connectedText)!=null?Nr:Jr.connected:ir==="error"?(Xr=kt.errorText)!=null?Xr:Jr.error:Jr[ir]})(oe),kt,oe)}ie.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Wr=kt.align==="left"?"persona-text-left":kt.align==="center"?"persona-text-center":"persona-text-right";ie.classList.add(Wr)},open(){P()&&Yt(!0,"api")},close(){P()&&Yt(!1,"api")},toggle(){P()&&Yt(!R,"api")},clearChat(){fr=!1,q.clearMessages(),fo.clear(),to();try{localStorage.removeItem(ds),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ds}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ds)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(),we==null||we.clear(),Q==null||Q.reset(),X==null||X.update()},setMessage(c){return!U||q.isStreaming()?!1:(!R&&P()&&Yt(!0,"system"),U.value=c,U.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||U.value.trim();return g?(!R&&P()&&Yt(!0,"system"),U.value="",U.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return q.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(q.isVoiceActive()||(!R&&P()&&Yt(!0,"system"),Ot.manuallyDeactivated=!1,dn(),q.toggleVoice().then(()=>{Ot.active=q.isVoiceActive(),Rn("user"),q.isVoiceActive()&&Ts()})),!0):At?!0:Kr()?(!R&&P()&&Yt(!0,"system"),Ot.manuallyDeactivated=!1,dn(),Or("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(()=>{Ot.active=!1,Ot.manuallyDeactivated=!0,dn(),Rn("user"),_o()}),!0):!1:At?(Ot.manuallyDeactivated=!0,dn(),sr("user"),!0):!1},injectMessage(c){return!R&&P()&&Yt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!R&&P()&&Yt(!0,"system");let g=q.injectAssistantMessage(c);return N&&(N=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!R&&P()&&Yt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!R&&P()&&Yt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!R&&P()&&Yt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!R&&P()&&Yt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!R&&P()&&Yt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){we&&(Q==null||Q.processEvent(c.type,c.payload),we.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ne||!we||kn()},hideEventStream(){fe&&ln()},isEventStreamVisible(){return fe},showArtifacts(){Fn(n)&&(fr=!1,gn(),st==null||st.setMobileOpen(!0))},hideArtifacts(){Fn(n)&&(fr=!0,gn())},upsertArtifact(c){return Fn(n)?(fr=!1,q.upsertArtifact(c)):null},selectArtifact(c){Fn(n)&&q.selectArtifact(c)},clearArtifacts(){Fn(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 k&&!R&&!W()||!U?!1:(U.focus(),!0)},async resolveApproval(c,g,b){let H=q.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.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 s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return P()&&R},isVoiceActive(){return Ot.active},getState(){return{open:P()&&R,launcherEnabled:k,voiceActive:Ot.active,streaming:q.isStreaming()}},showCSATFeedback(c){!R&&P()&&Yt(!0,"system");let g=K.querySelector(".persona-feedback-container");g&&g.remove();let b=ld({onSubmit:async(A,H)=>{var F;q.isClientTokenMode()&&await q.submitCSATFeedback(A,H),(F=c==null?void 0:c.onSubmit)==null||F.call(c,A,H)},onDismiss:c==null?void 0:c.onDismiss,...c});K.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&P()&&Yt(!0,"system");let g=K.querySelector(".persona-feedback-container");g&&g.remove();let b=dd({onSubmit:async(A,H)=>{var F;q.isClientTokenMode()&&await q.submitNPSFeedback(A,H),(F=c==null?void 0:c.onSubmit)==null||F.call(c,A,H)},onDismiss:c==null?void 0:c.onDismiss,...c});K.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(){Wn!=null&&(clearInterval(Wn),Wn=null),Ht.forEach(c=>c()),Re.remove(),ot==null||ot.remove(),Tr==null||Tr.destroy(),Mr==null||Mr.remove(),In&&B.removeEventListener("click",In)}};if((((Kf=r==null?void 0:r.debugTools)!=null?Kf:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Ir,getMessages:Ir.getMessages,getStatus:Ir.getStatus,getMetadata:Ir.getPersistentMetadata,updateMetadata:Ir.updatePersistentMetadata,clearHistory:()=>Ir.clearChat(),setVoiceActive:b=>b?Ir.startVoiceRecognition():Ir.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ht.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=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Ir.focusInput()};if(window.addEventListener("persona:focusInput",g),Ht.push(()=>{window.removeEventListener("persona:focusInput",g)}),Ne){let V=ke=>{let ve=ke.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===c)&&Ir.showEventStream()},_=ke=>{let ve=ke.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===c)&&Ir.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",_),Ht.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",_)})}let b=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Ir.showArtifacts()},A=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Ir.hideArtifacts()},H=V=>{let _=V.detail;_!=null&&_.instanceId&&_.instanceId!==c||_!=null&&_.artifact&&Ir.upsertArtifact(_.artifact)},F=V=>{let _=V.detail;_!=null&&_.instanceId&&_.instanceId!==c||typeof(_==null?void 0:_.id)=="string"&&Ir.selectArtifact(_.id)},$=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&Ir.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",H),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),Ht.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",H),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let Hn=eA(n.persistState);if(Hn&&P()){let c=tA(Hn.storage),g=`${Hn.keyPrefix}widget-open`,b=`${Hn.keyPrefix}widget-voice`,A=`${Hn.keyPrefix}widget-voice-mode`;if(c){let H=((Xf=Hn.persist)==null?void 0:Xf.openState)&&c.getItem(g)==="true",F=((Jf=Hn.persist)==null?void 0:Jf.voiceState)&&c.getItem(b)==="true",$=((Qf=Hn.persist)==null?void 0:Qf.voiceState)&&c.getItem(A)==="true";if(H&&setTimeout(()=>{Ir.open(),setTimeout(()=>{var V;if(F||$)Ir.startVoiceRecognition();else if((V=Hn.persist)!=null&&V.focusInput){let _=t.querySelector("textarea");_&&_.focus()}},100)},0),(Yf=Hn.persist)!=null&&Yf.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Zf=Hn.persist)!=null&&Zf.voiceState&&(s.on("voice:state",V=>{c.setItem(b,V.active?"true":"false")}),s.on("user:message",V=>{c.setItem(A,V.viaVoice?"true":"false")})),Hn.clearOnChatClear){let V=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(A)},_=()=>V();window.addEventListener("persona:clear-chat",_),Ht.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return p&&P()&&setTimeout(()=>{Ir.open()},0),xo(),Ir};var rA=(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},Ny=(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"},Lu=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=""},_y=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.minWidth="",Lu(t)},Mu=t=>{t.style.transition=""},ku=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=""},Eu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},ud=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},nA=(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))},oA=(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,k,E,M;let i=Nn(s),d=i.reveal==="push";nA(t,e,r,n,d),oA(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=(k=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?k:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),ku(e),Mu(n),_y(n),Eu(r),ud(o,n),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((M=(E=s==null?void 0:s.launcher)==null?void 0:E.zIndex)!=null?M:Qr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),_y(n),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",ku(e),Mu(n),Eu(r),ud(o,n);let h=i.animate?"transform 180ms ease":"none",C=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=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=v,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",Mu(n),Lu(n),ud(o,n);let h=rA(i.width,t.clientWidth),C=Math.max(0,t.clientWidth),v=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${h}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${h}px)`;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${C+h}px`,e.style.transition=v,e.style.transform=T,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="",ku(e),Lu(n),Eu(r),ud(o,n);let h=i.reveal==="emerge";h?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let C=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${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||T?"hidden":"visible",n.style.transition=v,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")}},aA=(t,e)=>{let r=t.ownerDocument.createElement("div");return Ny(r,e),t.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(n){Ny(r,n)},destroy(){r.remove()}}},sA=(t,e)=>{var E,M,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=(M=(E=e==null?void 0:e.launcher)==null?void 0:E.enabled)==null||M?(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(),Nn(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,k=()=>{x()};return S==null||S.addEventListener("resize",k),Nn(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(v){let T=v.launcherEnabled?v.open:!0;u!==T&&(u=T,x())},updateConfig(v){var T,W;e=v,((W=(T=e==null?void 0:e.launcher)==null?void 0:T.enabled)!=null?W:!0)===!1&&(u=!0),x()},destroy(){S==null||S.removeEventListener("resize",k),m(),n.isConnected&&(s&&s.parentNode===n?n.insertBefore(t,s):n.appendChild(t)),a.remove()}}},fi=(t,e)=>Br(e)?sA(t,e):aA(t,e);var Pu={},$y=!1,iA=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},lA=()=>{try{if(typeof Pu!="undefined"&&Pu.url)return new URL("../widget.css",Pu.url).href}catch{}return null},Uy=(t,e)=>{let r=lA(),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)}},qy=t=>{let e=iA(t.target),r=t.useShadowDom===!0,n=e.ownerDocument,o=t.config,s=fi(e,o),a,i=[],d=(S,k)=>{var C,v;let M=!((v=(C=k==null?void 0:k.launcher)==null?void 0:C.enabled)!=null?v:!0)||Br(k),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),M&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),r){let T=S.attachShadow({mode:"open"});T.appendChild(h),Uy(T,n)}else S.appendChild(h),Uy(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=pd(S,o,{debugTools:t.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};u(),t.onChatReady?t.onChatReady():t.onReady&&($y||($y=!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=fi(e,S),o=S,u()},y={update(S){var v,T,W,P,R,N;let k={...o,...S,launcher:{...(v=o==null?void 0:o.launcher)!=null?v:{},...(T=S==null?void 0:S.launcher)!=null?T:{},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:{}}}},E=Br(o),M=Br(k),h=Go(o),C=Go(k);if(E!==M||h!==C){m(k);return}o=k,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,k,E){if(k==="host")return s.host;if(k in S)return Reflect.get(S,k,E);let M=a[k];return typeof M=="function"?M.bind(a):M}});return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=x),x};var Ky=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),dA=new Set(["button","a","input","select","textarea","details","summary"]),cA=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Iu=/\b(product|card|item|listing|result)\b/i,Wu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,pA=3e3,uA=100;function Xy(t){let e=typeof t.className=="string"?t.className:"";if(Iu.test(e)||t.id&&Iu.test(t.id))return!0;for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];if(n.name.startsWith("data-")&&Iu.test(n.value))return!0}return!1}function Jy(t){var e;return Wu.test(((e=t.textContent)!=null?e:"").trim())}function Qy(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 fA(t){return!!t.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function zy(t){let e=t.match(Wu);return e?e[0]:null}function Vy(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 mA(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 gA="commerce-card",hA="result-card";function jy(t){return!Xy(t)||!Jy(t)||!Qy(t)&&!fA(t)?0:5200}function Gy(t){var n;return!Xy(t)||Jy(t)||!Qy(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 Hu=[{id:gA,scoreElement(t){return jy(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||Wu.test(n)&&n.length<32)}return!0},formatSummary(t,e){var d,l,p;if(jy(t)===0)return null;let{title:r,href:n}=Vy(t),o=(p=(l=zy(((d=t.textContent)!=null?d:"").trim()))!=null?l:zy(e.text))!=null?p:"",s=mA(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:hA,scoreElement(t){return Gy(t)},formatSummary(t,e){if(Gy(t)===0)return null;let{title:r,href:n}=Vy(t);return[n&&r?`[${r}](${n})`:r||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
159
+ `)}}];function xA(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function yA(t){var p,u,f,m,y,x,S,k,E,M,h,C,v;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=(E=(k=e.visibleOnly)!=null?k:t.visibleOnly)!=null?E:!0,a=(M=e.root)!=null?M:t.root,i=(h=e.mode)!=null?h:"structured",d=(C=e.maxCandidates)!=null?C:Math.max(500,r*10),l=(v=t.rules)!=null?v:Hu;return i==="simple"&&t.rules&&t.rules.length>0?(xA(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Ru(t){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/([^\w-])/g,"\\$1")}var bA=["data-testid","data-product","data-action","data-id","data-name","data-type"];function wA(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"||dA.has(e)||r&&cA.has(r)||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||t.getAttribute("contenteditable")==="true"?"clickable":"static"}function Yy(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 vA(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 Bu(t){let e=t.tagName.toLowerCase();if(t.id){let o=`#${Ru(t.id)}`;try{if(t.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of bA){let s=t.getAttribute(o);if(s){let a=`${e}[${o}="${Ru(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=>Ru(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 CA(t){return t==="static"?uA:pA}function Zy(t,e){var o;let r=t.tagName.toLowerCase(),n=((o=t.textContent)!=null?o:"").trim().substring(0,e);return{selector:Bu(t),tagName:r,text:n,role:t.getAttribute("role"),interactivity:wA(t),attributes:vA(t)}}function AA(t,e,r,n){let o=CA(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 SA(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 TA(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(Ky.has(p)){i=a.nextNode();continue}if(t.excludeSelector)try{if(l.closest(t.excludeSelector)){i=a.nextNode();continue}}catch{}if(t.visibleOnly&&!Yy(l)){i=a.nextNode();continue}let u=Zy(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}=AA(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;SA(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 MA(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(Ky.has(l)){s=o.nextNode();continue}if(t.excludeSelector)try{if(d.closest(t.excludeSelector)){s=o.nextNode();continue}}catch{}if(t.visibleOnly&&!Yy(d)){s=o.nextNode();continue}let p=Zy(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 eb(t={}){var n;let e=yA(t),r=(n=e.root)!=null?n:document.body;return r?e.mode==="simple"?MA(e,r):TA(e,r):[]}var fd=100;function tb(t,e={}){var s;if(t.length===0)return"No page elements found.";let r=(s=e.mode)!=null?s:"structured",n=[];if(r==="structured"){let a=t.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
160
160
  ${a.map(i=>`- ${i.split(`
161
161
  `).join(`
162
162
  `)}`).join(`
163
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of t)r==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,rd)}" (clickable)`);n.push(`Interactive elements:
163
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of t)r==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,fd)}" (clickable)`);n.push(`Interactive elements:
164
164
  ${a.join(`
165
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,rd)}" (navigable)`);n.push(`Navigation links:
165
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,fd)}" (navigable)`);n.push(`Navigation links:
166
166
  ${a.join(`
167
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,rd)}" (input)`);n.push(`Form inputs:
167
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,fd)}" (input)`);n.push(`Form inputs:
168
168
  ${a.join(`
169
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,rd)}"`);n.push(`Content:
169
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,fd)}"`);n.push(`Content:
170
170
  ${a.join(`
171
171
  `)}`)}return n.join(`
172
172
 
173
- `)}var wy={name:"@runtypelabs/persona",version:"3.29.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:launcher && pnpm run build:theme-ref && pnpm run build:codegen && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:codegen":"tsup src/codegen.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var vy=wy.version;function Cy(){return{name:"@persona/accessibility",version:"1.0.0",transform(t){return{...t,semantic:{...t.semantic,colors:{...t.semantic.colors,interactive:{...t.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Ay(){return{name:"@persona/animations",version:"1.0.0",transform(t){return{...t,palette:{...t.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Sy(t){return{name:"@persona/brand",version:"1.0.0",transform(e){var n;let r={...e.palette};return(n=t.colors)!=null&&n.primary&&(r.colors={...r.colors,primary:{50:Yn(t.colors.primary,.95),100:Yn(t.colors.primary,.9),200:Yn(t.colors.primary,.8),300:Yn(t.colors.primary,.7),400:Yn(t.colors.primary,.6),500:t.colors.primary,600:Yn(t.colors.primary,.8),700:Yn(t.colors.primary,.7),800:Yn(t.colors.primary,.6),900:Yn(t.colors.primary,.5),950:Yn(t.colors.primary,.45)}}),{...e,palette:r}}}}function Ty(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(t){return{...t,palette:{...t.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(t){return{...t,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function My(){return{name:"@persona/high-contrast",version:"1.0.0",transform(t){return{...t,semantic:{...t.semantic,colors:{...t.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Yn(t,e){let r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16),s=Math.round(r+(255-r)*(1-e)),a=Math.round(n+(255-n)*(1-e)),i=Math.round(o+(255-o)*(1-e));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function ky(t){return{name:t.name,version:t.version,transform:t.transform||(e=>e),cssVariables:t.cssVariables,afterResolve:t.afterResolve}}var FC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Ey={components:{panel:{borderRadius:"0",shadow:"none"}}},Cu={id:"shop",label:"Shopping Assistant",config:{theme:FC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:yn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Au={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ey}},Su={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ey}},Tu={shop:Cu,minimal:Au,fullscreen:Su};function Ly(t){return Tu[t]}var $C=`
173
+ `)}var rb={name:"@runtypelabs/persona",version:"3.31.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 nb=rb.version;function ob(){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 ab(){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 sb(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:co(t.colors.primary,.95),100:co(t.colors.primary,.9),200:co(t.colors.primary,.8),300:co(t.colors.primary,.7),400:co(t.colors.primary,.6),500:t.colors.primary,600:co(t.colors.primary,.8),700:co(t.colors.primary,.7),800:co(t.colors.primary,.6),900:co(t.colors.primary,.5),950:co(t.colors.primary,.45)}}),{...e,palette:r}}}}function ib(){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 lb(){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 co(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 db(t){return{name:t.name,version:t.version,transform:t.transform||(e=>e),cssVariables:t.cssVariables,afterResolve:t.afterResolve}}var EA={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"}}},cb={components:{panel:{borderRadius:"0",shadow:"none"}}},Du={id:"shop",label:"Shopping Assistant",config:{theme:EA,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Tn},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?"]}},Ou={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:cb}},Nu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:cb}},_u={shop:Du,minimal:Ou,fullscreen:Nu};function pb(t){return _u[t]}var LA=`
174
174
  @keyframes persona-stream-wipe {
175
175
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
176
176
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -206,7 +206,7 @@ ${a.join(`
206
206
  mask-image: none !important;
207
207
  }
208
208
  }
209
- `.trim(),UC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:$C};pa(UC);var qC=`
209
+ `.trim(),PA={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:LA};Aa(PA);var IA=`
210
210
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
211
211
  animation: persona-stream-glyph-cycle-fade
212
212
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -224,7 +224,7 @@ ${a.join(`
224
224
  opacity: 1 !important;
225
225
  }
226
226
  }
227
- `.trim(),ri="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",zC=10,VC=120,Mu=120,jC=.4,GC=50,KC=t=>{var n;if(!t)return Mu;let r=((n=t.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Mu},Oy=t=>{let e=t.closest(".persona-stream-glyph-cycle"),r=KC(e);return VC*r/Mu},ku=t=>{let e=ri[Math.floor(Math.random()*ri.length)];return t&&e===t&&(e=ri[(ri.indexOf(e)+1)%ri.length]),e},XC=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let r=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let o of Array.from(r)){if(o===t){n=!0;continue}n&&Math.random()<jC&&(o.textContent=ku())}},Py=new WeakMap,Iy=25,Ry=.5,JC=6,Wy=.25,By=new WeakMap,Hy=new WeakMap,QC=(t,e)=>{var o;if(!t)return Iy*Ry;let r=By.get(t);By.set(t,e);let n=(o=Hy.get(t))!=null?o:Iy;if(r!==void 0){let s=e-r;s>1&&(n=n*(1-Wy)+s*Wy,Hy.set(t,n))}return Math.max(JC,n*Ry)},Xa=new Map,YC=t=>{var r;let e=t.closest("[data-message-id]");return(r=e==null?void 0:e.dataset.messageId)!=null?r:null},ZC=t=>{var e;t&&Xa.set(t,((e=Xa.get(t))!=null?e:0)+1)},eA=t=>{var r;if(!t)return;let e=(r=Xa.get(t))!=null?r:0;e<=1?Xa.delete(t):Xa.set(t,e-1)},Ny=t=>{var l;if(t.dataset.glyphCycleScheduled==="true")return;let e=(l=t.textContent)!=null?l:"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=ku();let r=YC(t);r&&(t.dataset.glyphCycleMessageId=r),ZC(r);let n=t.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=QC(n,o),a=Oy(t),i=zC*a,d=o+i;if(n){let p=Py.get(n);p!==void 0&&(d=Math.max(d,p)),Py.set(n,d+s)}tA(t,e,d)},tA=(t,e,r)=>{var a;if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let n=Oy(t),o=(a=t.textContent)!=null?a:void 0,s=()=>{var d;if(!t.isConnected)return;if(Date.now()>=r){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,eA((d=t.dataset.glyphCycleMessageId)!=null?d:null),delete t.dataset.glyphCycleMessageId;return}let i=ku(o);t.textContent=i,o=i,XC(t),setTimeout(s,n)};setTimeout(s,n)},Dy=t=>{var r;let e=(r=t.querySelectorAll)==null?void 0:r.call(t,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))Ny(n)},rA=t=>t.nodeType===1,nA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:qC,bufferContent(t){if(t.length<GC)return"";let e=0,r=-1,n=0;for(;n<t.length;){if(t[n]==="*"&&t[n+1]==="*"){e+=1,n+=2;continue}/\s/.test(t[n])&&e%2===0&&(r=n),n+=1}return r<0?"":t.slice(0,r)},isAnimating(t){var e;return((e=Xa.get(t.id))!=null?e:0)>0},onAttach(t){Dy(t);let e=new MutationObserver(r=>{for(let n of r)for(let o of Array.from(n.addedNodes))rA(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?Ny(o):Dy(o))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};pa(nA);return Vy(oA);})();
227
+ `.trim(),mi="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",RA=10,WA=120,Fu=120,HA=.4,BA=50,DA=t=>{var n;if(!t)return Fu;let r=((n=t.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Fu},bb=t=>{let e=t.closest(".persona-stream-glyph-cycle"),r=DA(e);return WA*r/Fu},$u=t=>{let e=mi[Math.floor(Math.random()*mi.length)];return t&&e===t&&(e=mi[(mi.indexOf(e)+1)%mi.length]),e},OA=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()<HA&&(o.textContent=$u())}},ub=new WeakMap,fb=25,mb=.5,NA=6,gb=.25,hb=new WeakMap,xb=new WeakMap,_A=(t,e)=>{var o;if(!t)return fb*mb;let r=hb.get(t);hb.set(t,e);let n=(o=xb.get(t))!=null?o:fb;if(r!==void 0){let s=e-r;s>1&&(n=n*(1-gb)+s*gb,xb.set(t,n))}return Math.max(NA,n*mb)},cs=new Map,FA=t=>{var r;let e=t.closest("[data-message-id]");return(r=e==null?void 0:e.dataset.messageId)!=null?r:null},$A=t=>{var e;t&&cs.set(t,((e=cs.get(t))!=null?e:0)+1)},UA=t=>{var r;if(!t)return;let e=(r=cs.get(t))!=null?r:0;e<=1?cs.delete(t):cs.set(t,e-1)},wb=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=$u();let r=FA(t);r&&(t.dataset.glyphCycleMessageId=r),$A(r);let n=t.closest(".persona-stream-glyph-cycle"),o=Date.now(),s=_A(n,o),a=bb(t),i=RA*a,d=o+i;if(n){let p=ub.get(n);p!==void 0&&(d=Math.max(d,p)),ub.set(n,d+s)}qA(t,e,d)},qA=(t,e,r)=>{var a;if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let n=bb(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,UA((d=t.dataset.glyphCycleMessageId)!=null?d:null),delete t.dataset.glyphCycleMessageId;return}let i=$u(o);t.textContent=i,o=i,OA(t),setTimeout(s,n)};setTimeout(s,n)},yb=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))wb(n)},zA=t=>t.nodeType===1,VA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:IA,bufferContent(t){if(t.length<BA)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=cs.get(t.id))!=null?e:0)>0},onAttach(t){yb(t);let e=new MutationObserver(r=>{for(let n of r)for(let o of Array.from(n.addedNodes))zA(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?wb(o):yb(o))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};Aa(VA);return Rb(jA);})();
228
228
  /*! Bundled license information:
229
229
 
230
230
  dompurify/dist/purify.es.mjs: