@runtypelabs/persona 3.31.0 → 3.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-quh7NmYD.d.cts → types-CthJFfNx.d.cts} +7 -0
- package/dist/animations/{types-quh7NmYD.d.ts → types-CthJFfNx.d.ts} +7 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +3 -3
- package/dist/index.cjs +43 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +288 -8
- package/dist/index.d.ts +288 -8
- package/dist/index.global.js +76 -79
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +43 -43
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +78 -2
- package/dist/smart-dom-reader.d.ts +78 -2
- package/dist/theme-editor.cjs +30 -30
- package/dist/theme-editor.d.cts +92 -5
- package/dist/theme-editor.d.ts +92 -5
- package/dist/theme-editor.js +30 -30
- package/dist/webmcp-polyfill.js +4 -0
- package/package.json +4 -3
- package/src/ask-user-question-tool.test.ts +148 -0
- package/src/ask-user-question-tool.ts +138 -0
- package/src/client.ts +43 -9
- package/src/components/messages.ts +10 -0
- package/src/components/suggestions.ts +49 -6
- package/src/index-core.ts +15 -0
- package/src/index-global.ts +39 -0
- package/src/runtime/host-layout.test.ts +158 -3
- package/src/runtime/host-layout.ts +95 -1
- package/src/session.ts +188 -32
- package/src/session.webmcp.test.ts +48 -0
- package/src/suggest-replies-tool.test.ts +445 -0
- package/src/suggest-replies-tool.ts +152 -0
- package/src/theme-editor/index.ts +2 -0
- package/src/theme-editor/webmcp/index.ts +2 -0
- package/src/theme-editor/webmcp/types.ts +16 -3
- package/src/types.ts +79 -2
- package/src/ui.suggest-replies.test.ts +237 -0
- package/src/ui.ts +57 -13
- package/src/utils/dock.test.ts +23 -1
- package/src/utils/dock.ts +2 -0
- package/src/version.ts +5 -2
- package/src/webmcp-bridge.test.ts +60 -0
- package/src/webmcp-bridge.ts +34 -1
- package/src/webmcp-polyfill.ts +16 -0
package/dist/index.global.js
CHANGED
|
@@ -1,68 +1,65 @@
|
|
|
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
|
-
|
|
3
|
-
|
|
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
|
-
|
|
6
|
-
`)
|
|
7
|
-
`)
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`,1)[0].replace(
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
`,1)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`)
|
|
19
|
-
|
|
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
|
-
`),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,s,a;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=`
|
|
22
|
-
`:r.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=r[r.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var ey=Object.create;var Ss=Object.defineProperty;var ty=Object.getOwnPropertyDescriptor;var ry=Object.getOwnPropertyNames;var ny=Object.getPrototypeOf,oy=Object.prototype.hasOwnProperty;var Ug=r=>{throw TypeError(r)};var ay=(r,e,t)=>e in r?Ss(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var sy=(r=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(r,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):r)(function(r){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var qg=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),iy=(r,e)=>{for(var t in e)Ss(r,t,{get:e[t],enumerable:!0})},zg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ry(e))!oy.call(r,o)&&o!==t&&Ss(r,o,{get:()=>e[o],enumerable:!(n=ty(e,o))||n.enumerable});return r};var Li=(r,e,t)=>(t=r!=null?ey(ny(r)):{},zg(e||!r||!r.__esModule?Ss(t,"default",{value:r,enumerable:!0}):t,r)),ly=r=>zg(Ss({},"__esModule",{value:!0}),r);var cr=(r,e,t)=>ay(r,typeof e!="symbol"?e+"":e,t),dy=(r,e,t)=>e.has(r)||Ug("Cannot "+t);var $g=(r,e,t)=>e.has(r)?Ug("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t);var Pi=(r,e,t)=>(dy(r,e,"access private method"),t);var Id=qg(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.Allow=ze.ALL=ze.COLLECTION=ze.ATOM=ze.SPECIAL=ze.INF=ze._INFINITY=ze.INFINITY=ze.NAN=ze.BOOL=ze.NULL=ze.OBJ=ze.ARR=ze.NUM=ze.STR=void 0;ze.STR=1;ze.NUM=2;ze.ARR=4;ze.OBJ=8;ze.NULL=16;ze.BOOL=32;ze.NAN=64;ze.INFINITY=128;ze._INFINITY=256;ze.INF=ze.INFINITY|ze._INFINITY;ze.SPECIAL=ze.NULL|ze.BOOL|ze.INF|ze.NAN;ze.ATOM=ze.STR|ze.NUM|ze.SPECIAL;ze.COLLECTION=ze.ARR|ze.OBJ;ze.ALL=ze.ATOM|ze.COLLECTION;ze.Allow={STR:ze.STR,NUM:ze.NUM,ARR:ze.ARR,OBJ:ze.OBJ,NULL:ze.NULL,BOOL:ze.BOOL,NAN:ze.NAN,INFINITY:ze.INFINITY,_INFINITY:ze._INFINITY,INF:ze.INF,SPECIAL:ze.SPECIAL,ATOM:ze.ATOM,COLLECTION:ze.COLLECTION,ALL:ze.ALL};ze.default=ze.Allow});var zi=qg(Ur=>{"use strict";var A0=Ur&&Ur.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),S0=Ur&&Ur.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&A0(e,r,t)};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.Allow=Ur.MalformedJSON=Ur.PartialJSON=Ur.parseJSON=Ur.parse=void 0;var on=Id();Object.defineProperty(Ur,"Allow",{enumerable:!0,get:function(){return on.Allow}});S0(Id(),Ur);var Ui=class extends Error{};Ur.PartialJSON=Ui;var qi=class extends Error{};Ur.MalformedJSON=qi;function Lh(r,e=on.Allow.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return T0(r.trim(),e)}Ur.parseJSON=Lh;var T0=(r,e)=>{let t=r.length,n=0,o=p=>{throw new Ui(`${p} at position ${n}`)},a=p=>{throw new qi(`${p} at position ${n}`)},s=()=>(m(),n>=t&&o("Unexpected end of input"),r[n]==='"'?i():r[n]==="{"?d():r[n]==="["?l():r.substring(n,n+4)==="null"||on.Allow.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||on.Allow.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||on.Allow.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||on.Allow.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||on.Allow._INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||on.Allow.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):u()),i=()=>{let p=n,f=!1;for(n++;n<t&&(r[n]!=='"'||f&&r[n-1]==="\\");)f=r[n]==="\\"?!f:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(p,++n-Number(f)))}catch(b){a(String(b))}else if(on.Allow.STR&e)try{return JSON.parse(r.substring(p,n-Number(f))+'"')}catch{return JSON.parse(r.substring(p,r.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,m();let p={};try{for(;r[n]!=="}";){if(m(),n>=t&&on.Allow.OBJ&e)return p;let f=i();m(),n++;try{let b=s();p[f]=b}catch(b){if(on.Allow.OBJ&e)return p;throw b}m(),r[n]===","&&n++}}catch{if(on.Allow.OBJ&e)return p;o("Expected '}' at end of object")}return n++,p},l=()=>{n++;let p=[];try{for(;r[n]!=="]";)p.push(s()),m(),r[n]===","&&n++}catch{if(on.Allow.ARR&e)return p;o("Expected ']' at end of array")}return n++,p},u=()=>{if(n===0){r==="-"&&a("Not sure what '-' is");try{return JSON.parse(r)}catch(f){if(on.Allow.NUM&e)try{return JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}a(String(f))}}let p=n;for(r[n]==="-"&&n++;r[n]&&",]}".indexOf(r[n])===-1;)n++;n==t&&!(on.Allow.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(r.substring(p,n))}catch{r.substring(p,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(r.substring(p,r.lastIndexOf("e")))}catch(b){a(String(b))}}},m=()=>{for(;n<t&&`
|
|
2
|
+
\r `.includes(r[n]);)n++};return s()},M0=Lh;Ur.parse=M0});var Lw={};iy(Lw,{ASK_USER_QUESTION_CLIENT_TOOL:()=>qd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Ud,ASK_USER_QUESTION_TOOL_NAME:()=>Os,AgentWidgetClient:()=>ua,AgentWidgetSession:()=>ja,AttachmentManager:()=>ha,DEFAULT_COMPONENTS:()=>qp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Cl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>An,DEFAULT_PALETTE:()=>_p,DEFAULT_SEMANTIC:()=>Up,DEFAULT_WIDGET_CONFIG:()=>Kt,PRESETS:()=>ku,PRESET_FULLSCREEN:()=>Mu,PRESET_MINIMAL:()=>Tu,PRESET_SHOP:()=>Su,SUGGEST_REPLIES_CLIENT_TOOL:()=>Gi,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Od,SUGGEST_REPLIES_TOOL_NAME:()=>Vn,THEME_ZONES:()=>ux,VERSION:()=>Eb,WEBMCP_TOOL_PREFIX:()=>go,WebMcpBridge:()=>_a,accessibilityPlugin:()=>Lb,animationsPlugin:()=>Pb,applyThemeVariables:()=>_o,attachHeaderToContainer:()=>ya,brandPlugin:()=>Rb,buildComposer:()=>Ja,buildDefaultHeader:()=>Yp,buildHeader:()=>Co,buildHeaderWithLayout:()=>Qa,buildMinimalHeader:()=>Zp,builtInClientToolsForDispatch:()=>Us,collectEnrichedPageContext:()=>Tb,componentRegistry:()=>wo,createActionManager:()=>ci,createAgentExperience:()=>nd,createAskUserQuestionBubble:()=>qh,createBestAvailableVoiceProvider:()=>dl,createBubbleWithLayout:()=>Wx,createCSATFeedback:()=>ed,createComboButton:()=>Dl,createComponentMiddleware:()=>ob,createComponentStreamParser:()=>Ql,createDefaultSanitizer:()=>Ed,createDirectivePostprocessor:()=>ch,createDropdownMenu:()=>$o,createFlexibleJsonStreamParser:()=>jh,createIconButton:()=>Dr,createImagePart:()=>Zh,createJsonStreamParser:()=>tl,createLabelButton:()=>oi,createLocalStorageAdapter:()=>Xl,createMarkdownProcessor:()=>Rs,createMarkdownProcessorFromConfig:()=>ia,createMessageActions:()=>ou,createNPSFeedback:()=>td,createPlainTextParser:()=>Zi,createPlugin:()=>Wb,createRegexJsonParser:()=>el,createStandardBubble:()=>Ya,createTextPart:()=>$s,createTheme:()=>Ka,createThemeObserver:()=>Tl,createToggleGroup:()=>kx,createTypingIndicator:()=>va,createVoiceProvider:()=>ga,createWidgetHostLayout:()=>pi,createXmlParser:()=>rl,defaultActionHandlers:()=>wa,defaultJsonActionParser:()=>di,defaultParseRules:()=>wu,detectColorScheme:()=>Xs,directivePostprocessor:()=>ph,ensureAskUserQuestionSheet:()=>za,escapeHtml:()=>la,extractComponentDirectiveFromMessage:()=>Zl,fileToImagePart:()=>ex,formatEnrichedContext:()=>Mb,generateAssistantMessageId:()=>fa,generateMessageId:()=>Kh,generateStableSelector:()=>Au,generateUserMessageId:()=>Va,getActiveTheme:()=>Xa,getColorScheme:()=>$p,getDisplayText:()=>Qh,getHeaderLayout:()=>eu,getImageParts:()=>Yh,getPreset:()=>Db,hasComponentDirective:()=>Yl,hasImages:()=>Jh,headerLayouts:()=>Fl,highContrastPlugin:()=>Hb,initAgentWidget:()=>mb,isAskUserQuestionMessage:()=>ho,isComponentDirectiveType:()=>nb,isDockedMountMode:()=>Pr,isSuggestRepliesMessage:()=>_s,isVoiceSupported:()=>js,isWebMcpToolName:()=>da,latestAgentSuggestions:()=>Ki,listRegisteredStreamAnimations:()=>Kp,markdownPostprocessor:()=>yd,mergeWithDefaults:()=>wl,normalizeContent:()=>Xh,parseAskUserQuestionPayload:()=>xo,parseSuggestRepliesPayload:()=>_d,pluginRegistry:()=>li,reducedMotionPlugin:()=>Ib,registerStreamAnimationPlugin:()=>ba,removeAskUserQuestionSheet:()=>Oo,renderComponentDirective:()=>Jl,renderLoadingIndicatorWithFallback:()=>nu,renderLucideIcon:()=>Me,resolveDockConfig:()=>Sn,resolveSanitizer:()=>Na,resolveTokens:()=>Al,stripWebMcpPrefix:()=>_i,themeToCssVariables:()=>Sl,unregisterStreamAnimationPlugin:()=>Gp,validateImageFile:()=>tx,validateTheme:()=>zp});function fd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var sa=fd();function Qg(r){sa=r}var Jg=/[&<>"']/,cy=new RegExp(Jg.source,"g"),Yg=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,py=new RegExp(Yg.source,"g"),uy={"&":"&","<":"<",">":">",'"':""","'":"'"},Vg=r=>uy[r];function Cn(r,e){if(e){if(Jg.test(r))return r.replace(cy,Vg)}else if(Yg.test(r))return r.replace(py,Vg);return r}var fy=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function my(r){return r.replace(fy,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}var gy=/(^|[^\[])\^/g;function nr(r,e){let t=typeof r=="string"?r:r.source;e=e||"";let n={replace:(o,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(gy,"$1"),t=t.replace(o,s),n},getRegex:()=>new RegExp(t,e)};return n}function jg(r){try{r=encodeURI(r).replace(/%25/g,"%")}catch{return null}return r}var Ms={exec:()=>null};function Gg(r,e){let t=r.replace(/\|/g,(a,s,i)=>{let d=!1,l=s;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=t.split(/ \|/),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function Ri(r,e,t){let n=r.length;if(n===0)return"";let o=0;for(;o<n;){let a=r.charAt(n-o-1);if(a===e&&!t)o++;else if(a!==e&&t)o++;else break}return r.slice(0,n-o)}function hy(r,e){if(r.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<r.length;n++)if(r[n]==="\\")n++;else if(r[n]===e[0])t++;else if(r[n]===e[1]&&(t--,t<0))return n;return-1}function Kg(r,e,t,n){let o=e.href,a=e.title?Cn(e.title):null,s=r[1].replace(/\\([\[\]])/g,"$1");if(r[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:t,href:o,title:a,text:s,tokens:n.inlineTokens(s)};return n.state.inLink=!1,i}return{type:"image",raw:t,href:o,title:a,text:Cn(s)}}function xy(r,e){let t=r.match(/^(\s+)(?:```)/);if(t===null)return e;let n=t[1];return e.split(`
|
|
3
|
+
`).map(o=>{let a=o.match(/^\s+/);if(a===null)return o;let[s]=a;return s.length>=n.length?o.slice(n.length):o}).join(`
|
|
4
|
+
`)}var Fa=class{constructor(e){cr(this,"options");cr(this,"rules");cr(this,"lexer");this.options=e||sa}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Ri(n,`
|
|
5
|
+
`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],o=xy(n,t[3]||"");return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:o}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(/#$/.test(n)){let o=Ri(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
|
|
6
|
+
$1`);n=Ri(n.replace(/^ *>[ \t]?/gm,""),`
|
|
7
|
+
`);let o=this.lexer.state.top;this.lexer.state.top=!0;let a=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:t[0],tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),o=n.length>1,a={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let s=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let u=!1;if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;i=t[0],e=e.substring(i.length);let m=t[2].split(`
|
|
8
|
+
`,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),p=e.split(`
|
|
9
|
+
`,1)[0],f=0;this.options.pedantic?(f=2,d=m.trimStart()):(f=t[2].search(/[^ ]/),f=f>4?1:f,d=m.slice(f),f+=t[1].length);let b=!1;if(!m&&/^ *$/.test(p)&&(i+=p+`
|
|
10
|
+
`,e=e.substring(p.length+1),u=!0),!u){let T=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),M=new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),k=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),x=new RegExp(`^ {0,${Math.min(3,f-1)}}#`);for(;e;){let C=e.split(`
|
|
11
|
+
`,1)[0];if(p=C,this.options.pedantic&&(p=p.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),k.test(p)||x.test(p)||T.test(p)||M.test(e))break;if(p.search(/[^ ]/)>=f||!p.trim())d+=`
|
|
12
|
+
`+p.slice(f);else{if(b||m.search(/[^ ]/)>=4||k.test(m)||x.test(m)||M.test(m))break;d+=`
|
|
13
|
+
`+p}!b&&!p.trim()&&(b=!0),i+=C+`
|
|
14
|
+
`,e=e.substring(C.length+1),m=p.slice(f)}}a.loose||(l?a.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let h=null,S;this.options.gfm&&(h=/^\[[ xX]\] /.exec(d),h&&(S=h[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),a.items.push({type:"list_item",raw:i,task:!!h,checked:S,loose:!1,text:d,tokens:[]}),a.raw+=i}a.items[a.items.length-1].raw=i.trimEnd(),a.items[a.items.length-1].text=d.trimEnd(),a.raw=a.raw.trimEnd();for(let u=0;u<a.items.length;u++)if(this.lexer.state.top=!1,a.items[u].tokens=this.lexer.blockTokens(a.items[u].text,[]),!a.loose){let m=a.items[u].tokens.filter(f=>f.type==="space"),p=m.length>0&&m.some(f=>/\n.*\n/.test(f.raw));a.loose=p}if(a.loose)for(let u=0;u<a.items.length;u++)a.items[u].loose=!0;return a}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(/\s+/g," "),o=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:a}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!/[:|]/.test(t[2]))return;let n=Gg(t[1]),o=t[2].replace(/^\||\| *$/g,"").split("|"),a=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(`
|
|
15
|
+
`):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let i of o)/^ *-+: *$/.test(i)?s.align.push("right"):/^ *:-+: *$/.test(i)?s.align.push("center"):/^ *:-+ *$/.test(i)?s.align.push("left"):s.align.push(null);for(let i of n)s.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of a)s.rows.push(Gg(i,s.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
|
|
16
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:Cn(t[1])}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let s=Ri(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=hy(t[2],"()");if(s>-1){let d=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,d).trim(),t[3]=""}}let o=t[2],a="";if(this.options.pedantic){let s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);s&&(o=s[1],a=s[3])}else a=t[3]?t[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(n)?o=o.slice(1):o=o.slice(1,-1)),Kg(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(/\s+/g," "),a=t[o.toLowerCase()];if(!a){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Kg(n,a,n[0],this.lexer)}}emStrong(e,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o||o[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(o[1]||o[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...o[0]].length-1,i,d,l=s,u=0,m=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,t=t.slice(-1*e.length+s);(o=m.exec(t))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&s%3&&!((s+d)%3)){u+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+u);let p=[...o[0]][0].length,f=e.slice(0,s+o.index+p+d);if(Math.min(s,d)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let b=f.slice(2,-2);return{type:"strong",raw:f,text:b,tokens:this.lexer.inlineTokens(b)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(/\n/g," "),o=/[^ ]/.test(n),a=/^ /.test(n)&&/ $/.test(n);return o&&a&&(n=n.substring(1,n.length-1)),n=Cn(n,!0),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,o;return t[2]==="@"?(n=Cn(t[1]),o="mailto:"+n):(n=Cn(t[1]),o=n),{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,o;let t;if(t=this.rules.inline.url.exec(e)){let a,s;if(t[2]==="@")a=Cn(t[0]),s="mailto:"+a;else{let i;do i=t[0],t[0]=(o=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?o:"";while(i!==t[0]);a=Cn(t[0]),t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:a,href:s,tokens:[{type:"text",raw:a,text:a}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n;return this.lexer.state.inRawBlock?n=t[0]:n=Cn(t[0]),{type:"text",raw:t[0],text:n}}}},by=/^(?: *(?:\n|$))+/,yy=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,vy=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ls=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cy=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zg=/(?:[*+-]|\d{1,9}[.)])/,eh=nr(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Zg).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),md=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,wy=/^[^\n]+/,gd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Ay=nr(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",gd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Sy=nr(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Zg).getRegex(),Wi="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",hd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ty=nr("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",hd).replace("tag",Wi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),th=nr(md).replace("hr",Ls).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",Wi).getRegex(),My=nr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",th).getRegex(),xd={blockquote:My,code:yy,def:Ay,fences:vy,heading:Cy,hr:Ls,html:Ty,lheading:eh,list:Sy,newline:by,paragraph:th,table:Ms,text:wy},Xg=nr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ls).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",Wi).getRegex(),ky={...xd,table:Xg,paragraph:nr(md).replace("hr",Ls).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Xg).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",Wi).getRegex()},Ey={...xd,html:nr(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",hd).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:Ms,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:nr(md).replace("hr",Ls).replace("heading",` *#{1,6} *[^
|
|
17
|
+
]`).replace("lheading",eh).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},rh=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ly=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,nh=/^( {2,}|\\)\n(?!\s*$)/,Py=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ps="\\p{P}\\p{S}",Ry=nr(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Ps).getRegex(),Iy=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,Hy=nr(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Ps).getRegex(),Wy=nr("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Ps).getRegex(),By=nr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Ps).getRegex(),Dy=nr(/\\([punct])/,"gu").replace(/punct/g,Ps).getRegex(),Fy=nr(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Oy=nr(hd).replace("(?:-->|$)","-->").getRegex(),Ny=nr("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Oy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Hi=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,_y=nr(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Hi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),oh=nr(/^!?\[(label)\]\[(ref)\]/).replace("label",Hi).replace("ref",gd).getRegex(),ah=nr(/^!?\[(ref)\](?:\[\])?/).replace("ref",gd).getRegex(),Uy=nr("reflink|nolink(?!\\()","g").replace("reflink",oh).replace("nolink",ah).getRegex(),bd={_backpedal:Ms,anyPunctuation:Dy,autolink:Fy,blockSkip:Iy,br:nh,code:Ly,del:Ms,emStrongLDelim:Hy,emStrongRDelimAst:Wy,emStrongRDelimUnd:By,escape:rh,link:_y,nolink:ah,punctuation:Ry,reflink:oh,reflinkSearch:Uy,tag:Ny,text:Py,url:Ms},qy={...bd,link:nr(/^!?\[(label)\]\((.*?)\)/).replace("label",Hi).getRegex(),reflink:nr(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Hi).getRegex()},pd={...bd,escape:nr(rh).replace("])","~|])").getRegex(),url:nr(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},zy={...pd,br:nr(nh).replace("{2,}","*").getRegex(),text:nr(pd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ii={normal:xd,gfm:ky,pedantic:Ey},Ts={normal:bd,gfm:pd,breaks:zy,pedantic:qy},fo=class r{constructor(e){cr(this,"tokens");cr(this,"options");cr(this,"state");cr(this,"tokenizer");cr(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||sa,this.options.tokenizer=this.options.tokenizer||new Fa,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={block:Ii.normal,inline:Ts.normal};this.options.pedantic?(t.block=Ii.pedantic,t.inline=Ts.pedantic):this.options.gfm&&(t.block=Ii.gfm,this.options.breaks?t.inline=Ts.breaks:t.inline=Ts.gfm),this.tokenizer.rules=t}static get rules(){return{block:Ii,inline:Ts}}static lex(e,t){return new r(t).lex(e)}static lexInline(e,t){return new r(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
|
|
18
|
+
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,a,s;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},e,t))?(e=e.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.raw.length===1&&t.length>0?t[t.length-1].raw+=`
|
|
19
|
+
`:t.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
23
20
|
`+n.raw,o.text+=`
|
|
24
|
-
`+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.text):
|
|
21
|
+
`+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.list(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.html(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.def(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
25
22
|
`+n.raw,o.text+=`
|
|
26
|
-
`+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),
|
|
23
|
+
`+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.lheading(e)){e=e.substring(n.raw.length),t.push(n);continue}if(a=e,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=e.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(a=e.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(a))){o=t[t.length-1],s&&o.type==="paragraph"?(o.raw+=`
|
|
27
24
|
`+n.raw,o.text+=`
|
|
28
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):
|
|
25
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n),s=a.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&o.type==="text"?(o.raw+=`
|
|
29
26
|
`+n.raw,o.text+=`
|
|
30
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):
|
|
27
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,o,a,s=e,i,d,l;if(this.tokens.links){let u=Object.keys(this.tokens.links);if(u.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)u.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(n=u.call({lexer:this},e,t))?(e=e.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),o=t[t.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length),o=t[t.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(n=this.tokenizer.emStrong(e,s,l)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),t.push(n);continue}if(a=e,this.options.extensions&&this.options.extensions.startInline){let u=1/0,m=e.slice(1),p;this.options.extensions.startInline.forEach(f=>{p=f.call({lexer:this},m),typeof p=="number"&&p>=0&&(u=Math.min(u,p))}),u<1/0&&u>=0&&(a=e.substring(0,u+1))}if(n=this.tokenizer.inlineText(a)){e=e.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=t[t.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(e){let u="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}},Oa=class{constructor(e){cr(this,"options");this.options=e||sa}code(e,t,n){var a;let o=(a=(t||"").match(/^\S*/))==null?void 0:a[0];return e=e.replace(/\n$/,"")+`
|
|
31
28
|
`,o?'<pre><code class="language-'+Cn(o)+'">'+(n?e:Cn(e,!0))+`</code></pre>
|
|
32
29
|
`:"<pre><code>"+(n?e:Cn(e,!0))+`</code></pre>
|
|
33
30
|
`}blockquote(e){return`<blockquote>
|
|
34
31
|
${e}</blockquote>
|
|
35
|
-
`}html(e,
|
|
32
|
+
`}html(e,t){return e}heading(e,t,n){return`<h${t}>${e}</h${t}>
|
|
36
33
|
`}hr(){return`<hr>
|
|
37
|
-
`}list(e,
|
|
34
|
+
`}list(e,t,n){let o=t?"ol":"ul",a=t&&n!==1?' start="'+n+'"':"";return"<"+o+a+`>
|
|
38
35
|
`+e+"</"+o+`>
|
|
39
|
-
`}listitem(e,
|
|
36
|
+
`}listitem(e,t,n){return`<li>${e}</li>
|
|
40
37
|
`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>
|
|
41
|
-
`}table(e,
|
|
38
|
+
`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),`<table>
|
|
42
39
|
<thead>
|
|
43
40
|
`+e+`</thead>
|
|
44
|
-
`+
|
|
41
|
+
`+t+`</table>
|
|
45
42
|
`}tablerow(e){return`<tr>
|
|
46
43
|
${e}</tr>
|
|
47
|
-
`}tablecell(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,
|
|
49
|
-
`+(
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),vh=t=>t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),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
|
-
`+
|
|
44
|
+
`}tablecell(e,t){let n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
|
|
45
|
+
`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){let o=jg(e);if(o===null)return n;e=o;let a='<a href="'+e+'"';return t&&(a+=' title="'+t+'"'),a+=">"+n+"</a>",a}image(e,t,n){let o=jg(e);if(o===null)return n;e=o;let a=`<img src="${e}" alt="${n}"`;return t&&(a+=` title="${t}"`),a+=">",a}text(e){return e}},ks=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}},mo=class r{constructor(e){cr(this,"options");cr(this,"renderer");cr(this,"textRenderer");this.options=e||sa,this.options.renderer=this.options.renderer||new Oa,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ks}static parse(e,t){return new r(t).parse(e)}static parseInline(e,t){return new r(t).parseInline(e)}parse(e,t=!0){let n="";for(let o=0;o<e.length;o++){let a=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=a,i=this.options.extensions.renderers[s.type].call({parser:this},s);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(s.type)){n+=i||"";continue}}switch(a.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let s=a;n+=this.renderer.heading(this.parseInline(s.tokens),s.depth,my(this.parseInline(s.tokens,this.textRenderer)));continue}case"code":{let s=a;n+=this.renderer.code(s.text,s.lang,!!s.escaped);continue}case"table":{let s=a,i="",d="";for(let u=0;u<s.header.length;u++)d+=this.renderer.tablecell(this.parseInline(s.header[u].tokens),{header:!0,align:s.align[u]});i+=this.renderer.tablerow(d);let l="";for(let u=0;u<s.rows.length;u++){let m=s.rows[u];d="";for(let p=0;p<m.length;p++)d+=this.renderer.tablecell(this.parseInline(m[p].tokens),{header:!1,align:s.align[p]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let s=a,i=this.parse(s.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let s=a,i=s.ordered,d=s.start,l=s.loose,u="";for(let m=0;m<s.items.length;m++){let p=s.items[m],f=p.checked,b=p.task,h="";if(p.task){let S=this.renderer.checkbox(!!f);l?p.tokens.length>0&&p.tokens[0].type==="paragraph"?(p.tokens[0].text=S+" "+p.tokens[0].text,p.tokens[0].tokens&&p.tokens[0].tokens.length>0&&p.tokens[0].tokens[0].type==="text"&&(p.tokens[0].tokens[0].text=S+" "+p.tokens[0].tokens[0].text)):p.tokens.unshift({type:"text",text:S+" "}):h+=S+" "}h+=this.parse(p.tokens,l),u+=this.renderer.listitem(h,b,!!f)}n+=this.renderer.list(u,i,d);continue}case"html":{let s=a;n+=this.renderer.html(s.text,s.block);continue}case"paragraph":{let s=a;n+=this.renderer.paragraph(this.parseInline(s.tokens));continue}case"text":{let s=a,i=s.tokens?this.parseInline(s.tokens):s.text;for(;o+1<e.length&&e[o+1].type==="text";)s=e[++o],i+=`
|
|
46
|
+
`+(s.tokens?this.parseInline(s.tokens):s.text);n+=t?this.renderer.paragraph(i):i;continue}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let o=0;o<e.length;o++){let a=e[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){n+=s||"";continue}}switch(a.type){case"escape":{let s=a;n+=t.text(s.text);break}case"html":{let s=a;n+=t.html(s.text);break}case"link":{let s=a;n+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break}case"image":{let s=a;n+=t.image(s.href,s.title,s.text);break}case"strong":{let s=a;n+=t.strong(this.parseInline(s.tokens,t));break}case"em":{let s=a;n+=t.em(this.parseInline(s.tokens,t));break}case"codespan":{let s=a;n+=t.codespan(s.text);break}case"br":{n+=t.br();break}case"del":{let s=a;n+=t.del(this.parseInline(s.tokens,t));break}case"text":{let s=a;n+=t.text(s.text);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},na=class{constructor(e){cr(this,"options");this.options=e||sa}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};cr(na,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var aa,ud,sh,Es=class{constructor(...e){$g(this,aa);cr(this,"defaults",fd());cr(this,"options",this.setOptions);cr(this,"parse",Pi(this,aa,ud).call(this,fo.lex,mo.parse));cr(this,"parseInline",Pi(this,aa,ud).call(this,fo.lexInline,mo.parseInline));cr(this,"Parser",mo);cr(this,"Renderer",Oa);cr(this,"TextRenderer",ks);cr(this,"Lexer",fo);cr(this,"Tokenizer",Fa);cr(this,"Hooks",na);this.use(...e)}walkTokens(e,t){var o,a;let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let i=s;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,t));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,t));break}case"list":{let i=s;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=s;(a=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&a[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let s=t.renderers[a.name];s?t.renderers[a.name]=function(...i){let d=a.renderer.apply(this,i);return d===!1&&(d=s.apply(this,i)),d}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[a.level];s?s.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),o.extensions=t),n.renderer){let a=this.defaults.renderer||new Oa(this.defaults);for(let s in n.renderer){if(!(s in a))throw new Error(`renderer '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.renderer[i],l=a[i];a[i]=(...u)=>{let m=d.apply(a,u);return m===!1&&(m=l.apply(a,u)),m||""}}o.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new Fa(this.defaults);for(let s in n.tokenizer){if(!(s in a))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=n.tokenizer[i],l=a[i];a[i]=(...u)=>{let m=d.apply(a,u);return m===!1&&(m=l.apply(a,u)),m}}o.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new na;for(let s in n.hooks){if(!(s in a))throw new Error(`hook '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.hooks[i],l=a[i];na.passThroughHooks.has(s)?a[i]=u=>{if(this.defaults.async)return Promise.resolve(d.call(a,u)).then(p=>l.call(a,p));let m=d.call(a,u);return l.call(a,m)}:a[i]=(...u)=>{let m=d.apply(a,u);return m===!1&&(m=l.apply(a,u)),m}}o.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,s=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(s.call(this,i)),a&&(d=d.concat(a.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return fo.lex(e,t!=null?t:this.defaults)}parser(e,t){return mo.parse(e,t!=null?t:this.defaults)}};aa=new WeakSet,ud=function(e,t){return(n,o)=>{let a={...o},s={...this.defaults,...a};this.defaults.async===!0&&a.async===!1&&(s.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),s.async=!0);let i=Pi(this,aa,sh).call(this,!!s.silent,!!s.async);if(typeof n=="undefined"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s),s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(n):n).then(d=>e(d,s)).then(d=>s.hooks?s.hooks.processAllTokens(d):d).then(d=>s.walkTokens?Promise.all(this.walkTokens(d,s.walkTokens)).then(()=>d):d).then(d=>t(d,s)).then(d=>s.hooks?s.hooks.postprocess(d):d).catch(i);try{s.hooks&&(n=s.hooks.preprocess(n));let d=e(n,s);s.hooks&&(d=s.hooks.processAllTokens(d)),s.walkTokens&&this.walkTokens(d,s.walkTokens);let l=t(d,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(d){return i(d)}}},sh=function(e,t){return n=>{if(n.message+=`
|
|
47
|
+
Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+Cn(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}};var oa=new Es;function rr(r,e){return oa.parse(r,e)}rr.options=rr.setOptions=function(r){return oa.setOptions(r),rr.defaults=oa.defaults,Qg(rr.defaults),rr};rr.getDefaults=fd;rr.defaults=sa;rr.use=function(...r){return oa.use(...r),rr.defaults=oa.defaults,Qg(rr.defaults),rr};rr.walkTokens=function(r,e){return oa.walkTokens(r,e)};rr.parseInline=oa.parseInline;rr.Parser=mo;rr.parser=mo.parse;rr.Renderer=Oa;rr.TextRenderer=ks;rr.Lexer=fo;rr.lexer=fo.lex;rr.Tokenizer=Fa;rr.Hooks=na;rr.parse=rr;var Hw=rr.options,Ww=rr.setOptions,Bw=rr.use,Dw=rr.walkTokens,Fw=rr.parseInline;var Ow=mo.parse,Nw=fo.lex;var $y=r=>{if(r)return r},Rs=r=>{var o,a;let e=r==null?void 0:r.markedOptions,t=new Es({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(a=e==null?void 0:e.breaks)!=null?a:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),n=$y(r==null?void 0:r.renderer);return n&&t.use({renderer:n}),s=>t.parse(s)},ia=r=>r?Rs({markedOptions:r.options,renderer:r.renderer}):Rs(),Vy=Rs(),yd=r=>Vy(r),la=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),lh=r=>r.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),ih=r=>`%%FORM_PLACEHOLDER_${r}%%`,dh=(r,e)=>{let t=r;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let a=JSON.parse(o.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=ih(e.length);return e.push({token:s,type:String(a.type)}),s}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let a=ih(e.length);return e.push({token:a,type:o}),a}),t},ch=r=>{let e=ia(r);return t=>{let n=[],o=dh(t,n),a=e(o);return n.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${lh(i)}"></div>`;a=a.replace(d,u)}),a}},ph=r=>{let e=[],t=dh(r,e),n=yd(t);return e.forEach(({token:o,type:a})=>{let s=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${lh(a)}"></div>`;n=n.replace(s,d)}),n};var{entries:vh,setPrototypeOf:uh,isFrozen:jy,getPrototypeOf:Gy,getOwnPropertyDescriptor:Ky}=Object,{freeze:rn,seal:Hn,create:Fi}=Object,{apply:Md,construct:kd}=typeof Reflect!="undefined"&&Reflect;rn||(rn=function(e){return e});Hn||(Hn=function(e){return e});Md||(Md=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),a=2;a<n;a++)o[a-2]=arguments[a];return e.apply(t,o)});kd||(kd=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return new e(...n)});var Bi=nn(Array.prototype.forEach),Xy=nn(Array.prototype.lastIndexOf),fh=nn(Array.prototype.pop),Is=nn(Array.prototype.push),Qy=nn(Array.prototype.splice),Oi=nn(String.prototype.toLowerCase),vd=nn(String.prototype.toString),Cd=nn(String.prototype.match),Hs=nn(String.prototype.replace),Jy=nn(String.prototype.indexOf),Yy=nn(String.prototype.trim),wn=nn(Object.prototype.hasOwnProperty),tn=nn(RegExp.prototype.test),Ws=Zy(TypeError);function nn(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return Md(r,e,n)}}function Zy(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return kd(r,t)}}function Ht(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Oi;uh&&uh(r,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let a=t(o);a!==o&&(jy(e)||(e[n]=a),o=a)}r[o]=!0}return r}function e0(r){for(let e=0;e<r.length;e++)wn(r,e)||(r[e]=null);return r}function to(r){let e=Fi(null);for(let[t,n]of vh(r))wn(r,t)&&(Array.isArray(n)?e[t]=e0(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=to(n):e[t]=n);return e}function Bs(r,e){for(;r!==null;){let n=Ky(r,e);if(n){if(n.get)return nn(n.get);if(typeof n.value=="function")return nn(n.value)}r=Gy(r)}function t(){return null}return t}var mh=rn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),wd=rn(["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"]),Ad=rn(["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=rn(["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"]),Sd=rn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),r0=rn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),gh=rn(["#text"]),hh=rn(["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"]),Td=rn(["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"]),xh=rn(["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"]),Di=rn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),n0=Hn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),o0=Hn(/<%[\w\W]*|[\w\W]*%>/gm),a0=Hn(/\$\{[\w\W]*/gm),s0=Hn(/^data-[\-\w.\u00B7-\uFFFF]+$/),i0=Hn(/^aria-[\-\w]+$/),Ch=Hn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),l0=Hn(/^(?:\w+script|data):/i),d0=Hn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),wh=Hn(/^html$/i),c0=Hn(/^[a-z][.\w]*(-[.\w]+)+$/i),bh=Object.freeze({__proto__:null,ARIA_ATTR:i0,ATTR_WHITESPACE:d0,CUSTOM_ELEMENT:c0,DATA_ATTR:s0,DOCTYPE_NAME:wh,ERB_EXPR:o0,IS_ALLOWED_URI:Ch,IS_SCRIPT_OR_DATA:l0,MUSTACHE_EXPR:n0,TMPLIT_EXPR:a0}),Ds={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},p0=function(){return typeof window=="undefined"?null:window},u0=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));let a="dompurify"+(n?"#"+n:"");try{return e.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},yh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ah(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:p0(),e=_e=>Ah(_e);if(e.version="3.3.3",e.removed=[],!r||!r.document||r.document.nodeType!==Ds.document||!r.Element)return e.isSupported=!1,e;let{document:t}=r,n=t,o=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:i,Element:d,NodeFilter:l,NamedNodeMap:u=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=r,b=d.prototype,h=Bs(b,"cloneNode"),S=Bs(b,"remove"),T=Bs(b,"nextSibling"),M=Bs(b,"childNodes"),k=Bs(b,"parentNode");if(typeof s=="function"){let _e=t.createElement("template");_e.content&&_e.content.ownerDocument&&(t=_e.content.ownerDocument)}let x,C="",{implementation:w,createNodeIterator:E,createDocumentFragment:H,getElementsByTagName:I}=t,{importNode:L}=n,O=yh();e.isSupported=typeof vh=="function"&&typeof k=="function"&&w&&w.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:$,ERB_EXPR:te,TMPLIT_EXPR:xe,DATA_ATTR:Je,ARIA_ATTR:we,IS_SCRIPT_OR_DATA:De,ATTR_WHITESPACE:Ae,CUSTOM_ELEMENT:qe}=bh,{IS_ALLOWED_URI:He}=bh,J=null,re=Ht({},[...mh,...wd,...Ad,...Sd,...gh]),Q=null,ge=Ht({},[...hh,...Td,...xh,...Di]),Z=Object.seal(Fi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),G=null,pe=null,ke=Object.seal(Fi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),le=!0,ne=!0,de=!1,Et=!0,wt=!1,We=!0,he=!1,at=!1,Re=!1,j=!1,ue=!1,nt=!1,Rt=!0,ee=!1,Ge="user-content-",Fr=!0,Bt=!1,or={},hr=null,sn=Ht({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),F=null,fe=Ht({},["audio","video","img","source","image","track"]),Ie=null,Xe=Ht({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Fe="http://www.w3.org/1998/Math/MathML",Ne="http://www.w3.org/2000/svg",Ye="http://www.w3.org/1999/xhtml",At=Ye,Xt=!1,ar=null,K=Ht({},[Fe,Ne,Ye],vd),mt=Ht({},["mi","mo","mn","ms","mtext"]),it=Ht({},["annotation-xml"]),ye=Ht({},["title","style","font","a","script"]),ie=null,st=["application/xhtml+xml","text/html"],pr="text/html",pt=null,yr=null,Rr=t.createElement("form"),ut=function(R){return R instanceof RegExp||R instanceof Function},Lt=function(){let R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(yr&&yr===R)){if((!R||typeof R!="object")&&(R={}),R=to(R),ie=st.indexOf(R.PARSER_MEDIA_TYPE)===-1?pr:R.PARSER_MEDIA_TYPE,pt=ie==="application/xhtml+xml"?vd:Oi,J=wn(R,"ALLOWED_TAGS")?Ht({},R.ALLOWED_TAGS,pt):re,Q=wn(R,"ALLOWED_ATTR")?Ht({},R.ALLOWED_ATTR,pt):ge,ar=wn(R,"ALLOWED_NAMESPACES")?Ht({},R.ALLOWED_NAMESPACES,vd):K,Ie=wn(R,"ADD_URI_SAFE_ATTR")?Ht(to(Xe),R.ADD_URI_SAFE_ATTR,pt):Xe,F=wn(R,"ADD_DATA_URI_TAGS")?Ht(to(fe),R.ADD_DATA_URI_TAGS,pt):fe,hr=wn(R,"FORBID_CONTENTS")?Ht({},R.FORBID_CONTENTS,pt):sn,G=wn(R,"FORBID_TAGS")?Ht({},R.FORBID_TAGS,pt):to({}),pe=wn(R,"FORBID_ATTR")?Ht({},R.FORBID_ATTR,pt):to({}),or=wn(R,"USE_PROFILES")?R.USE_PROFILES:!1,le=R.ALLOW_ARIA_ATTR!==!1,ne=R.ALLOW_DATA_ATTR!==!1,de=R.ALLOW_UNKNOWN_PROTOCOLS||!1,Et=R.ALLOW_SELF_CLOSE_IN_ATTR!==!1,wt=R.SAFE_FOR_TEMPLATES||!1,We=R.SAFE_FOR_XML!==!1,he=R.WHOLE_DOCUMENT||!1,j=R.RETURN_DOM||!1,ue=R.RETURN_DOM_FRAGMENT||!1,nt=R.RETURN_TRUSTED_TYPE||!1,Re=R.FORCE_BODY||!1,Rt=R.SANITIZE_DOM!==!1,ee=R.SANITIZE_NAMED_PROPS||!1,Fr=R.KEEP_CONTENT!==!1,Bt=R.IN_PLACE||!1,He=R.ALLOWED_URI_REGEXP||Ch,At=R.NAMESPACE||Ye,mt=R.MATHML_TEXT_INTEGRATION_POINTS||mt,it=R.HTML_INTEGRATION_POINTS||it,Z=R.CUSTOM_ELEMENT_HANDLING||{},R.CUSTOM_ELEMENT_HANDLING&&ut(R.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=R.CUSTOM_ELEMENT_HANDLING.tagNameCheck),R.CUSTOM_ELEMENT_HANDLING&&ut(R.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=R.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),R.CUSTOM_ELEMENT_HANDLING&&typeof R.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=R.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),wt&&(ne=!1),ue&&(j=!0),or&&(J=Ht({},gh),Q=Fi(null),or.html===!0&&(Ht(J,mh),Ht(Q,hh)),or.svg===!0&&(Ht(J,wd),Ht(Q,Td),Ht(Q,Di)),or.svgFilters===!0&&(Ht(J,Ad),Ht(Q,Td),Ht(Q,Di)),or.mathMl===!0&&(Ht(J,Sd),Ht(Q,xh),Ht(Q,Di))),wn(R,"ADD_TAGS")||(ke.tagCheck=null),wn(R,"ADD_ATTR")||(ke.attributeCheck=null),R.ADD_TAGS&&(typeof R.ADD_TAGS=="function"?ke.tagCheck=R.ADD_TAGS:(J===re&&(J=to(J)),Ht(J,R.ADD_TAGS,pt))),R.ADD_ATTR&&(typeof R.ADD_ATTR=="function"?ke.attributeCheck=R.ADD_ATTR:(Q===ge&&(Q=to(Q)),Ht(Q,R.ADD_ATTR,pt))),R.ADD_URI_SAFE_ATTR&&Ht(Ie,R.ADD_URI_SAFE_ATTR,pt),R.FORBID_CONTENTS&&(hr===sn&&(hr=to(hr)),Ht(hr,R.FORBID_CONTENTS,pt)),R.ADD_FORBID_CONTENTS&&(hr===sn&&(hr=to(hr)),Ht(hr,R.ADD_FORBID_CONTENTS,pt)),Fr&&(J["#text"]=!0),he&&Ht(J,["html","head","body"]),J.table&&(Ht(J,["tbody"]),delete G.tbody),R.TRUSTED_TYPES_POLICY){if(typeof R.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ws('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof R.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ws('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=R.TRUSTED_TYPES_POLICY,C=x.createHTML("")}else x===void 0&&(x=u0(f,o)),x!==null&&typeof C=="string"&&(C=x.createHTML(""));rn&&rn(R),yr=R}},tt=Ht({},[...wd,...Ad,...t0]),zt=Ht({},[...Sd,...r0]),vr=function(R){let se=k(R);(!se||!se.tagName)&&(se={namespaceURI:At,tagName:"template"});let Ee=Oi(R.tagName),Ot=Oi(se.tagName);return ar[R.namespaceURI]?R.namespaceURI===Ne?se.namespaceURI===Ye?Ee==="svg":se.namespaceURI===Fe?Ee==="svg"&&(Ot==="annotation-xml"||mt[Ot]):!!tt[Ee]:R.namespaceURI===Fe?se.namespaceURI===Ye?Ee==="math":se.namespaceURI===Ne?Ee==="math"&&it[Ot]:!!zt[Ee]:R.namespaceURI===Ye?se.namespaceURI===Ne&&!it[Ot]||se.namespaceURI===Fe&&!mt[Ot]?!1:!zt[Ee]&&(ye[Ee]||!tt[Ee]):!!(ie==="application/xhtml+xml"&&ar[R.namespaceURI]):!1},sr=function(R){Is(e.removed,{element:R});try{k(R).removeChild(R)}catch{S(R)}},ur=function(R,se){try{Is(e.removed,{attribute:se.getAttributeNode(R),from:se})}catch{Is(e.removed,{attribute:null,from:se})}if(se.removeAttribute(R),R==="is")if(j||ue)try{sr(se)}catch{}else try{se.setAttribute(R,"")}catch{}},Mr=function(R){let se=null,Ee=null;if(Re)R="<remove></remove>"+R;else{let Nt=Cd(R,/^[\r\n\t ]+/);Ee=Nt&&Nt[0]}ie==="application/xhtml+xml"&&At===Ye&&(R='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+R+"</body></html>");let Ot=x?x.createHTML(R):R;if(At===Ye)try{se=new p().parseFromString(Ot,ie)}catch{}if(!se||!se.documentElement){se=w.createDocument(At,"template",null);try{se.documentElement.innerHTML=Xt?C:Ot}catch{}}let et=se.body||se.documentElement;return R&&Ee&&et.insertBefore(t.createTextNode(Ee),et.childNodes[0]||null),At===Ye?I.call(se,he?"html":"body")[0]:he?se.documentElement:et},un=function(R){return E.call(R.ownerDocument||R,R,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},St=function(R){return R instanceof m&&(typeof R.nodeName!="string"||typeof R.textContent!="string"||typeof R.removeChild!="function"||!(R.attributes instanceof u)||typeof R.removeAttribute!="function"||typeof R.setAttribute!="function"||typeof R.namespaceURI!="string"||typeof R.insertBefore!="function"||typeof R.hasChildNodes!="function")},qr=function(R){return typeof i=="function"&&R instanceof i};function xr(_e,R,se){Bi(_e,Ee=>{Ee.call(e,R,se,yr)})}let Mn=function(R){let se=null;if(xr(O.beforeSanitizeElements,R,null),St(R))return sr(R),!0;let Ee=pt(R.nodeName);if(xr(O.uponSanitizeElement,R,{tagName:Ee,allowedTags:J}),We&&R.hasChildNodes()&&!qr(R.firstElementChild)&&tn(/<[/\w!]/g,R.innerHTML)&&tn(/<[/\w!]/g,R.textContent)||R.nodeType===Ds.progressingInstruction||We&&R.nodeType===Ds.comment&&tn(/<[/\w]/g,R.data))return sr(R),!0;if(!(ke.tagCheck instanceof Function&&ke.tagCheck(Ee))&&(!J[Ee]||G[Ee])){if(!G[Ee]&&yt(Ee)&&(Z.tagNameCheck instanceof RegExp&&tn(Z.tagNameCheck,Ee)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Ee)))return!1;if(Fr&&!hr[Ee]){let Ot=k(R)||R.parentNode,et=M(R)||R.childNodes;if(et&&Ot){let Nt=et.length;for(let Yt=Nt-1;Yt>=0;--Yt){let lr=h(et[Yt],!0);lr.__removalCount=(R.__removalCount||0)+1,Ot.insertBefore(lr,T(R))}}}return sr(R),!0}return R instanceof d&&!vr(R)||(Ee==="noscript"||Ee==="noembed"||Ee==="noframes")&&tn(/<\/no(script|embed|frames)/i,R.innerHTML)?(sr(R),!0):(wt&&R.nodeType===Ds.text&&(se=R.textContent,Bi([$,te,xe],Ot=>{se=Hs(se,Ot," ")}),R.textContent!==se&&(Is(e.removed,{element:R.cloneNode()}),R.textContent=se)),xr(O.afterSanitizeElements,R,null),!1)},ln=function(R,se,Ee){if(pe[se]||Rt&&(se==="id"||se==="name")&&(Ee in t||Ee in Rr))return!1;if(!(ne&&!pe[se]&&tn(Je,se))){if(!(le&&tn(we,se))){if(!(ke.attributeCheck instanceof Function&&ke.attributeCheck(se,R))){if(!Q[se]||pe[se]){if(!(yt(R)&&(Z.tagNameCheck instanceof RegExp&&tn(Z.tagNameCheck,R)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(R))&&(Z.attributeNameCheck instanceof RegExp&&tn(Z.attributeNameCheck,se)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(se,R))||se==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&tn(Z.tagNameCheck,Ee)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Ee))))return!1}else if(!Ie[se]){if(!tn(He,Hs(Ee,Ae,""))){if(!((se==="src"||se==="xlink:href"||se==="href")&&R!=="script"&&Jy(Ee,"data:")===0&&F[R])){if(!(de&&!tn(De,Hs(Ee,Ae,"")))){if(Ee)return!1}}}}}}}return!0},yt=function(R){return R!=="annotation-xml"&&Cd(R,qe)},Gn=function(R){xr(O.beforeSanitizeAttributes,R,null);let{attributes:se}=R;if(!se||St(R))return;let Ee={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Q,forceKeepAttr:void 0},Ot=se.length;for(;Ot--;){let et=se[Ot],{name:Nt,namespaceURI:Yt,value:lr}=et,vt=pt(Nt),zr=lr,$t=Nt==="value"?zr:Yy(zr);if(Ee.attrName=vt,Ee.attrValue=$t,Ee.keepAttr=!0,Ee.forceKeepAttr=void 0,xr(O.uponSanitizeAttribute,R,Ee),$t=Ee.attrValue,ee&&(vt==="id"||vt==="name")&&(ur(Nt,R),$t=Ge+$t),We&&tn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,$t)){ur(Nt,R);continue}if(vt==="attributename"&&Cd($t,"href")){ur(Nt,R);continue}if(Ee.forceKeepAttr)continue;if(!Ee.keepAttr){ur(Nt,R);continue}if(!Et&&tn(/\/>/i,$t)){ur(Nt,R);continue}wt&&Bi([$,te,xe],Dn=>{$t=Hs($t,Dn," ")});let $r=pt(R.nodeName);if(!ln($r,vt,$t)){ur(Nt,R);continue}if(x&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Yt)switch(f.getAttributeType($r,vt)){case"TrustedHTML":{$t=x.createHTML($t);break}case"TrustedScriptURL":{$t=x.createScriptURL($t);break}}if($t!==zr)try{Yt?R.setAttributeNS(Yt,Nt,$t):R.setAttribute(Nt,$t),St(R)?sr(R):fh(e.removed)}catch{ur(Nt,R)}}xr(O.afterSanitizeAttributes,R,null)},kn=function _e(R){let se=null,Ee=un(R);for(xr(O.beforeSanitizeShadowDOM,R,null);se=Ee.nextNode();)xr(O.uponSanitizeShadowNode,se,null),Mn(se),Gn(se),se.content instanceof a&&_e(se.content);xr(O.afterSanitizeShadowDOM,R,null)};return e.sanitize=function(_e){let R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},se=null,Ee=null,Ot=null,et=null;if(Xt=!_e,Xt&&(_e="<!-->"),typeof _e!="string"&&!qr(_e))if(typeof _e.toString=="function"){if(_e=_e.toString(),typeof _e!="string")throw Ws("dirty is not a string, aborting")}else throw Ws("toString is not a function");if(!e.isSupported)return _e;if(at||Lt(R),e.removed=[],typeof _e=="string"&&(Bt=!1),Bt){if(_e.nodeName){let lr=pt(_e.nodeName);if(!J[lr]||G[lr])throw Ws("root node is forbidden and cannot be sanitized in-place")}}else if(_e instanceof i)se=Mr("<!---->"),Ee=se.ownerDocument.importNode(_e,!0),Ee.nodeType===Ds.element&&Ee.nodeName==="BODY"||Ee.nodeName==="HTML"?se=Ee:se.appendChild(Ee);else{if(!j&&!wt&&!he&&_e.indexOf("<")===-1)return x&&nt?x.createHTML(_e):_e;if(se=Mr(_e),!se)return j?null:nt?C:""}se&&Re&&sr(se.firstChild);let Nt=un(Bt?_e:se);for(;Ot=Nt.nextNode();)Mn(Ot),Gn(Ot),Ot.content instanceof a&&kn(Ot.content);if(Bt)return _e;if(j){if(ue)for(et=H.call(se.ownerDocument);se.firstChild;)et.appendChild(se.firstChild);else et=se;return(Q.shadowroot||Q.shadowrootmode)&&(et=L.call(n,et,!0)),et}let Yt=he?se.outerHTML:se.innerHTML;return he&&J["!doctype"]&&se.ownerDocument&&se.ownerDocument.doctype&&se.ownerDocument.doctype.name&&tn(wh,se.ownerDocument.doctype.name)&&(Yt="<!DOCTYPE "+se.ownerDocument.doctype.name+`>
|
|
48
|
+
`+Yt),wt&&Bi([$,te,xe],lr=>{Yt=Hs(Yt,lr," ")}),x&&nt?x.createHTML(Yt):Yt},e.setConfig=function(){let _e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Lt(_e),at=!0},e.clearConfig=function(){yr=null,at=!1},e.isValidAttribute=function(_e,R,se){yr||Lt({});let Ee=pt(_e),Ot=pt(R);return ln(Ee,Ot,se)},e.addHook=function(_e,R){typeof R=="function"&&Is(O[_e],R)},e.removeHook=function(_e,R){if(R!==void 0){let se=Xy(O[_e],R);return se===-1?void 0:Qy(O[_e],se,1)[0]}return fh(O[_e])},e.removeHooks=function(_e){O[_e]=[]},e.removeAllHooks=function(){O=yh()},e}var Sh=Ah();var f0={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},m0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ed=()=>{let r=Sh(typeof window!="undefined"?window:void 0);return r.addHook("uponSanitizeAttribute",(e,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!m0.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),e=>r.sanitize(e,f0)},Na=r=>r===!1?null:typeof r=="function"?r:Ed();var go="webmcp:",Ld=new Map,Th=r=>{var e;Ld.clear();for(let t of r){let n=(e=t.title)==null?void 0:e.trim();n&&Ld.set(t.name,n)}},Rd=r=>Ld.get(_i(r)),Ni={warn(r,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${r}`,...e)}},Pd=null,kh=r=>{Pd=r};function Eh(r){if(r.length===0)return"0:empty";let e=r.map(t=>{var n,o;return[t.name,(n=t.description)!=null?n:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${r.length}:${g0(e.join(""))}`}function Mh(r,e){let t=3735928559^e,n=1103547991^e;for(let o=0;o<r.length;o++){let a=r.charCodeAt(o);t=Math.imul(t^a,2654435761),n=Math.imul(n^a,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&n)+(t>>>0)}function g0(r){let e=Mh(r,0).toString(36),t=Mh(r,2654435761).toString(36);return`${e}.${t}`}var _a=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(o){return Ni.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}Th(t);let n=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let a={name:o.name,description:o.description,origin:"webmcp",...n?{pageOrigin:n}:{}},s=x0(o.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(e,t,n){if(await this.ensureReady(),this.config.enabled!==!0)return $n("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let b=typeof document!="undefined"&&!!document.modelContext;return $n(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=_i(e),s;try{s=await o.getTools()}catch(b){let h=b instanceof Error?b.message:String(b);return $n(`Failed to read WebMCP registry: ${h}`)}Th(s);let i=s.find(b=>b.name===a);if(!i)return $n(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return $n(`WebMCP tool not allowed by client allowlist: ${a}`);if(n!=null&&n.aborted)return $n("Aborted by cancel()");let d=Rd(a),l={toolName:a,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return $n("User declined the tool call.");if(n!=null&&n.aborted)return $n("Aborted by cancel()");let u=new AbortController,m=!1,p=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),f=()=>u.abort();n&&(n.aborted?u.abort():n.addEventListener("abort",f,{once:!0}));try{let b=await o.executeTool(i,C0(t),{signal:u.signal});return b0(b)}catch(b){if(m)return $n(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(n!=null&&n.aborted)return $n("Aborted by cancel()");let h=b instanceof Error?b.message:String(b);return $n(h)}finally{clearTimeout(p),n&&n.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Pd?await Pd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Ni.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ni.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var n;let t=(n=this.confirmHandler)!=null?n:y0;try{return await t(e)}catch(o){return Ni.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(n=>h0(e,n))}},_i=r=>r.startsWith(go)?r.slice(go.length):r,da=r=>r.startsWith(go),h0=(r,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(r)},x0=r=>{if(!(r===void 0||r===""))try{let e=JSON.parse(r);return e!==null&&typeof e=="object"?e:void 0}catch{return}},b0=r=>{if(r==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(r)}catch{return{content:[{type:"text",text:r}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:w0(e)}]}},$n=r=>({isError:!0,content:[{type:"text",text:r}]}),y0=async r=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=v0(r.args),t=`Allow the AI to call ${r.toolName}`+(e?`
|
|
52
49
|
|
|
53
50
|
Arguments:
|
|
54
|
-
${e}`:"")+(
|
|
51
|
+
${e}`:"")+(r.description?`
|
|
55
52
|
|
|
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,"\\")
|
|
58
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return
|
|
59
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>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(`
|
|
53
|
+
${r.description}`:"");return window.confirm(t)},v0=r=>{if(r==null)return"";try{let e=JSON.stringify(r,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(r)}},C0=r=>{if(r===void 0)return"{}";try{let e=JSON.stringify(r);return e===void 0?"{}":e}catch{return"{}"}},w0=r=>{if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}};var Do=Li(zi(),1);var v=(r,e)=>{let t=document.createElement(r);return e&&(t.className=e),t},ro=(r,e,t)=>{let n=r.createElement(e);return t&&(n.className=t),n};var Os="ask_user_question",Fs=8,Ua="data-persona-ask-sheet-for",k0="Other",E0="Other\u2026",Rh="Type your own answer here",Ih="Send",L0="Next",P0="Back",R0="Submit all",I0="Skip",H0=3,Hd="data-ask-current-index",Wd="data-ask-question-count",Hh="data-ask-answers",Bd="data-ask-grouped",Wh="data-ask-layout",W0=r=>r.layout==="pills"?"pills":"rows",B0=r=>r.getAttribute(Wh)==="pills"?"pills":"rows",Ph=!1,Bh=r=>r.replace(/["\\]/g,"\\$&"),ho=r=>r.variant==="tool"&&!!r.toolCall&&r.toolCall.name===Os,$i=r=>{var e,t;return(t=(e=r==null?void 0:r.features)==null?void 0:e.askUserQuestion)!=null?t:{}},xo=r=>{let e=r.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let n=e.chunks;if(!n||n.length===0)return{payload:null,complete:t};try{let o=n.join(""),a=(0,Do.parse)(o,Do.STR|Do.OBJ|Do.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Ns=r=>{let e=Array.isArray(r==null?void 0:r.questions)?r.questions:[];return e.length>Fs&&!Ph&&(Ph=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Fs}.`)),e.slice(0,Fs)},D0=r=>{var e;return(e=Ns(r)[0])!=null?e:null},F0=(r,e)=>{var t;return(t=Ns(r)[e])!=null?t:null},Dh=(r,e)=>{let t=e.styles;t&&(t.sheetBackground&&r.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&r.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&r.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&r.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&r.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&r.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&r.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&r.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&r.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Fh=(r,e,t)=>{if(r!=="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(t+1),n.appendChild(o)}return n},O0=(r,e,t,n)=>{let a=v("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(e)),a.setAttribute("data-option-label",r.label),t==="rows"){let s=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=r.label,s.appendChild(i),r.description){let l=v("span","persona-ask-row-description");l.textContent=r.description,s.appendChild(l)}a.appendChild(s);let d=Fh(t,n,e);d&&a.appendChild(d)}else a.textContent=r.label,r.description&&(a.title=r.description);return a},N0=r=>{let t=v("span",r==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},_0=(r,e,t,n)=>{var u,m,p;let a=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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(r!=null&&r.multiSelect),d=(Array.isArray(r==null?void 0:r.options)?r.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!t){for(let f=0;f<H0;f++)a.appendChild(N0(n));return a}if(d.forEach((f,b)=>{a.appendChild(O0(f,b,n,s))}),(r==null?void 0:r.allowFreeText)!==!1){let f=n==="rows"?k0:E0;if(n==="rows"){let b=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let h=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=(u=e.freeTextPlaceholder)!=null?u:Rh,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),h.appendChild(S),b.appendChild(h);let T=Fh(n,s,d.length);T&&b.appendChild(T),a.appendChild(b)}else{let b=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(p=e.freeTextLabel)!=null?p:f,a.appendChild(b)}}return a},Oh=(r,e)=>{var a,s;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=(a=r.freeTextPlaceholder)!=null?a:Rh,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=(s=r.submitLabel)!=null?s:Ih,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},U0=r=>{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 t=v("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(n=r.submitLabel)!=null?n:Ih,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},q0=(r,e,t)=>{var l,u,m,p;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=t.backLabel)!=null?l:P0,o.setAttribute("data-ask-user-action","back"),o.disabled=r===0,n.appendChild(o);let a=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=v("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=t.skipLabel)!=null?u:I0,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=r===e-1;return i.textContent=d?(m=t.submitAllLabel)!=null?m:R0:(p=t.nextLabel)!=null?p:L0,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n},ca=r=>{let e=r.getAttribute(Hh);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Nh=(r,e)=>{r.setAttribute(Hh,JSON.stringify(e))},Wn=r=>{var t;let e=Number((t=r.getAttribute(Hd))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},z0=(r,e)=>{r.setAttribute(Hd,String(Math.max(0,Math.floor(e))))},qa=r=>{var t;let e=Number((t=r.getAttribute(Wd))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Fo=r=>r.getAttribute(Bd)==="true",$0=(r,e)=>{var o;let t=(o=r.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let n={};return e.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(n[s]=d)}}),n},V0=(r,e)=>{var n;let t=(n=r.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Vi=(r,e)=>{let{payload:t}=xo(e),n=Ns(t),o=ca(r),a={},s=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(a[l]=o[d]))}),a},_h=r=>{let e=ca(r),t=Wn(r),n=e[t],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let a=r.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",u=o.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=r.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!s.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Uh=r=>{if(!Fo(r))return;let e=ca(r),t=Wn(r),n=e[t],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=r.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!o);let s=r.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Dd=(r,e,t)=>{let n=$i(t),o=B0(r),{payload:a,complete:s}=xo(e),i=Fo(r),d=Wn(r),l=qa(r),u=i?F0(a,d):D0(a),m=!!(u!=null&&u.multiSelect),p=r.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${d+1}/${l}`:"");let f=r.querySelector('[data-ask-stepper="true"]');f&&f.remove();let b=r.querySelector('[data-ask-question="true"]');if(b){let M=typeof(u==null?void 0:u.question)=="string"?u.question:"";b.textContent=M,b.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let h=r.querySelector('[data-ask-pill-list="true"]');if(h){let M=_0(u,n,s,o);h.replaceWith(M)}if(o!=="rows"){let M=r.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Oh(n,o))}let S=r.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!S?r.appendChild(U0(n)):(!m||i)&&S&&S.remove(),r.setAttribute("data-multi-select",m?"true":"false");let T=r.querySelector('[data-ask-nav-row="true"]');if(i){let M=q0(d,l,n);T?T.replaceWith(M):r.appendChild(M)}else T&&T.remove();_h(r),Uh(r)},j0=(r,e,t)=>{let n=$i(e),o=W0(n),a=r.toolCall.id,s=Ns(t),i=Math.max(1,s.length),d=i>1,l=$0(r,s),u=d?V0(r,i):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ua,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",r.id),m.setAttribute(Wd,String(i)),m.setAttribute(Hd,String(u)),m.setAttribute(Bd,d?"true":"false"),m.setAttribute(Wh,o),Nh(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`),Dh(m,n);let p=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="",p.appendChild(f);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",p.appendChild(b),m.appendChild(p);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(Oh(n,o)),Dd(m,r,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},G0=(r,e,t)=>{let{payload:n}=xo(e),o=Math.max(1,Ns(n).length);o>qa(r)&&(r.setAttribute(Wd,String(o)),o>1&&!Fo(r)&&r.setAttribute(Bd,"true")),Dd(r,e,t)},qh=(r,e)=>{let t=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${r.id}`,t.setAttribute("data-message-id",r.id),t.setAttribute("data-bubble-type","ask-user-question");let n=$i(e);Dh(t,n);let o=v("span","persona-ask-stub-label"),{complete:a}=xo(r);return o.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},za=(r,e,t)=>{if(!t||!ho(r)||$i(e).enabled===!1)return;let o=r.toolCall.id;t.querySelectorAll(`[${Ua}]`).forEach(l=>{l.getAttribute(Ua)!==o&&l.remove()});let s=t.querySelector(`[${Ua}="${Bh(o)}"]`);if(s){G0(s,r,e);return}let{payload:i}=xo(r),d=j0(r,e,i);t.appendChild(d)},Oo=(r,e)=>{if(!r)return;let t=e?`[${Ua}="${Bh(e)}"]`:`[${Ua}]`;r.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(a)?a:180)})},Fd=r=>Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),No=(r,e)=>{let t=ca(r),n=Wn(r);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[n]:t[n]=e,Nh(r,t),_h(r),Uh(r)},ji=(r,e,t,n)=>{let o=qa(r),a=Math.max(0,Math.min(o-1,n));z0(r,a),Dd(r,e,t)};var Vn="suggest_replies";var Od={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Gi={name:Vn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:Od,origin:"sdk",annotations:{readOnlyHint:!0}},Nd=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_s=r=>{var e;return r.variant==="tool"&&((e=r.toolCall)==null?void 0:e.name)===Vn},_d=r=>{let e=r;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let n=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},Ki=r=>{var e;for(let t=r.length-1;t>=0;t--){let n=r[t];if(n.role==="user")return null;if(!_s(n))continue;let o=_d((e=n.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},zh=r=>{var t;let e=(t=r==null?void 0:r.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var Ud={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Fs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option \u2014 free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},qd={name:Os,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make \u2014 a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Ud,origin:"sdk",annotations:{readOnlyHint:!0}},Us=r=>{var n;let e=[],t=(n=r==null?void 0:r.features)==null?void 0:n.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(qd),zh(r)&&e.push(Gi),e};var bo=Li(zi(),1),Xi=r=>r.replace(/\\n/g,`
|
|
54
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),$a=r=>{if(r===null)return"null";if(r===void 0)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r,null,2)}catch{return String(r)}},K0=r=>{var s,i;let e=(s=r.completedAt)!=null?s:Date.now(),t=(i=r.startedAt)!=null?i:e,o=(r.durationMs!==void 0?r.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},$h=r=>r.status==="complete"?K0(r):r.status==="pending"?"Waiting":"",X0=r=>{var o,a,s;let t=(typeof r.duration=="number"?r.duration:typeof r.durationMs=="number"?r.durationMs:Math.max(0,((o=r.completedAt)!=null?o:Date.now())-((s=(a=r.startedAt)!=null?a:r.completedAt)!=null?s:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Vh=r=>r.status==="complete"?X0(r):"Using tool...",Qi=r=>{let e=r/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},zs=r=>{var t,n,o;let e=typeof r.duration=="number"?r.duration:typeof r.durationMs=="number"?r.durationMs:Math.max(0,((t=r.completedAt)!=null?t:Date.now())-((o=(n=r.startedAt)!=null?n:r.completedAt)!=null?o:Date.now()));return Qi(e)},Ji=r=>{var t,n,o;let e=r.durationMs!==void 0?r.durationMs:Math.max(0,((t=r.completedAt)!=null?t:Date.now())-((o=(n=r.startedAt)!=null?n:r.completedAt)!=null?o:Date.now()));return Qi(e)},zd=(r,e,t)=>{var a;if(!e)return t;let n=((a=r.name)==null?void 0:a.trim())||"tool",o=zs(r);return e.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Yi=(r,e)=>{let t=r.replace(/\{toolName\}/g,e),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=o.exec(t))!==null;)s.index>a&&qs(n,t.slice(a,s.index),[]),s[1]!==void 0?qs(n,s[1],["bold"]):s[2]!==void 0?qs(n,s[2],["italic"]):s[3]!==void 0&&qs(n,s[3],["dim"]),a=s.index+s[0].length;return a<t.length&&qs(n,t.slice(a),[]),n},qs=(r,e,t)=>{let n=e.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&r.push({text:n[o],styles:t}),o<n.length-1&&r.push({text:"{duration}",styles:t,isDuration:!0})},Q0=()=>{let r=null,e=0,t=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(o);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
55
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
56
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>r,processChunk:async n=>{if(n.length<=e)return r!==null?{text:r,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let a=t(n);return a!==null&&(r=a),e=n.length,r!==null?{text:r,raw:n}:null},close:async()=>{}}},pa=r=>{try{let e=JSON.parse(r);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Zi=()=>{let r={processChunk:e=>null,getExtractedText:()=>null};return r.__isPlainTextParser=!0,r},el=()=>{var e;let r=Q0();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:r.processChunk(t)},getExtractedText:r.getExtractedText.bind(r),close:(e=r.close)==null?void 0:e.bind(r)}},tl=()=>{let r=null,e=0;return{getExtractedText:()=>r,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=e)return r!==null||r===""?{text:r||"",raw:t}:null;try{let o=(0,bo.parse)(t,bo.STR|bo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?r=typeof o.text=="string"?Xi(o.text):"":o.type==="init"&&o.form?r="":typeof o.text=="string"&&(r=Xi(o.text)))}catch{}return e=t.length,r!==null?{text:r,raw:t}:null},close:()=>{}}},jh=r=>{let e=null,t=0,o=r||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Xi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Xi(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>e,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return e!==null?{text:e,raw:a}:null;try{let i=(0,bo.parse)(a,bo.STR|bo.OBJ),d=o(i);d!==null&&(e=d)}catch{}return t=a.length,{text:e||"",raw:a}},close:()=>{}}},rl=()=>{let r=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let n=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(r=n[1],{text:r,raw:e}):null},getExtractedText:()=>r}};var nl=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var a,s,i;let n=(i=(a=t==null?void 0:t.seq)!=null?a:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(e,t);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:e,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of e)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var J0="https://api.runtype.com/v1/dispatch",ol="https://api.runtype.com";function Y0(r){var a,s;let e=r.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(n)return`attachment.${n}`;let o=e.indexOf("/");if(o>0){let i=(s=(a=e.slice(o+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var $d=r=>!!(r.contentParts&&r.contentParts.length>0||r.llmContent&&r.llmContent.trim().length>0||r.rawContent&&r.rawContent.trim().length>0||r.content&&r.content.trim().length>0);function Z0(r){switch(r){case"json":return tl;case"regex-json":return el;case"xml":return rl;default:return Zi}}var Gh=r=>r.startsWith("{")||r.startsWith("[")||r.startsWith("<");function ev(r,e){if(!r)return e;let t=r.trim(),n=e.trim();if(t.length===0)return e;if(n.length===0)return r;let o=Gh(t);if(!Gh(n))return r;if(!o||n===t||n.startsWith(t))return e;let s=pa(r);return pa(e)!==null&&s===null?e:r}var ua=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,n,o,a;this.apiUrl=(t=e.apiUrl)!=null?t:J0,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(n=e.streamParser)!=null?n:Z0(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((a=e.webmcp)==null?void 0:a.enabled)===!0?new _a(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,n){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,n):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ol}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let e=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ol}/v1/client/feedback`}async sendFeedback(e){var a,s;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(s=(a=this.config).onSessionExpired)==null||s.call(a),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,a,s,i;let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(o=this.config).onSessionExpired)==null||a.call(o);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}let l=await this.buildPayload(e.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter($d).map(x=>{var C,w,E;return{id:x.id,role:x.role,content:(E=(w=(C=x.contentParts)!=null?C:x.llmContent)!=null?w:x.rawContent)!=null?E:x.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},p=l.clientTools,f=!!(p&&p.length>0),b=f?Eh(p):void 0,h=this.clientToolsFingerprintSessionId===d.sessionId,S=f&&h&&this.lastSentClientToolsFingerprint===b,T=!1,M=null,k;for(let x=0;;x++){let w={...m,...f&&(T||!S)&&p?{clientTools:p}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:n.signal}),k.status===409&&x===0&&f){let E=await k.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}M=E!=null?E:{error:"Chat request failed"}}break}if(!k.ok){let x=M!=null?M:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(k.status===429){let w=new Error(x.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let C=new Error(x.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!k.body){let x=new Error("No response body received");throw t({type:"error",error:x}),x}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(k.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(e,t){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let n=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var s;let o=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ol}/v1/agents/${e.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,n){var l,u;let o=this.isClientTokenMode(),a=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ol}/resume`,s;o&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=n==null?void 0:n.streamResponse)!=null?u:!0};return s&&(d.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(d),signal:n==null?void 0:n.signal})}async buildAgentPayload(e){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter($d).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Us(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(o.length>0&&(n.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(n.context=i)}return n}async buildPayload(e){var a,s;let n={messages:e.slice().filter($d).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Us(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(o.length>0&&(n.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(n.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...n},config:this.config});if(i&&typeof i=="object"){let d=i;return n.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=n.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return n}async handleCustomSSEEvent(e,t,n,o,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return n.current=m,o(m),m},l=u=>n.current?n.current:d(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),s.current=null,t({type:"status",status:"idle"})),i.error&&(s.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,n){var Bt,or,hr,sn;let o=e.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=F=>{let fe=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Ie=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Xe=F.tools?F.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...F,reasoning:fe,toolCall:Ie,tools:Xe}},m=F=>{if(F.role!=="assistant"||F.variant)return!0;let fe=Array.isArray(F.contentParts)&&F.contentParts.length>0,Ie=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||fe||Ie||!!F.stopReason},p=F=>{m(F)&&t({type:"message",message:u(F)})},f=null,b=null,h={current:null},S={current:null},T=!1,M=new Map,k=new Map,x=new Map,C=new Map,w={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},H=(F,fe,Ie="")=>`${F}::${fe}::${Ie}`,I=(F,fe)=>`${F}::${fe}::`,L=(F,fe,Ie,Xe)=>{let Fe=H(F,fe,Ie),Ne=x.get(Fe);if(Ne)return Ne;let Ye=Ie?`-${Ie}`:"",At={id:`nested-${F}-${fe}${Ye}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ie?{partId:Ie}:{},agentMetadata:{executionId:Xe,parentToolId:F,parentStepId:fe}};return x.set(Fe,At),p(At),At},O=F=>{if(F==null)return null;try{return String(F)}catch{return null}},$=F=>{var fe,Ie,Xe,Fe,Ne;return O((Ne=(Fe=(Xe=(Ie=(fe=F.stepId)!=null?fe:F.step_id)!=null?Ie:F.step)!=null?Xe:F.parentId)!=null?Fe:F.flowStepId)!=null?Ne:F.flow_step_id)},te=F=>{var fe,Ie,Xe,Fe,Ne,Ye,At;return O((At=(Ye=(Ne=(Fe=(Xe=(Ie=(fe=F.callId)!=null?fe:F.call_id)!=null?Ie:F.requestId)!=null?Xe:F.request_id)!=null?Fe:F.toolCallId)!=null?Ne:F.tool_call_id)!=null?Ye:F.stepId)!=null?At:F.step_id)},xe=n,Je=!1,we=()=>{if(f)return f;let F;return!Je&&xe?(F=xe,Je=!0):xe&&S.current?F=`${xe}_${S.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},De=(F,fe)=>{w.lastId=fe,F&&w.byStep.set(F,fe)},Ae=(F,fe)=>{var Ne;let Ie=(Ne=F.reasoningId)!=null?Ne:F.id,Xe=$(F);if(Ie){let Ye=String(Ie);return De(Xe,Ye),Ye}if(Xe){let Ye=w.byStep.get(Xe);if(Ye)return w.lastId=Ye,Ye}if(w.lastId&&!fe)return w.lastId;if(!fe)return null;let Fe=`reason-${l()}`;return De(Xe,Fe),Fe},qe=F=>{let fe=M.get(F);if(fe)return fe;let Ie={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return M.set(F,Ie),p(Ie),Ie},He=(F,fe)=>{E.lastId=fe,F&&E.byCall.set(F,fe)},J=new Set,re=new Map,Q=new Set,ge=new Map,Z=F=>{if(!F)return!1;let fe=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return fe==="emit_artifact_markdown"||fe==="emit_artifact_component"},G=(F,fe)=>{var Ne;let Ie=(Ne=F.toolId)!=null?Ne:F.id,Xe=te(F);if(Ie){let Ye=String(Ie);return He(Xe,Ye),Ye}if(Xe){let Ye=E.byCall.get(Xe);if(Ye)return E.lastId=Ye,Ye}if(E.lastId&&!fe)return E.lastId;if(!fe)return null;let Fe=`tool-${l()}`;return He(Xe,Fe),Fe},pe=F=>{let fe=k.get(F);if(fe)return fe;let Ie={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return k.set(F,Ie),p(Ie),Ie},ke=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let fe=Number(F);if(!Number.isNaN(fe)&&Number.isFinite(fe))return fe;let Ie=Date.parse(F);if(!Number.isNaN(Ie))return Ie}return Date.now()},le=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ne=new Map,de=new Map,Et=new Map,wt=new Map,We=null,he=(F,fe,Ie)=>{var At;let Xe=Et.get(F);Xe||(Xe=[],Et.set(F,Xe));let Fe=0,Ne=Xe.length;for(;Fe<Ne;){let Xt=Fe+Ne>>>1;Xe[Xt].seq<fe?Fe=Xt+1:Ne=Xt}((At=Xe[Fe])==null?void 0:At.seq)===fe?Xe[Fe]={seq:fe,text:Ie}:Xe.splice(Fe,0,{seq:fe,text:Ie});let Ye="";for(let Xt=0;Xt<Xe.length;Xt++)Ye+=Xe[Xt].text;return Ye},at=(F,fe)=>{let Ie=le(fe),Xe=de.get(F.id),Fe=ev(Xe,Ie);F.rawContent=Fe;let Ne=ne.get(F.id),Ye=mt=>{var ye;let it=(ye=F.content)!=null?ye:"";mt.trim()!==""&&(it.trim().length===0||mt.startsWith(it)||mt.trimStart().startsWith(it.trim()))&&(F.content=mt)},At=()=>{var mt;if(Ne){let it=(mt=Ne.close)==null?void 0:mt.call(Ne);it instanceof Promise&&it.catch(()=>{})}ne.delete(F.id),de.delete(F.id),F.streaming=!1,p(F)};if(!Ne){Ye(Ie),At();return}let Xt=pa(Fe);if(Xt!==null&&Xt.trim()!==""){Ye(Xt),At();return}let ar=mt=>{var ie;let it=typeof mt=="string"?mt:(ie=mt==null?void 0:mt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let ye=Ne.getExtractedText();return ye!==null&&ye.trim()!==""?ye:Ie},K;try{K=Ne.processChunk(Fe)}catch{Ye(Ie),At();return}if(K instanceof Promise){K.then(mt=>{Ye(ar(mt)),At()}).catch(()=>{Ye(Ie),At()});return}Ye(ar(K)),At()},Re=[],j=!1,ue,nt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,ue()}))},Rt=new nl((F,fe)=>{Re.push({payloadType:F,payload:fe}),nt()}),ee=null,Ge=new Map,Fr=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(ue=()=>{var F,fe,Ie,Xe,Fe,Ne,Ye,At,Xt,ar,K,mt,it,ye,ie,st,pr,pt,yr,Rr,ut,Lt,tt,zt,vr,sr,ur,Mr,un,St,qr,xr,Mn,ln,yt,Gn,kn,_e,R,se,Ee,Ot,et,Nt,Yt,lr,vt,zr,$t,$r,Dn,oo,Ao,fn,Vt,Qr,En,So,ao,To,Kn,mn,Fn,Tt,Cr,wr,gn,Mo,ve,On,Ln,q,Sa,Xn,so,io,Qn,Nn,as,hn,xn,_n,Un,Vo,lo,Vr,Jn,Ta,jo,Ma,fi,ka,mi,Ea,Pt,ss,Pn,dn,gi,hi,La,co,is,ko,ls,ds,cs,ps,cn,Pa,Yn,Zn,us,xi,fs,ms,Go,bi,yi,vi,Ci,sd,Ko,Eo,wi,gs,Lo,Ai,hs,Po,xs,Si,po,Ti,Ro,jt,Ra,Ia;for(let Xo=0;Xo<Re.length;Xo++){let je=Re[Xo].payloadType,P=Re[Xo].payload;if(je==="reason_start"){let z=(F=Ae(P,!0))!=null?F:`reason-${l()}`,B=qe(z);B.reasoning=(fe=B.reasoning)!=null?fe:{id:z,status:"streaming",chunks:[]},B.reasoning.startedAt=(Xe=B.reasoning.startedAt)!=null?Xe:ke((Ie=P.startedAt)!=null?Ie:P.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",p(B)}else if(je==="reason_delta"||je==="reason_chunk"){let z=(Ne=(Fe=Ae(P,!1))!=null?Fe:Ae(P,!0))!=null?Ne:`reason-${l()}`,B=qe(z);B.reasoning=(Ye=B.reasoning)!=null?Ye:{id:z,status:"streaming",chunks:[]},B.reasoning.startedAt=(Xt=B.reasoning.startedAt)!=null?Xt:ke((At=P.startedAt)!=null?At:P.timestamp);let oe=(mt=(K=(ar=P.reasoningText)!=null?ar:P.text)!=null?K:P.delta)!=null?mt:"";if(oe&&P.hidden!==!0){let ce=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(ce!==void 0){let X=he(z,ce,String(oe));B.reasoning.chunks=[X]}else B.reasoning.chunks.push(String(oe))}if(B.reasoning.status=P.done?"complete":"streaming",P.done){B.reasoning.completedAt=ke((it=P.completedAt)!=null?it:P.timestamp);let ce=(ye=B.reasoning.startedAt)!=null?ye:Date.now();B.reasoning.durationMs=Math.max(0,((ie=B.reasoning.completedAt)!=null?ie:Date.now())-ce)}B.streaming=B.reasoning.status!=="complete",p(B)}else if(je==="reason_complete"){let z=(pr=(st=Ae(P,!1))!=null?st:Ae(P,!0))!=null?pr:`reason-${l()}`,B=M.get(z);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=ke((pt=P.completedAt)!=null?pt:P.timestamp);let ce=(yr=B.reasoning.startedAt)!=null?yr:Date.now();B.reasoning.durationMs=Math.max(0,((Rr=B.reasoning.completedAt)!=null?Rr:Date.now())-ce),B.streaming=!1,p(B)}let oe=$(P);oe&&w.byStep.delete(oe)}else if(je==="tool_start"){let z=(ut=G(P,!0))!=null?ut:`tool-${l()}`,B=(Lt=P.toolName)!=null?Lt:P.name;if(Z(B)){J.add(z);continue}let oe=pe(z),ce=(tt=oe.toolCall)!=null?tt:{id:z,status:"pending"};ce.name=B!=null?B:ce.name,ce.status="running",P.args!==void 0?ce.args=P.args:P.parameters!==void 0&&(ce.args=P.parameters),ce.startedAt=(vr=ce.startedAt)!=null?vr:ke((zt=P.startedAt)!=null?zt:P.timestamp),ce.completedAt=void 0,ce.durationMs=void 0,oe.toolCall=ce,oe.streaming=!0;let X=P.agentContext;(X||P.executionId)&&(oe.agentMetadata={executionId:(sr=X==null?void 0:X.executionId)!=null?sr:P.executionId,iteration:(ur=X==null?void 0:X.iteration)!=null?ur:P.iteration}),p(oe)}else if(je==="tool_chunk"||je==="tool_delta"){let z=(un=(Mr=G(P,!1))!=null?Mr:G(P,!0))!=null?un:`tool-${l()}`;if(J.has(z))continue;let B=pe(z),oe=(St=B.toolCall)!=null?St:{id:z,status:"running"};oe.startedAt=(xr=oe.startedAt)!=null?xr:ke((qr=P.startedAt)!=null?qr:P.timestamp);let ce=(yt=(ln=(Mn=P.text)!=null?Mn:P.delta)!=null?ln:P.message)!=null?yt:"";ce&&(oe.chunks=(Gn=oe.chunks)!=null?Gn:[],oe.chunks.push(String(ce))),oe.status="running",B.toolCall=oe,B.streaming=!0;let X=P.agentContext;(X||P.executionId)&&(B.agentMetadata=(R=B.agentMetadata)!=null?R:{executionId:(kn=X==null?void 0:X.executionId)!=null?kn:P.executionId,iteration:(_e=X==null?void 0:X.iteration)!=null?_e:P.iteration}),p(B)}else if(je==="tool_complete"){let z=(Ee=(se=G(P,!1))!=null?se:G(P,!0))!=null?Ee:`tool-${l()}`;if(J.has(z)){J.delete(z);continue}let B=pe(z),oe=(Ot=B.toolCall)!=null?Ot:{id:z,status:"running"};oe.status="complete",P.result!==void 0&&(oe.result=P.result),typeof P.duration=="number"&&(oe.duration=P.duration),oe.completedAt=ke((et=P.completedAt)!=null?et:P.timestamp);let ce=(Nt=P.duration)!=null?Nt:P.executionTime;if(typeof ce=="number")oe.durationMs=ce;else{let $e=(Yt=oe.startedAt)!=null?Yt:Date.now();oe.durationMs=Math.max(0,((lr=oe.completedAt)!=null?lr:Date.now())-$e)}B.toolCall=oe,B.streaming=!1;let X=P.agentContext;(X||P.executionId)&&(B.agentMetadata=($t=B.agentMetadata)!=null?$t:{executionId:(vt=X==null?void 0:X.executionId)!=null?vt:P.executionId,iteration:(zr=X==null?void 0:X.iteration)!=null?zr:P.iteration}),p(B);let Le=te(P);Le&&E.byCall.delete(Le)}else if(je==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let z=typeof P.toolCallId=="string"&&P.toolCallId.length>0?P.toolCallId:void 0,B=($r=z!=null?z:P.toolId)!=null?$r:`local-${l()}`,oe=pe(B),ce=P.toolName,X=da(ce),Le=(Dn=oe.toolCall)!=null?Dn:{id:B,status:"pending"};Le.name=ce,Le.args=P.parameters,Le.status=X?"running":"complete",Le.chunks=(oo=Le.chunks)!=null?oo:[],Le.startedAt=(fn=Le.startedAt)!=null?fn:ke((Ao=P.startedAt)!=null?Ao:P.timestamp),X?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=(Vt=Le.completedAt)!=null?Vt:Le.startedAt,oe.toolCall=Le,oe.streaming=!1,oe.agentMetadata={...oe.agentMetadata,executionId:(En=P.executionId)!=null?En:(Qr=oe.agentMetadata)==null?void 0:Qr.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},p(oe)}else if(je==="text_start"){if((So=P.toolContext)!=null&&So.toolId)continue;let z=P.partId;if(z!==void 0&&S.current!==null&&z!==S.current){let B=f;B&&(B.streaming=!1,p(B),We=B,f=null,T=!0)}z!==void 0&&(S.current=z)}else if(je==="text_end"){if((ao=P.toolContext)!=null&&ao.toolId)continue;let z=f;z&&(z.streaming=!1,p(z),We=z,f=null,T=!0)}else if(je==="step_chunk"||je==="step_delta"){let z=P.stepType,B=P.executionType;if(z==="tool"||B==="context")continue;let oe=P.toolContext;if(oe!=null&&oe.toolId){let $e=String((Kn=(To=P.id)!=null?To:oe.stepId)!=null?Kn:`step-${l()}`),gt=P.partId!==void 0&&P.partId!==null?String(P.partId):"",lt=`${oe.toolId}::${$e}`,qt=C.get(lt);if(gt!==""&&qt!==void 0&&qt!==""&&qt!==gt){let ft=x.get(H(oe.toolId,$e,qt));ft&&ft.streaming!==!1&&(ft.streaming=!1,p(ft))}gt!==""&&C.set(lt,gt);let Zt=L(oe.toolId,$e,gt,oe.executionId),Ir=(Cr=(Tt=(Fn=(mn=P.text)!=null?mn:P.delta)!=null?Fn:P.content)!=null?Tt:P.chunk)!=null?Cr:"";Ir&&(Zt.content+=String(Ir),Zt.streaming=!0,p(Zt)),P.isComplete&&(Zt.streaming=!1,p(Zt));continue}let ce=P.partId;if(ce!==void 0&&S.current!==null&&ce!==S.current){let $e=f;$e&&($e.streaming=!1,p($e),We=$e,f=null,T=!0)}ce!==void 0&&(S.current=ce);let X=ce!==void 0&&(wr=wt.get(ce))!=null?wr:we();ce!==void 0&&(X.partId||(X.partId=ce),wt.set(ce,X));let Le=(On=(ve=(Mo=(gn=P.text)!=null?gn:P.delta)!=null?Mo:P.content)!=null?ve:P.chunk)!=null?On:"";if(Le){let $e=typeof P.seq=="number"?P.seq:void 0,gt=ce!=null?ce:X.id,lt=$e!==void 0?he(gt,$e,String(Le)):((Ln=de.get(X.id))!=null?Ln:"")+Le;X.rawContent=lt,ne.has(X.id)||ne.set(X.id,this.createStreamParser());let qt=ne.get(X.id),Zt=lt.trim().startsWith("{")||lt.trim().startsWith("[");if(Zt&&de.set(X.id,lt),qt.__isPlainTextParser===!0){X.content=$e!==void 0?lt:X.content+Le,de.delete(X.id),ne.delete(X.id),X.rawContent=void 0,p(X);continue}let ft=qt.processChunk(lt);if(ft instanceof Promise)ft.then(Mt=>{var Ze;let br=typeof Mt=="string"?Mt:(Ze=Mt==null?void 0:Mt.text)!=null?Ze:null;if(br!==null&&br.trim()!=="")X.content=br,p(X);else if(!Zt&&!lt.trim().startsWith("<")){let _r=f,fr=_r&&_r.id===X.id?_r:X;fr.id===X.id&&(fr.content=$e!==void 0?lt:fr.content+Le,de.delete(fr.id),ne.delete(fr.id),fr.rawContent=void 0,p(fr))}}).catch(()=>{X.content=$e!==void 0?lt:X.content+Le,de.delete(X.id),ne.delete(X.id),X.rawContent=void 0,p(X)});else{let Mt=typeof ft=="string"?ft:(q=ft==null?void 0:ft.text)!=null?q:null;Mt!==null&&Mt.trim()!==""?(X.content=Mt,p(X)):!Zt&&!lt.trim().startsWith("<")&&(X.content=$e!==void 0?lt:X.content+Le,de.delete(X.id),ne.delete(X.id),X.rawContent=void 0,p(X))}}if(P.isComplete){let $e=(Xn=(Sa=P.result)==null?void 0:Sa.response)!=null?Xn:X.content;if($e){let gt=de.get(X.id),lt=gt!=null?gt:le($e);X.rawContent=lt;let qt=ne.get(X.id),Zt=null,Ir=!1;if(qt&&(Zt=qt.getExtractedText(),Zt===null&&(Zt=pa(lt)),Zt===null)){let ft=qt.processChunk(lt);ft instanceof Promise?(Ir=!0,ft.then(Mt=>{var Ze;let br=typeof Mt=="string"?Mt:(Ze=Mt==null?void 0:Mt.text)!=null?Ze:null;if(br!==null){let _r=f;_r&&_r.id===X.id&&(_r.content=br,_r.streaming=!1,ne.delete(_r.id),de.delete(_r.id),p(_r))}})):Zt=typeof ft=="string"?ft:(so=ft==null?void 0:ft.text)!=null?so:null}if(!Ir){Zt!==null&&Zt.trim()!==""?X.content=Zt:de.has(X.id)||(X.content=le($e));let ft=ne.get(X.id);if(ft){let Mt=(io=ft.close)==null?void 0:io.call(ft);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(X.id)}de.delete(X.id),X.streaming=!1,p(X)}}}}else if(je==="step_complete"){let z=P.stepType,B=P.executionType;if(z==="tool"||B==="context")continue;let oe=P.toolContext;if(oe!=null&&oe.toolId){let $e=String((Nn=(Qn=P.id)!=null?Qn:oe.stepId)!=null?Nn:"");if($e){let gt=I(oe.toolId,$e);for(let[lt,qt]of x)lt.startsWith(gt)&&qt.streaming!==!1&&(qt.streaming=!1,p(qt));C.delete(`${oe.toolId}::${$e}`)}continue}let ce=P.stopReason;if(T){if(f!==null){let lt=f;ce&&(lt.stopReason=ce),ne.delete(lt.id),de.delete(lt.id),lt.streaming!==!1&&(lt.streaming=!1,p(lt))}let $e=(as=P.result)==null?void 0:as.response,gt=We;gt&&(ce&&(gt.stopReason=ce),$e!=null?at(gt,$e):(ne.delete(gt.id),de.delete(gt.id))),We=null;continue}let X=(hn=P.result)==null?void 0:hn.response,Le=we();if(ce&&(Le.stopReason=ce),X!=null){let $e=ne.get(Le.id),gt=!1,lt=!1;if($e){let qt=$e.getExtractedText(),Zt=de.get(Le.id),Ir=Zt!=null?Zt:le(X);if(Le.rawContent=Ir,qt!==null&&qt.trim()!=="")Le.content=qt,gt=!0;else{let ft=pa(Ir);if(ft!==null)Le.content=ft,gt=!0;else{let Mt=$e.processChunk(Ir);if(Mt instanceof Promise)lt=!0,Mt.then(br=>{var _r;let Ze=typeof br=="string"?br:(_r=br==null?void 0:br.text)!=null?_r:null;if(Ze!==null&&Ze.trim()!==""){let fr=f;fr&&fr.id===Le.id&&(fr.content=Ze,fr.streaming=!1,ne.delete(fr.id),de.delete(fr.id),p(fr))}else{let fr=$e.getExtractedText(),Or=f;Or&&Or.id===Le.id&&(fr!==null&&fr.trim()!==""?Or.content=fr:de.has(Or.id)||(Or.content=le(X)),Or.streaming=!1,ne.delete(Or.id),de.delete(Or.id),p(Or))}});else{let br=typeof Mt=="string"?Mt:(xn=Mt==null?void 0:Mt.text)!=null?xn:null;if(br!==null&&br.trim()!=="")Le.content=br,gt=!0;else{let Ze=$e.getExtractedText();Ze!==null&&Ze.trim()!==""&&(Le.content=Ze,gt=!0)}}}}}if(!lt){if(!Le.rawContent){let qt=de.get(Le.id);Le.rawContent=qt!=null?qt:le(X)}if(!gt&&!de.has(Le.id)&&(Le.content=le(X)),$e){let qt=(_n=$e.close)==null?void 0:_n.call($e);qt instanceof Promise&&qt.catch(()=>{})}ne.delete(Le.id),de.delete(Le.id),Le.streaming=!1,p(Le)}}else ne.delete(Le.id),de.delete(Le.id),Le.streaming=!1,p(Le)}else if(je==="flow_complete"){let z=(Un=P.result)==null?void 0:Un.response;if(T){if(f!==null){let B=f;ne.delete(B.id),de.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}}else if(z!=null){let B=we(),oe=de.get(B.id),ce=oe!=null?oe:le(z);B.rawContent=ce;let X=le(z),Le=ne.get(B.id);if(Le){let lt=pa(ce);if(lt!==null)X=lt;else{let qt=Le.processChunk(ce);qt instanceof Promise&&qt.then(Ir=>{var Mt;let ft=typeof Ir=="string"?Ir:(Mt=Ir==null?void 0:Ir.text)!=null?Mt:null;ft!==null&&(B.content=ft,B.streaming=!1,p(B))});let Zt=Le.getExtractedText();Zt!==null&&(X=Zt)}}ne.delete(B.id),de.delete(B.id);let $e=X!==B.content,gt=B.streaming!==!1;$e&&(B.content=X),B.streaming=!1,($e||gt)&&p(B)}else if(f!==null){let B=f;ne.delete(B.id),de.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}t({type:"status",status:"idle"})}else if(je==="agent_start")ee={executionId:P.executionId,agentId:(Vo=P.agentId)!=null?Vo:"virtual",agentName:(lo=P.agentName)!=null?lo:"",status:"running",currentIteration:0,maxTurns:(Vr=P.maxTurns)!=null?Vr:1,startedAt:ke(P.startedAt)};else if(je==="agent_iteration_start"){if(ee&&(ee.currentIteration=P.iteration),Fr==="separate"&&P.iteration>1){let z=f;z&&(z.streaming=!1,p(z),Ge.set(P.iteration-1,z),f=null)}}else if(je==="agent_turn_start")b=null;else if(je==="agent_turn_delta"){if(P.contentType==="text"){let z=we();z.content+=(Jn=P.delta)!=null?Jn:"",z.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:ee==null?void 0:ee.agentName},b=z,p(z)}else if(P.contentType==="thinking"){let z=(Ta=P.turnId)!=null?Ta:`agent-think-${P.iteration}`,B=qe(z);B.reasoning=(jo=B.reasoning)!=null?jo:{id:z,status:"streaming",chunks:[]},B.reasoning.chunks.push((Ma=P.delta)!=null?Ma:""),B.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId},p(B)}else if(P.contentType==="tool_input"){let z=(fi=P.toolCallId)!=null?fi:E.lastId;if(z){let B=k.get(z);B!=null&&B.toolCall&&(B.toolCall.chunks=(ka=B.toolCall.chunks)!=null?ka:[],B.toolCall.chunks.push((mi=P.delta)!=null?mi:""),p(B))}}}else if(je==="agent_turn_complete"){let z=P.turnId;if(z){let ce=M.get(z);if(ce!=null&&ce.reasoning){ce.reasoning.status="complete",ce.reasoning.completedAt=ke(P.completedAt);let X=(Ea=ce.reasoning.startedAt)!=null?Ea:Date.now();ce.reasoning.durationMs=Math.max(0,((Pt=ce.reasoning.completedAt)!=null?Pt:Date.now())-X),ce.streaming=!1,p(ce)}}let B=P.stopReason,oe=f!=null?f:b;if(B&&oe!==null){let ce=P.turnId;(!ce||((ss=oe.agentMetadata)==null?void 0:ss.turnId)===ce)&&(oe.stopReason=B,p(oe))}}else if(je==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let z=(Pn=P.toolCallId)!=null?Pn:`agent-tool-${l()}`;He(te(P),z);let B=pe(z),oe=(dn=B.toolCall)!=null?dn:{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};oe.name=(hi=(gi=P.toolName)!=null?gi:P.name)!=null?hi:oe.name,oe.status="running",P.parameters!==void 0&&(oe.args=P.parameters),oe.startedAt=ke((La=P.startedAt)!=null?La:P.timestamp),B.toolCall=oe,B.streaming=!0,B.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(B)}else if(je==="agent_tool_delta"){let z=(co=P.toolCallId)!=null?co:E.lastId;if(z){let B=(is=k.get(z))!=null?is:pe(z);B.toolCall&&(B.toolCall.chunks=(ko=B.toolCall.chunks)!=null?ko:[],B.toolCall.chunks.push((ls=P.delta)!=null?ls:""),B.toolCall.status="running",B.streaming=!0,p(B))}}else if(je==="agent_tool_complete"){let z=(ds=P.toolCallId)!=null?ds:E.lastId;if(z){let B=(cs=k.get(z))!=null?cs:pe(z);if(B.toolCall){B.toolCall.status="complete",P.result!==void 0&&(B.toolCall.result=P.result),typeof P.executionTime=="number"&&(B.toolCall.durationMs=P.executionTime),B.toolCall.completedAt=ke((ps=P.completedAt)!=null?ps:P.timestamp),B.streaming=!1,p(B);let oe=te(P);oe&&E.byCall.delete(oe)}}}else if(je==="agent_media"){let z=Array.isArray(P.media)?P.media:[],B=[];for(let oe of z){if(!oe||typeof oe!="object")continue;let ce=oe,X=typeof ce.type=="string"?ce.type:void 0,Le=typeof ce.mediaType=="string"?ce.mediaType.toLowerCase():"",$e=null,gt="";if(X==="media"){let lt=typeof ce.data=="string"?ce.data:void 0;if(!lt)continue;gt=Le.length>0?Le:"application/octet-stream",$e=`data:${gt};base64,${lt}`}else if(X==="image-url"){let lt=typeof ce.url=="string"?ce.url:void 0;if(!lt)continue;gt=Le,$e=lt}else if(X==="file-url"){let lt=typeof ce.url=="string"?ce.url:void 0;if(!lt)continue;gt=Le,$e=lt}else continue;if($e)if(X==="image-url"||gt.startsWith("image/"))B.push({type:"image",image:$e,...gt?{mimeType:gt}:{}});else if(gt.startsWith("audio/"))B.push({type:"audio",audio:$e,mimeType:gt});else if(gt.startsWith("video/"))B.push({type:"video",video:$e,mimeType:gt});else{let lt=gt||"application/octet-stream";B.push({type:"file",data:$e,mimeType:lt,filename:Y0(lt)})}}if(B.length>0){let oe=l(),ce=P.toolCallId,Le={id:`agent-media-${typeof ce=="string"&&ce.length>0?`${ce}-${oe}`:String(oe)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:oe,agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(Le);let $e=f;$e&&($e.streaming=!1,p($e)),f=null,h.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let z=`agent-reflection-${P.executionId}-${P.iteration}`,B={id:z,role:"assistant",content:(cn=P.reflection)!=null?cn:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Pa=P.reflection)!=null?Pa:""]},agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(B)}else if(je==="agent_complete"){ee&&(ee.status=P.success?"complete":"error",ee.completedAt=ke(P.completedAt),ee.stopReason=P.stopReason);let z=f;z&&(z.streaming=!1,p(z)),t({type:"status",status:"idle"})}else if(je==="agent_error"){let z=typeof P.error=="string"?P.error:(Zn=(Yn=P.error)==null?void 0:Yn.message)!=null?Zn:"Agent execution error";P.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):t({type:"error",error:new Error(z)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let z=(us=P.approvalId)!=null?us:`approval-${l()}`,B={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(xi=ee==null?void 0:ee.agentId)!=null?xi:"virtual",executionId:(ms=(fs=P.executionId)!=null?fs:ee==null?void 0:ee.executionId)!=null?ms:"",toolName:(Go=P.toolName)!=null?Go:"",toolType:P.toolType,description:(yi=P.description)!=null?yi:`Execute ${(bi=P.toolName)!=null?bi:"tool"}`,...typeof P.reason=="string"&&P.reason?{reason:P.reason}:{},parameters:P.parameters}};p(B)}else if(je==="step_await"&&P.awaitReason==="approval_required"){let z=(vi=P.approvalId)!=null?vi:`approval-${l()}`,B={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ci=ee==null?void 0:ee.agentId)!=null?Ci:"virtual",executionId:(Ko=(sd=P.executionId)!=null?sd:ee==null?void 0:ee.executionId)!=null?Ko:"",toolName:(Eo=P.toolName)!=null?Eo:"",toolType:P.toolType,description:(gs=P.description)!=null?gs:`Execute ${(wi=P.toolName)!=null?wi:"tool"}`,...typeof P.reason=="string"&&P.reason?{reason:P.reason}:{},parameters:P.parameters}};p(B)}else if(je==="agent_approval_complete"){let z=P.approvalId;if(z){let oe={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(Lo=P.decision)!=null?Lo:"approved",agentId:(Ai=ee==null?void 0:ee.agentId)!=null?Ai:"virtual",executionId:(Po=(hs=P.executionId)!=null?hs:ee==null?void 0:ee.executionId)!=null?Po:"",toolName:(xs=P.toolName)!=null?xs:"",description:(Si=P.description)!=null?Si:"",resolvedAt:Date.now()}};p(oe)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let z=P.artifactType,B=String(P.id),oe=typeof P.title=="string"?P.title:void 0;if(t({type:"artifact_start",id:B,artifactType:z,title:oe,component:typeof P.component=="string"?P.component:void 0}),ge.set(B,{markdown:"",title:oe}),!Q.has(B)){Q.add(B);let ce={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:oe,artifactType:z,status:"streaming"}})};re.set(B,ce),p(ce)}}else if(je==="artifact_delta"){let z=String(P.id),B=typeof P.delta=="string"?P.delta:String((po=P.delta)!=null?po:"");t({type:"artifact_delta",id:z,artDelta:B});let oe=ge.get(z);oe&&(oe.markdown+=B)}else if(je==="artifact_update"){let z=P.props&&typeof P.props=="object"&&!Array.isArray(P.props)?P.props:{};t({type:"artifact_update",id:String(P.id),props:z,component:typeof P.component=="string"?P.component:void 0})}else if(je==="artifact_complete"){let z=String(P.id);t({type:"artifact_complete",id:z});let B=re.get(z);if(B){B.streaming=!1;try{let oe=JSON.parse((Ti=B.rawContent)!=null?Ti:"{}");if(oe.props){oe.props.status="complete";let ce=ge.get(z);ce!=null&&ce.markdown&&(oe.props.markdown=ce.markdown)}B.rawContent=JSON.stringify(oe)}catch{}ge.delete(z),p(B),re.delete(z)}}}else if(je==="transcript_insert"){let z=P.message;if(!z||typeof z!="object")continue;let B=String((Ro=z.id)!=null?Ro:`msg-${l()}`),oe=z.role,X={id:B,role:oe==="user"?"user":oe==="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(p(X),X.rawContent)try{let Le=JSON.parse(X.rawContent),$e=(jt=Le==null?void 0:Le.props)==null?void 0:jt.artifactId;typeof $e=="string"&&Q.add($e)}catch{}f=null,h.current=null,ne.delete(B),de.delete(B)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let z=null;if(P.error instanceof Error)z=P.error;else if(je==="dispatch_error"){let B=(Ra=P.message)!=null?Ra:P.error;B!=null&&B!==""&&(z=new Error(String(B)))}else if(je==="step_error"||je==="flow_error"){let B=P.error;typeof B=="string"&&B!==""?z=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(z=new Error(String((Ia=B.message)!=null?Ia:B)))}else je==="error"&&P.error!=null&&P.error!==""&&(z=new Error(String(P.error)));if(z){t({type:"error",error:z});let B=f;B&&B.streaming&&(B.streaming=!1,p(B)),t({type:"status",status:"idle"})}}}}}Re.length=0};;){let{done:F,value:fe}=await o.read();if(F)break;s+=a.decode(fe,{stream:!0});let Ie=s.split(`
|
|
60
57
|
|
|
61
|
-
`);
|
|
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}
|
|
58
|
+
`);s=(or=Ie.pop())!=null?or:"";for(let Xe of Ie){let Fe=Xe.split(`
|
|
59
|
+
`),Ne="message",Ye="";for(let ar of Fe)ar.startsWith("event:")?Ne=ar.replace("event:","").trim():ar.startsWith("data:")&&(Ye+=ar.replace("data:","").trim());if(!Ye)continue;let At;try{At=JSON.parse(Ye)}catch(ar){t({type:"error",error:ar instanceof Error?ar:new Error("Failed to parse chat stream payload")});continue}let Xt=Ne!=="message"?Ne:(hr=At.type)!=null?hr:"message";if((sn=this.onSSEEvent)==null||sn.call(this,Xt,At),this.parseSSEEvent){h.current=f;let ar=await this.handleCustomSSEEvent(At,t,h,p,l,S);if(h.current&&h.current!==f&&(f=h.current),ar)continue}Rt.push(Xt,At),ue()}}Rt.flushPending(),ue(),Rt.destroy()}};function Kh(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${r}_${e}`}function Va(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${r}_${e}`}function fa(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${r}_${e}`}var al="[Image]";function Xh(r){return typeof r=="string"?[{type:"text",text:r}]:r}function Qh(r){return typeof r=="string"?r:r.filter(e=>e.type==="text").map(e=>e.text).join("")}function Jh(r){return typeof r=="string"?!1:r.some(e=>e.type==="image")}function Yh(r){return typeof r=="string"?[]:r.filter(e=>e.type==="image")}function $s(r){return{type:"text",text:r}}function Zh(r,e){return{type:"image",image:r,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function ex(r){return new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;e({type:"image",image:o,mimeType:r.type,alt:r.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(r)})}function tx(r,e=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var rx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],tv=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],yo=[...rx,...tv];function rv(r){return rx.includes(r)||r.startsWith("image/")}function sl(r){return rv(r.type)}async function nx(r){return new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;sl(r)?e({type:"image",image:o,mimeType:r.type,alt:r.name}):e({type:"file",data:o,mimeType:r.type,filename:r.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(r)})}function ox(r,e=yo,t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${r.type}". Accepted types: ${e.join(", ")}`}}function nv(r){let e=r.split(".");return e.length>1?e.pop().toLowerCase():""}function ax(r,e){let t=nv(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[r]||t||"FILE"}var il=class{constructor(e=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=e}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(t),a=n.createBuffer(1,o.length,this.sampleRate);a.getChannelData(0).set(o);let s=n.createBufferSource();s.buffer=a,s.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=a.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,s.onended=()=>{let d=this.activeSources.indexOf(s);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),n=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=0;a<t;a++){let s=o.getInt16(a*2,!0);n[a]=s/32768}return n}};var ll=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,t,n,o,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(t),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let s=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(s);let i=0;for(let u=0;u<s.length;u++)i+=s[u]*s[u];let d=Math.sqrt(i/s.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,a()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Vs=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 ll;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let a=o.location.protocol==="https:"?"wss:":"ws:",s=(e=this.config)==null?void 0:e.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!s)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${a}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${a}//${s}/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((p,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let b=!1,h=T=>{b||(b=!0,clearTimeout(S),f(new Error(T)))},S=setTimeout(()=>h("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{b||(b=!0,clearTimeout(S),p())},{once:!0}),this.ws.addEventListener("error",()=>{h("WebSocket connection failed to "+u+"."+m)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!b){let M=T.code!==1006?` (code ${T.code})`:"";h("WebSocket connection failed"+M+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let t=JSON.parse(e.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var t,n;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(t=e.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(e.response.audio).catch(o=>this.errorCallbacks.forEach(a=>a(o instanceof Error?o:new Error(String(o)))))):(n=e.response.audio)!=null&&n.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(e.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new il(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var e,t,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let a=this.w;this.audioContext||(this.audioContext=new(a.AudioContext||a.webkitAudioContext));let s=this.audioContext,i=(t=(e=this.config)==null?void 0:e.pauseDuration)!=null?t:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(s,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(p=>p("processing")),this.processingStartCallbacks.forEach(p=>p());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:u});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(a){throw this.errorCallbacks.forEach(s=>s(a)),this.statusCallbacks.forEach(s=>s("error")),a}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var a,s;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(s=(a=this.config)==null?void 0:a.silenceThreshold)!=null?s:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(t=>t(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(e),o=this.getFormatFromMimeType(e.type),a=this.generateRequestId();this.currentRequestId=a,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:a}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result.split(",")[1];t(s)},o.onerror=n,o.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let t=atob(e.base64),n=new Uint8Array(t.length);for(let l=0;l<t.length;l++)n[l]=t.charCodeAt(l);let o=e.format||"mp3",a=o==="mp3"?"audio/mpeg":`audio/${o}`,s=new Blob([n],{type:a}),i=URL.createObjectURL(s),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var ma=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let a=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(a=>a(new Error(o.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ga(r){switch(r.type){case"runtype":if(!r.runtype)throw new Error("Runtype voice provider requires configuration");return new Vs(r.runtype);case"browser":if(!ma.isSupported())throw new Error("Browser speech recognition not supported");return new ma(r.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${r.type}`)}}function dl(r){if((r==null?void 0:r.type)==="runtype"&&r.runtype)return ga({type:"runtype",runtype:r.runtype});if(ma.isSupported())return ga({type:"browser",browser:(r==null?void 0:r.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function js(r){try{return dl(r),!0}catch{return!1}}var ov=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function av(r,e){return ov.some(t=>r[t]!==e[t])}function sx(r,e){let t=r instanceof Error?r:new Error(String(r));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let n="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${n}
|
|
63
60
|
|
|
64
|
-
_Details: ${r.message}_`:n}var 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
|
|
61
|
+
_Details: ${t.message}_`:n}var Gs=r=>({isError:!0,content:[{type:"text",text:r}]}),ix=(r,e="WebMCP tool execution failed.")=>r instanceof Error&&r.message?r.message:typeof r=="string"&&r?r:e,lx=r=>da(r)||r===Vn,ja=class r{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=e=>{var t,n,o,a,s,i,d,l,u,m;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall,f=!!(p!=null&&p.name)&&(da(p.name)||p.name===Vn&&((n=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:n.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(e.message),(a=e.message.agentMetadata)!=null&&a.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:(s=e.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i: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;((d=this.agentExecution)==null?void 0:d.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),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(m=(u=this.callbacks).onError)==null||m.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var n,o;this.messages=[...(n=e.initialMessages)!=null?n:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ua(e),this.wireDefaultWebMcpConfirm();for(let a of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(a.id,{...a,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return js((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,n;return(n=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?n:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var t,n,o;try{let a=e||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=ga(a);let s=(t=this.config.voiceRecognition)!=null?t:{},i=(n=s.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=s.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,m,p,f,b,h;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.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&&((p=l.text)!=null&&p.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=(h=this.pendingVoiceAssistantMessageId)!=null?h:(b=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:b.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 u,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(u=this.callbacks).onVoiceStatusChanged)==null||m.call(u,l)}),this.voiceProvider.connect()}catch(a){console.error("Failed to setup voice:",a)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,o,a,s,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=e.runtype)==null?void 0:n.agentId)||"",clientToken:((o=e.runtype)==null?void 0:o.clientToken)||"",host:(a=e.runtype)==null?void 0:a.host,voiceId:(s=e.runtype)==null?void 0:s.voiceId,pauseDuration:(i=e.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=e.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=e.browser)==null?void 0:l.language)||"en-US",continuous:(u=e.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(e=this.callbacks).onError)==null||t.call(e,n instanceof Error?n:new Error(String(n))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!av(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config=t,this.client=new ua(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:m}=e,f={id:s!=null?s:t==="user"?Va():t==="assistant"?fa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...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 t=[];for(let n of e){let{role:o,content:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:m=!1,voiceProcessing:p,rawContent:f}=n,h={id:d!=null?d:o==="user"?Va():o==="assistant"?fa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:m,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};t.push(h)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:o="",llmContent:a,id:s,createdAt:i,sequence:d}=e,l={text:o,component:t,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var l,u,m,p,f;let n=e.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Va(),a=fa(),s={id:o,role:"user",content:n||al,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(b){let h=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!h){let S=sx(b,this.config.errorMessage);if(S){let T={id:a,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(b instanceof Error?(m=(u=this.callbacks).onError)==null||m.call(u,b):(f=(p=this.callbacks).onError)==null||f.call(p,new Error(String(b))))}}async continueConversation(){var o,a,s,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=fa();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let m=sx(l,this.config.errorMessage);if(m){let p={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,t){var o,a,s;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,a,s;try{if(((a=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:a.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(s=e.description)!=null?s:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${t.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(n,i)})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(a=>a.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),n(t==="approved")}async resolveApproval(e,t,n){var u,m,p,f,b;let o=`approval-${e.id}`,a={...e,status:t,resolvedAt:Date.now()},s=this.messages.find(h=>h.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=s==null?void 0:s.createdAt)!=null?u:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let h;if(l?h=await l({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,n):h=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),h){let S=null;if(h instanceof Response){if(!h.ok){let T=await h.json().catch(()=>null);throw new Error((p=T==null?void 0:T.error)!=null?p:`Approval request failed: ${h.status}`)}S=h.body}else h instanceof ReadableStream&&(S=h);S?await this.connectStream(S,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(h){let S=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(f=this.callbacks).onError)==null||b.call(f,h instanceof Error?h:new Error(String(h)))}}persistAskUserQuestionProgress(e,t){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(o=>o.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var u,m,p,f,b,h,S,T,M,k,x,C;let n=this.messages.find(w=>w.id===e.id);if(((u=n==null?void 0:n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,a=(p=e.toolCall)==null?void 0:p.name;if(!o||!a){(b=(f=this.callbacks).onError)==null||b.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof t=="string"?void 0:t;if(s===void 0&&typeof t=="string"){let w=(h=e.toolCall)==null?void 0:h.args,E=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(E.length===1){let H=typeof((S=E[0])==null?void 0:S.question)=="string"?E[0].question:"";H&&(s={[H]:t})}}this.markAskUserQuestionResolved(e,s),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(M=e.toolCall)==null?void 0:M.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).map(([E,H])=>`${E}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=s!=null?s:{};l.forEach((E,H)=>{let I=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!I)return;let L=w[I],O=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(o,{[a]:t});if(!w.ok){let E=await w.json().catch(()=>null);throw new Error((k=E==null?void 0:E.error)!=null?k:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let E=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(C=(x=this.callbacks).onError)==null||C.call(x,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(e){var a,s;let t=(a=e.agentMetadata)==null?void 0:a.executionId,n=(s=e.toolCall)==null?void 0:s.id;if(!t||!n){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(n)&&(o.seen.add(n),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(e,n)}resolveWebMcpToolStartedAt(e){var o,a;let t=this.messages.find(s=>s.id===e.id),n=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(a=e.toolCall)==null?void 0:a.startedAt];for(let s of n)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(e){var n,o;if(((n=e.toolCall)==null?void 0:n.name)!==Vn)return!1;let t=this.messages.find(a=>a.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,n,o=Date.now(),a){this.messages.some(s=>s.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...a},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:n,completedAt:o,duration:void 0,durationMs:Math.max(0,o-n)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,l,u,m;let n=[],o=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(t.map(async p=>{var C,w,E,H,I,L,O;let f=(C=p.toolCall)==null?void 0:C.name,b=(w=p.toolCall)==null?void 0:w.id;if(!f||!b)return null;let h=`${e}:${b}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(h),n.push(h);let S=this.markWebMcpToolRunning(p),T=(H=(E=p.agentMetadata)==null?void 0:E.webMcpToolCallId)!=null?H:f;if(f===Vn)return{dedupeKey:h,resumeKey:T,output:Nd(),toolMessage:p,startedAt:S,completedAt:Date.now()};let M=new AbortController;this.webMcpResolveControllers.add(M),o.push(M);let k=this.client.executeWebMcpToolCall(f,(I=p.toolCall)==null?void 0:I.args,M.signal),x;if(!k)x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{x=await k}catch($){let te=$ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"));return te||(O=(L=this.callbacks).onError)==null||O.call(L,$ instanceof Error?$:new Error(String($))),this.markWebMcpToolComplete(p,Gs(te?"Aborted by cancel()":ix($)),S),this.webMcpInflightKeys.delete(h),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,Gs("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(h),null):{dedupeKey:h,resumeKey:T,output:x,toolMessage:p,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=s.filter(b=>b!==null),i.length===0)return;let p={};for(let b of i)p[b.resumeKey]=b.output;let f=await this.client.resumeFlow(e,p,{signal:a.signal});if(!f.ok){let b=await f.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${f.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((l=b.toolMessage.toolCall)==null?void 0:l.name)===Vn?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(m=(u=this.callbacks).onError)==null||m.call(u,p instanceof Error?p:new Error(String(p)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,Gs("Aborted by cancel()"),b.startedAt)}finally{for(let p of n)this.webMcpInflightKeys.delete(p);for(let p of o)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var b,h,S,T,M,k,x,C,w,E,H,I;let t=(b=e.agentMetadata)==null?void 0:b.executionId,n=(h=e.toolCall)==null?void 0:h.name,o=(S=e.toolCall)==null?void 0:S.id;if(!t){(M=(T=this.callbacks).onError)==null||M.call(T,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!n)return;if(!o){let L=`${t}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);try{await this.resumeWithToolOutput(t,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(L)}catch(O){(x=(k=this.callbacks).onError)==null||x.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(L)}return}let a=`${t}:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=n===Vn,u=(C=e.toolCall)==null?void 0:C.args,m=l?null:this.client.executeWebMcpToolCall(n,u,d),p="execute",f=s;try{let L;if(l?L=Nd():m?L=await m:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Gs("Aborted by cancel()"),s);return}let O=(E=(w=e.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?E:n;p="resume",await this.resumeWithToolOutput(t,O,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(e,L,s,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(L){let O=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(p==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(e,Gs(O||d.aborted?"Aborted by cancel()":ix(L)),s),O||(I=(H=this.callbacks).onError)==null||I.call(H,L instanceof Error?L:new Error(String(L)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,n,o){var s,i;let a=await this.client.resumeFlow(e,{[t]:n},{signal:o==null?void 0:o.signal});if(!a.ok){let d=await a.json().catch(()=>null);throw new Error((s=d==null?void 0:d.error)!=null?s:`Resume failed: ${a.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let a={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,a),this.selectedArtifactId=t,this.emitArtifactsState(),a}let n={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,n;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let n of e)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,e)}speak(e,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(e),a=n.getVoices();if(t.voice){let s=a.find(i=>i.name===t.voice);s&&(o.voice=s)}else a.length>0&&(o.voice=t.pickVoice?t.pickVoice(a):r.pickBestVoice(a));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let a=e.find(s=>s.name===o);if(a)return a}return(n=e.find(o=>o.lang.startsWith("en")))!=null?n:e[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),n=this.messages.findIndex(o=>o.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,a)=>{var u,m,p,f,b,h,S,T,M,k,x,C,w,E,H;if(a!==n)return o;let s={...o,...t};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=o.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&t.agentMetadata&&(s.agentMetadata={...(p=s.agentMetadata)!=null?p:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let I=o.approval,L=t.approval;s.approval={...I,...L,executionId:L.executionId||I.executionId,toolName:L.toolName||I.toolName,description:L.description||I.description,toolType:(f=L.toolType)!=null?f:I.toolType,reason:(b=L.reason)!=null?b:I.reason,parameters:(h=L.parameters)!=null?h:I.parameters}}let i=(S=t.toolCall)==null?void 0:S.name,d=(T=t.agentMetadata)==null?void 0:T.executionId,l=(M=t.toolCall)==null?void 0:M.id;if(i&&lx(i)&&d&&l&&((k=t.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let I=`${d}:${l}`,L=this.webMcpInflightKeys.has(I),O=this.webMcpResolvedKeys.has(I),$=(x=o.toolCall)==null?void 0:x.name,te=((C=o.agentMetadata)==null?void 0:C.executionId)===d&&((w=o.toolCall)==null?void 0:w.id)===l&&$!==void 0&&lx($)&&((E=o.toolCall)==null?void 0:E.status)==="complete";(L||O||te)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=o.toolCall,s.streaming=o.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,n)=>{var d,l;let o=new Date(t.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(a)&&o!==a)return o-a;let s=(d=t.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return s!==i?s-i:t.id.localeCompare(n.id)})}};var Vd=[["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 jd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Gd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Kd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Xd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Qd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Jd=[["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 Yd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Zd=[["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 ec=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var tc=[["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 rc=[["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 nc=[["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 oc=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var ac=[["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 sc=[["path",{d:"M20 6 9 17l-5-5"}]];var ic=[["path",{d:"m6 9 6 6 6-6"}]];var lc=[["path",{d:"m15 18-6-6 6-6"}]];var dc=[["path",{d:"m9 18 6-6-6-6"}]];var cc=[["path",{d:"m18 15-6-6-6 6"}]];var cl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var pl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var pc=[["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 uc=[["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 fc=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var mc=[["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 gc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var hc=[["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 xc=[["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 ul=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var fl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var bc=[["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 yc=[["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 vc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Cc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var wc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Ac=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Sc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Tc=[["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 Mc=[["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 kc=[["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 Ec=[["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 Lc=[["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 ml=[["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 Pc=[["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 Rc=[["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 Ic=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Hc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Wc=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Bc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var gl=[["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 Dc=[["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 Fc=[["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 Oc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Nc=[["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 _c=[["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 hl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Uc=[["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 qc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var zc=[["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 $c=[["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 Vc=[["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 jc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Gc=[["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 Kc=[["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 Xc=[["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 Qc=[["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 Jc=[["path",{d:"M5 12h14"}]];var Yc=[["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 Zc=[["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 ep=[["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 tp=[["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 rp=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var np=[["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 op=[["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 ap=[["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 sp=[["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 ip=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var lp=[["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 dp=[["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 cp=[["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 pp=[["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 up=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var fp=[["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 mp=[["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 gp=[["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 hp=[["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 xp=[["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 xl=[["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 bp=[["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 yp=[["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 vp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Cp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var bl=[["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 wp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Ap=[["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 Sp=[["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 Tp=[["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 Mp=[["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 kp=[["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 Ep=[["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 Lp=[["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 Pp=[["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 Rp=[["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 yl=[["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 Ip=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Hp=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Wp=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Bp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Dp=[["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 Fp=[["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 Op=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Np=[["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 sv={activity:Vd,"arrow-down":jd,"arrow-up":Qd,"arrow-up-right":Xd,bot:tc,"chevron-down":ic,"chevron-up":cc,"chevron-right":dc,"chevron-left":lc,check:sc,clipboard:uc,"clipboard-copy":pc,copy:mc,file:Sc,"file-code":Cc,"file-spreadsheet":wc,"file-text":Ac,"image-plus":Dc,loader:Uc,"loader-circle":hl,mic:Xc,paperclip:tp,"refresh-cw":dp,search:up,send:fp,"shield-alert":hp,"shield-check":xp,"shield-x":xl,square:wp,"thumbs-down":kp,"thumbs-up":Ep,upload:Hp,"volume-2":Bp,x:Op,user:Wp,mail:zc,phone:ap,calendar:oc,clock:fc,building:rc,"map-pin":$c,lock:qc,key:Nc,"credit-card":gc,"at-sign":Jd,hash:Ic,globe:Rc,link:_c,"circle-check":cl,"circle-x":pl,"triangle-alert":yl,info:Oc,ban:Yd,shield:bp,"arrow-left":Gd,"arrow-right":Kd,"external-link":bc,ellipsis:fl,"ellipsis-vertical":ul,menu:jc,house:gl,plus:ip,minus:Jc,pencil:np,trash:Rp,"trash-2":Pp,save:pp,download:xc,share:gp,funnel:ml,settings:mp,"rotate-cw":cp,maximize:Vc,minimize:Qc,"shopping-cart":vp,"shopping-bag":yp,package:ep,truck:Ip,tag:Mp,gift:Pc,receipt:lp,wallet:Fp,store:Sp,"dollar-sign":hc,percent:op,play:sp,pause:rp,"volume-x":Dp,camera:ac,image:Fc,film:Mc,headphones:Hc,"message-circle":Gc,"message-square":Kc,bell:Zd,heart:Wc,star:Ap,eye:vc,"eye-off":yc,bookmark:ec,"calendar-days":nc,history:Bc,timer:Lp,folder:Lc,"folder-open":Ec,files:Tc,sparkles:bl,zap:Np,sun:Tp,moon:Zc,flag:kc,monitor:Yc,smartphone:Cp},Me=(r,e=24,t="currentColor",n=2)=>{let o=sv[r];return o?iv(o,e,t,n):(console.warn(`Lucide icon "${r}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function iv(r,e,t,n){if(!Array.isArray(r))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),r.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var vl={allowedTypes:yo,maxFileSize:10*1024*1024,maxFiles:4};function lv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function dv(r){return r==="application/pdf"||r.startsWith("text/")||r.includes("word")?"file-text":r.includes("excel")||r.includes("spreadsheet")?"file-spreadsheet":r==="application/json"?"file-code":"file"}var ha=class r{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,n,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:vl.allowedTypes,maxFileSize:(n=e.maxFileSize)!=null?n:vl.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:vl.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:vl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,n,o,a,s,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,l,"count");continue}let u=ox(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let m=(o=u.error)!=null&&o.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,m);continue}try{let m=await nx(l),p=sl(l)?URL.createObjectURL(l):null,f={id:lv(),file:l,previewUrl:p,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 a,s,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let o=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var e,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=sl(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",t&&e.previewUrl){let s=v("img");s.src=e.previewUrl,s.alt=e.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",n.appendChild(s)}else{let s=v("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=dv(e.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=v("span");l.textContent=ax(e.file.type,e.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",s.appendChild(l),n.appendChild(s)}let o=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 a=Me("x",10,"var(--persona-text-inverse, #ffffff)",2);a?o.appendChild(a):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new r({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var dx=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function Ks(r,e){if(!r)return e;if(!e)return r;let t={...r};for(let[n,o]of Object.entries(e)){let a=t[n];dx(a)&&dx(o)?t[n]=Ks(a,o):t[n]=o}return t}var An="min(440px, calc(100vw - 24px))",Cl="440px",Kt={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:An,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 cx(r,e){if(!(!r&&!e))return r?e?Ks(r,e):r:e}function wl(r){var e,t,n,o,a,s,i,d,l,u,m,p,f,b,h,S,T,M,k,x,C;return r?{...Kt,...r,theme:cx(Kt.theme,r.theme),darkTheme:cx(Kt.darkTheme,r.darkTheme),launcher:{...Kt.launcher,...r.launcher,dock:{...(e=Kt.launcher)==null?void 0:e.dock,...(t=r.launcher)==null?void 0:t.dock},clearChat:{...(n=Kt.launcher)==null?void 0:n.clearChat,...(o=r.launcher)==null?void 0:o.clearChat}},copy:{...Kt.copy,...r.copy},sendButton:{...Kt.sendButton,...r.sendButton},statusIndicator:{...Kt.statusIndicator,...r.statusIndicator},voiceRecognition:{...Kt.voiceRecognition,...r.voiceRecognition},features:(()=>{var J,re,Q,ge,Z,G,pe,ke,le,ne;let w=(J=Kt.features)==null?void 0:J.artifacts,E=(re=r.features)==null?void 0:re.artifacts,H=(Q=Kt.features)==null?void 0:Q.scrollToBottom,I=(ge=r.features)==null?void 0:ge.scrollToBottom,L=(Z=Kt.features)==null?void 0:Z.scrollBehavior,O=(G=r.features)==null?void 0:G.scrollBehavior,$=(pe=Kt.features)==null?void 0:pe.streamAnimation,te=(ke=r.features)==null?void 0:ke.streamAnimation,xe=(le=Kt.features)==null?void 0:le.askUserQuestion,Je=(ne=r.features)==null?void 0:ne.askUserQuestion,we=w===void 0&&E===void 0?void 0:{...w,...E,layout:{...w==null?void 0:w.layout,...E==null?void 0:E.layout}},De=H===void 0&&I===void 0?void 0:{...H,...I},Ae=L===void 0&&O===void 0?void 0:{...L,...O},qe=$===void 0&&te===void 0?void 0:{...$,...te},He=xe===void 0&&Je===void 0?void 0:{...xe,...Je,styles:{...xe==null?void 0:xe.styles,...Je==null?void 0:Je.styles}};return{...Kt.features,...r.features,...De!==void 0?{scrollToBottom:De}:{},...Ae!==void 0?{scrollBehavior:Ae}:{},...we!==void 0?{artifacts:we}:{},...qe!==void 0?{streamAnimation:qe}:{},...He!==void 0?{askUserQuestion:He}:{}}})(),suggestionChips:(a=r.suggestionChips)!=null?a:Kt.suggestionChips,suggestionChipsConfig:{...Kt.suggestionChipsConfig,...r.suggestionChipsConfig},layout:{...Kt.layout,...r.layout,header:{...(s=Kt.layout)==null?void 0:s.header,...(i=r.layout)==null?void 0:i.header},messages:{...(d=Kt.layout)==null?void 0:d.messages,...(l=r.layout)==null?void 0:l.messages,avatar:{...(m=(u=Kt.layout)==null?void 0:u.messages)==null?void 0:m.avatar,...(f=(p=r.layout)==null?void 0:p.messages)==null?void 0:f.avatar},timestamp:{...(h=(b=Kt.layout)==null?void 0:b.messages)==null?void 0:h.timestamp,...(T=(S=r.layout)==null?void 0:S.messages)==null?void 0:T.timestamp}},slots:{...(M=Kt.layout)==null?void 0:M.slots,...(k=r.layout)==null?void 0:k.slots}},markdown:{...Kt.markdown,...r.markdown,options:{...(x=Kt.markdown)==null?void 0:x.options,...(C=r.markdown)==null?void 0:C.options}},messageActions:{...Kt.messageActions,...r.messageActions}}:Kt}var _p={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"}},Up={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"}},qp={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:An,maxWidth:Cl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ga(r,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),n=r;for(let o of t){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ga(r,n):n}function Al(r){let e={};function t(n,o){for(let[a,s]of Object.entries(n)){let i=`${o}.${a}`;if(typeof s=="string"){let d=Ga(r,s);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&t(s,i)}}return t(r.palette,"palette"),t(r.semantic,"semantic"),t(r.components,"components"),e}function zp(r){let e=[],t=[];return r.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),r.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),r.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function px(r,e){let t={...r};for(let[n,o]of Object.entries(e)){let a=t[n];a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?t[n]=px(a,o):t[n]=o}return t}function cv(r,e){return e?px(r,e):r}function Ka(r,e={}){var o,a,s,i,d,l,u,m,p,f,b,h,S;let t={palette:_p,semantic:Up,components:qp},n={palette:{...t.palette,...r==null?void 0:r.palette,colors:{...t.palette.colors,...(o=r==null?void 0:r.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(a=r==null?void 0:r.palette)==null?void 0:a.spacing},typography:{...t.palette.typography,...(s=r==null?void 0:r.palette)==null?void 0:s.typography},shadows:{...t.palette.shadows,...(i=r==null?void 0:r.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=r==null?void 0:r.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=r==null?void 0:r.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...r==null?void 0:r.semantic,colors:{...t.semantic.colors,...(u=r==null?void 0:r.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(p=(m=r==null?void 0:r.semantic)==null?void 0:m.colors)==null?void 0:p.interactive},feedback:{...t.semantic.colors.feedback,...(b=(f=r==null?void 0:r.semantic)==null?void 0:f.colors)==null?void 0:b.feedback}},spacing:{...t.semantic.spacing,...(h=r==null?void 0:r.semantic)==null?void 0:h.spacing},typography:{...t.semantic.typography,...(S=r==null?void 0:r.semantic)==null?void 0:S.typography}},components:cv(t.components,r==null?void 0:r.components)};if(e.validate!==!1){let T=zp(n);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(M=>M.message).join(", ")}`)}if(e.plugins)for(let T of e.plugins)n=T.transform(n);return n}function Sl(r){var h,S,T,M,k,x,C,w,E,H,I,L,O,$,te,xe,Je,we,De,Ae,qe,He,J,re,Q,ge,Z,G,pe,ke,le,ne,de,Et,wt,We,he,at,Re,j,ue,nt,Rt,ee,Ge,Fr,Bt,or,hr,sn,F,fe,Ie,Xe,Fe,Ne,Ye,At,Xt,ar,K,mt,it,ye,ie,st,pr,pt,yr,Rr,ut,Lt,tt,zt,vr,sr,ur,Mr,un,St,qr,xr,Mn,ln,yt,Gn,kn,_e,R,se,Ee,Ot,et,Nt,Yt,lr,vt,zr,$t,$r,Dn,oo,Ao,fn,Vt,Qr,En,So,ao,To,Kn,mn,Fn,Tt,Cr,wr,gn,Mo;let e=Al(r),t={};for(let[ve,On]of Object.entries(e)){let Ln=ve.replace(/\./g,"-");t[`--persona-${Ln}`]=On.value}t["--persona-primary"]=(h=t["--persona-semantic-colors-primary"])!=null?h:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(S=t["--persona-semantic-colors-secondary"])!=null?S:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(T=t["--persona-semantic-colors-accent"])!=null?T:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(M=t["--persona-semantic-colors-surface"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(x=t["--persona-semantic-colors-container"])!=null?x:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(C=t["--persona-semantic-colors-text"])!=null?C:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(E=t["--persona-semantic-colors-text-inverse"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(H=t["--persona-semantic-colors-border"])!=null?H:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(I=t["--persona-semantic-colors-divider"])!=null?I:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(L=t["--persona-components-voice-recording-indicator"])!=null?L:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(xe=t["--persona-components-approval-requested-background"])!=null?xe:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Je=t["--persona-components-approval-requested-border"])!=null?Je:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(we=t["--persona-components-approval-requested-text"])!=null?we:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(De=t["--persona-components-approval-requested-shadow"])!=null?De:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Ae=t["--persona-components-approval-approve-background"])!=null?Ae:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(qe=t["--persona-components-approval-deny-background"])!=null?qe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(He=t["--persona-components-attachment-image-background"])!=null?He:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(J=t["--persona-components-attachment-image-border"])!=null?J:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Q=t["--persona-semantic-typography-fontSize"])!=null?Q:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ge=t["--persona-semantic-typography-fontWeight"])!=null?ge:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Z=t["--persona-semantic-typography-lineHeight"])!=null?Z:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(G=t["--persona-palette-radius-sm"])!=null?G:"0.125rem",t["--persona-radius-md"]=(pe=t["--persona-palette-radius-md"])!=null?pe:"0.375rem",t["--persona-radius-lg"]=(ke=t["--persona-palette-radius-lg"])!=null?ke:"0.5rem",t["--persona-radius-xl"]=(le=t["--persona-palette-radius-xl"])!=null?le:"0.75rem",t["--persona-radius-full"]=(ne=t["--persona-palette-radius-full"])!=null?ne:"9999px",t["--persona-launcher-radius"]=(Et=(de=t["--persona-components-launcher-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?Et:"9999px",t["--persona-launcher-bg"]=(wt=t["--persona-components-launcher-background"])!=null?wt:t["--persona-primary"],t["--persona-launcher-fg"]=(We=t["--persona-components-launcher-foreground"])!=null?We:t["--persona-text-inverse"],t["--persona-launcher-border"]=(he=t["--persona-components-launcher-border"])!=null?he:t["--persona-border"],t["--persona-button-primary-bg"]=(at=t["--persona-components-button-primary-background"])!=null?at:t["--persona-primary"],t["--persona-button-primary-fg"]=(Re=t["--persona-components-button-primary-foreground"])!=null?Re:t["--persona-text-inverse"],t["--persona-button-radius"]=(ue=(j=t["--persona-components-button-primary-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?ue:"9999px",t["--persona-panel-radius"]=(Rt=(nt=t["--persona-components-panel-borderRadius"])!=null?nt:t["--persona-radius-xl"])!=null?Rt:"0.75rem",t["--persona-panel-border"]=(ee=t["--persona-components-panel-border"])!=null?ee:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Fr=(Ge=t["--persona-components-panel-shadow"])!=null?Ge:t["--persona-palette-shadows-xl"])!=null?Fr:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(Bt=t["--persona-components-launcher-shadow"])!=null?Bt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(hr=(or=t["--persona-components-input-borderRadius"])!=null?or:t["--persona-radius-lg"])!=null?hr:"0.5rem",t["--persona-message-user-radius"]=(F=(sn=t["--persona-components-message-user-borderRadius"])!=null?sn:t["--persona-radius-lg"])!=null?F:"0.5rem",t["--persona-message-assistant-radius"]=(Ie=(fe=t["--persona-components-message-assistant-borderRadius"])!=null?fe:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-header-bg"]=(Xe=t["--persona-components-header-background"])!=null?Xe:t["--persona-surface"],t["--persona-header-border"]=(Fe=t["--persona-components-header-border"])!=null?Fe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ne=t["--persona-components-header-iconBackground"])!=null?Ne:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ye=t["--persona-components-header-iconForeground"])!=null?Ye:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(At=t["--persona-components-header-titleForeground"])!=null?At:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Xt=t["--persona-components-header-subtitleForeground"])!=null?Xt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ar=t["--persona-components-header-actionIconForeground"])!=null?ar:t["--persona-muted"];let n=(K=r.components)==null?void 0:K.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom);let o=(mt=r.components)==null?void 0:mt.introCard;t["--persona-intro-card-bg"]=(it=t["--persona-components-introCard-background"])!=null?it:t["--persona-surface"],t["--persona-intro-card-radius"]=(ye=t["--persona-components-introCard-borderRadius"])!=null?ye:"1rem",t["--persona-intro-card-padding"]=(ie=t["--persona-components-introCard-padding"])!=null?ie:"1.5rem",t["--persona-intro-card-shadow"]=(pr=(st=o==null?void 0:o.shadow)!=null?st:t["--persona-components-introCard-shadow"])!=null?pr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(pt=t["--persona-components-input-background"])!=null?pt:t["--persona-surface"],t["--persona-input-placeholder"]=(yr=t["--persona-components-input-placeholder"])!=null?yr:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Rr=t["--persona-components-message-user-background"])!=null?Rr:t["--persona-accent"],t["--persona-message-user-text"]=(ut=t["--persona-components-message-user-text"])!=null?ut:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Lt=t["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(tt=t["--persona-components-message-assistant-background"])!=null?tt:t["--persona-surface"],t["--persona-message-assistant-text"]=(zt=t["--persona-components-message-assistant-text"])!=null?zt:t["--persona-text"],t["--persona-message-assistant-border"]=(vr=t["--persona-components-message-assistant-border"])!=null?vr:t["--persona-border"],t["--persona-message-assistant-shadow"]=(sr=t["--persona-components-message-assistant-shadow"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Mr=(ur=t["--persona-components-scrollToBottom-background"])!=null?ur:t["--persona-button-primary-bg"])!=null?Mr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(St=(un=t["--persona-components-scrollToBottom-foreground"])!=null?un:t["--persona-button-primary-fg"])!=null?St:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(qr=t["--persona-components-scrollToBottom-border"])!=null?qr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(xr=t["--persona-components-scrollToBottom-size"])!=null?xr:"40px",t["--persona-scroll-to-bottom-radius"]=(yt=(ln=(Mn=t["--persona-components-scrollToBottom-borderRadius"])!=null?Mn:t["--persona-button-radius"])!=null?ln:t["--persona-radius-full"])!=null?yt:"9999px",t["--persona-scroll-to-bottom-shadow"]=(kn=(Gn=t["--persona-components-scrollToBottom-shadow"])!=null?Gn:t["--persona-palette-shadows-sm"])!=null?kn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(_e=t["--persona-components-scrollToBottom-padding"])!=null?_e:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(R=t["--persona-components-scrollToBottom-gap"])!=null?R:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Ee=(se=t["--persona-components-scrollToBottom-fontSize"])!=null?se:t["--persona-palette-typography-fontSize-sm"])!=null?Ee:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Ot=t["--persona-components-scrollToBottom-iconSize"])!=null?Ot:"14px",t["--persona-tool-bubble-shadow"]=(et=t["--persona-components-toolBubble-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Nt=t["--persona-components-reasoningBubble-shadow"])!=null?Nt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Yt=t["--persona-components-composer-shadow"])!=null?Yt:"none",t["--persona-md-inline-code-bg"]=(lr=t["--persona-components-markdown-inlineCode-background"])!=null?lr:t["--persona-container"],t["--persona-md-inline-code-color"]=(vt=t["--persona-components-markdown-inlineCode-foreground"])!=null?vt:t["--persona-text"],t["--persona-md-link-color"]=($t=(zr=t["--persona-components-markdown-link-foreground"])!=null?zr:t["--persona-accent"])!=null?$t:"#0f0f0f";let a=t["--persona-components-markdown-heading-h1-fontSize"];a&&(t["--persona-md-h1-size"]=a);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=($r=t["--persona-components-markdown-codeBlock-background"])!=null?$r:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Dn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Dn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(oo=t["--persona-components-markdown-codeBlock-textColor"])!=null?oo:"inherit",t["--persona-md-table-header-bg"]=(Ao=t["--persona-components-markdown-table-headerBackground"])!=null?Ao:t["--persona-container"],t["--persona-md-table-border-color"]=(fn=t["--persona-components-markdown-table-borderColor"])!=null?fn:t["--persona-border"],t["--persona-md-hr-color"]=(Vt=t["--persona-components-markdown-hr-color"])!=null?Vt:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Qr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Qr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(En=t["--persona-components-markdown-blockquote-background"])!=null?En:"transparent",t["--persona-md-blockquote-text-color"]=(So=t["--persona-components-markdown-blockquote-textColor"])!=null?So:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(ao=t["--persona-components-collapsibleWidget-container"])!=null?ao:t["--persona-surface"],t["--cw-surface"]=(To=t["--persona-components-collapsibleWidget-surface"])!=null?To:t["--persona-surface"],t["--cw-border"]=(Kn=t["--persona-components-collapsibleWidget-border"])!=null?Kn:t["--persona-border"],t["--persona-message-border"]=(mn=t["--persona-components-message-border"])!=null?mn:t["--persona-border"];let u=r.components,m=u==null?void 0:u.iconButton;m&&(m.background&&(t["--persona-icon-btn-bg"]=m.background),m.border&&(t["--persona-icon-btn-border"]=m.border),m.color&&(t["--persona-icon-btn-color"]=m.color),m.padding&&(t["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(t["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(t["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(t["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(t["--persona-icon-btn-active-border"]=m.activeBorder));let p=u==null?void 0:u.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let f=u==null?void 0:u.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let b=u==null?void 0:u.artifact;if(b!=null&&b.toolbar){let ve=b.toolbar;ve.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ve.iconHoverColor),ve.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ve.iconHoverBackground),ve.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ve.iconPadding),ve.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ve.iconBorderRadius),ve.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ve.iconBorder),ve.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ve.toggleGroupGap),ve.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ve.toggleBorderRadius),ve.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ve.copyBackground),ve.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ve.copyBorder),ve.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ve.copyColor),ve.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ve.copyBorderRadius),ve.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ve.copyPadding),ve.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ve.copyMenuBackground,t["--persona-dropdown-bg"]=(Fn=t["--persona-dropdown-bg"])!=null?Fn:ve.copyMenuBackground),ve.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ve.copyMenuBorder,t["--persona-dropdown-border"]=(Tt=t["--persona-dropdown-border"])!=null?Tt:ve.copyMenuBorder),ve.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ve.copyMenuShadow,t["--persona-dropdown-shadow"]=(Cr=t["--persona-dropdown-shadow"])!=null?Cr:ve.copyMenuShadow),ve.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ve.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(wr=t["--persona-dropdown-radius"])!=null?wr:ve.copyMenuBorderRadius),ve.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ve.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ve.copyMenuItemHoverBackground),ve.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ve.iconBackground),ve.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ve.toolbarBorder)}if(b!=null&&b.tab){let ve=b.tab;ve.background&&(t["--persona-artifact-tab-bg"]=ve.background),ve.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ve.activeBackground),ve.activeBorder&&(t["--persona-artifact-tab-active-border"]=ve.activeBorder),ve.borderRadius&&(t["--persona-artifact-tab-radius"]=ve.borderRadius),ve.textColor&&(t["--persona-artifact-tab-color"]=ve.textColor),ve.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ve.hoverBackground),ve.listBackground&&(t["--persona-artifact-tab-list-bg"]=ve.listBackground),ve.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ve.listBorderColor),ve.listPadding&&(t["--persona-artifact-tab-list-padding"]=ve.listPadding)}if(b!=null&&b.pane){let ve=b.pane;if(ve.toolbarBackground){let On=(Mo=Ga(r,ve.toolbarBackground))!=null?Mo:ve.toolbarBackground;t["--persona-artifact-toolbar-bg"]=On}}return t}var ux={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 pv={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"}}},fx=r=>{if(!(!r||typeof r!="object"||Array.isArray(r)))return r},Xs=()=>{var r;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},uv=r=>{var t;let e=(t=r==null?void 0:r.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Xs()},$p=r=>uv(r),fv=r=>Ka(r),mv=r=>{var t;let e=Ka(void 0,{validate:!1});return Ka({...r,palette:{...e.palette,colors:{...pv.colors,...(t=r==null?void 0:r.palette)==null?void 0:t.colors}}},{validate:!1})},Xa=r=>{let e=$p(r),t=fx(r==null?void 0:r.theme),n=fx(r==null?void 0:r.darkTheme);return e==="dark"?mv(Ks(t!=null?t:{},n!=null?n:{})):fv(t)},gv=r=>Sl(r),_o=(r,e)=>{let t=Xa(e),n=gv(t);for(let[o,a]of Object.entries(n))r.style.setProperty(o,a)},Tl=r=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{r(Xs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>r(Xs());t.addEventListener?(t.addEventListener("change",n),e.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),e.push(()=>t.removeListener(n)))}return()=>{e.forEach(t=>t())}};var mx=(function(){"use strict";let r=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:r,afterNodeAdded:r,beforeNodeMorphed:r,afterNodeMorphed:r,beforeNodeRemoved:r,afterNodeRemoved:r,beforeAttributeUpdated:r},head:{style:"merge",shouldPreserve:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:r,afterHeadMorphed:r},restoreFocus:!0};function t(p,f,b={}){p=u(p);let h=m(f),S=l(p,h,b),T=o(S,()=>i(S,p,h,M=>M.morphStyle==="innerHTML"?(a(M,p,h),Array.from(p.childNodes)):n(M,p,h)));return S.pantry.remove(),T}function n(p,f,b){let h=m(f);return a(p,h,b,f,f.nextSibling),Array.from(h.childNodes)}function o(p,f){var k;if(!p.config.restoreFocus)return f();let b=document.activeElement;if(!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement))return f();let{id:h,selectionStart:S,selectionEnd:T}=b,M=f();return h&&h!==((k=document.activeElement)==null?void 0:k.getAttribute("id"))&&(b=p.target.querySelector(`[id="${h}"]`),b==null||b.focus()),b&&!b.selectionEnd&&T&&b.setSelectionRange(S,T),M}let a=(function(){function p(x,C,w,E=null,H=null){C instanceof HTMLTemplateElement&&w instanceof HTMLTemplateElement&&(C=C.content,w=w.content),E||(E=C.firstChild);for(let I of w.childNodes){if(E&&E!=H){let O=b(x,I,E,H);if(O){O!==E&&S(x,E,O),s(O,I,x),E=O.nextSibling;continue}}if(I instanceof Element){let O=I.getAttribute("id");if(x.persistentIds.has(O)){let $=T(C,O,E,x);s($,I,x),E=$.nextSibling;continue}}let L=f(C,I,E,x);L&&(E=L.nextSibling)}for(;E&&E!=H;){let I=E;E=E.nextSibling,h(x,I)}}function f(x,C,w,E){if(E.callbacks.beforeNodeAdded(C)===!1)return null;if(E.idMap.has(C)){let H=document.createElement(C.tagName);return x.insertBefore(H,w),s(H,C,E),E.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(C,!0);return x.insertBefore(H,w),E.callbacks.afterNodeAdded(H),H}}let b=(function(){function x(E,H,I,L){let O=null,$=H.nextSibling,te=0,xe=I;for(;xe&&xe!=L;){if(w(xe,H)){if(C(E,xe,H))return xe;O===null&&(E.idMap.has(xe)||(O=xe))}if(O===null&&$&&w(xe,$)&&(te++,$=$.nextSibling,te>=2&&(O=void 0)),E.activeElementAndParents.includes(xe))break;xe=xe.nextSibling}return O||null}function C(E,H,I){let L=E.idMap.get(H),O=E.idMap.get(I);if(!O||!L)return!1;for(let $ of L)if(O.has($))return!0;return!1}function w(E,H){var O,$,te;let I=E,L=H;return I.nodeType===L.nodeType&&I.tagName===L.tagName&&(!((O=I.getAttribute)!=null&&O.call(I,"id"))||(($=I.getAttribute)==null?void 0:$.call(I,"id"))===((te=L.getAttribute)==null?void 0:te.call(L,"id")))}return x})();function h(x,C){var w;if(x.idMap.has(C))k(x.pantry,C,null);else{if(x.callbacks.beforeNodeRemoved(C)===!1)return;(w=C.parentNode)==null||w.removeChild(C),x.callbacks.afterNodeRemoved(C)}}function S(x,C,w){let E=C;for(;E&&E!==w;){let H=E;E=E.nextSibling,h(x,H)}return E}function T(x,C,w,E){var I,L;let H=((L=(I=E.target).getAttribute)==null?void 0:L.call(I,"id"))===C&&E.target||E.target.querySelector(`[id="${C}"]`)||E.pantry.querySelector(`[id="${C}"]`);return M(H,E),k(x,H,w),H}function M(x,C){let w=x.getAttribute("id");for(;x=x.parentNode;){let E=C.idMap.get(x);E&&(E.delete(w),E.size||C.idMap.delete(x))}}function k(x,C,w){if(x.moveBefore)try{x.moveBefore(C,w)}catch{x.insertBefore(C,w)}else x.insertBefore(C,w)}return p})(),s=(function(){function p(M,k,x){return x.ignoreActive&&M===document.activeElement?null:(x.callbacks.beforeNodeMorphed(M,k)===!1||(M instanceof HTMLHeadElement&&x.head.ignore||(M instanceof HTMLHeadElement&&x.head.style!=="morph"?d(M,k,x):(f(M,k,x),T(M,x)||a(x,M,k))),x.callbacks.afterNodeMorphed(M,k)),M)}function f(M,k,x){let C=k.nodeType;if(C===1){let w=M,E=k,H=w.attributes,I=E.attributes;for(let L of I)S(L.name,w,"update",x)||w.getAttribute(L.name)!==L.value&&w.setAttribute(L.name,L.value);for(let L=H.length-1;0<=L;L--){let O=H[L];if(O&&!E.hasAttribute(O.name)){if(S(O.name,w,"remove",x))continue;w.removeAttribute(O.name)}}T(w,x)||b(w,E,x)}(C===8||C===3)&&M.nodeValue!==k.nodeValue&&(M.nodeValue=k.nodeValue)}function b(M,k,x){if(M instanceof HTMLInputElement&&k instanceof HTMLInputElement&&k.type!=="file"){let C=k.value,w=M.value;h(M,k,"checked",x),h(M,k,"disabled",x),k.hasAttribute("value")?w!==C&&(S("value",M,"update",x)||(M.setAttribute("value",C),M.value=C)):S("value",M,"remove",x)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&k instanceof HTMLOptionElement)h(M,k,"selected",x);else if(M instanceof HTMLTextAreaElement&&k instanceof HTMLTextAreaElement){let C=k.value,w=M.value;if(S("value",M,"update",x))return;C!==w&&(M.value=C),M.firstChild&&M.firstChild.nodeValue!==C&&(M.firstChild.nodeValue=C)}}function h(M,k,x,C){let w=k[x],E=M[x];if(w!==E){let H=S(x,M,"update",C);H||(M[x]=k[x]),w?H||M.setAttribute(x,""):S(x,M,"remove",C)||M.removeAttribute(x)}}function S(M,k,x,C){return M==="value"&&C.ignoreActiveValue&&k===document.activeElement?!0:C.callbacks.beforeAttributeUpdated(M,k,x)===!1}function T(M,k){return!!k.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return p})();function i(p,f,b,h){if(p.head.block){let S=f.querySelector("head"),T=b.querySelector("head");if(S&&T){let M=d(S,T,p);return Promise.all(M).then(()=>{let k=Object.assign(p,{head:{block:!1,ignore:!0}});return h(k)})}}return h(p)}function d(p,f,b){let h=[],S=[],T=[],M=[],k=new Map;for(let C of f.children)k.set(C.outerHTML,C);for(let C of p.children){let w=k.has(C.outerHTML),E=b.head.shouldReAppend(C),H=b.head.shouldPreserve(C);w||H?E?S.push(C):(k.delete(C.outerHTML),T.push(C)):b.head.style==="append"?E&&(S.push(C),M.push(C)):b.head.shouldRemove(C)!==!1&&S.push(C)}M.push(...k.values());let x=[];for(let C of M){let w=document.createRange().createContextualFragment(C.outerHTML).firstChild;if(b.callbacks.beforeNodeAdded(w)!==!1){if("href"in w&&w.href||"src"in w&&w.src){let E,H=new Promise(function(I){E=I});w.addEventListener("load",function(){E()}),x.push(H)}p.appendChild(w),b.callbacks.afterNodeAdded(w),h.push(w)}}for(let C of S)b.callbacks.beforeNodeRemoved(C)!==!1&&(p.removeChild(C),b.callbacks.afterNodeRemoved(C));return b.head.afterHeadMorphed(p,{added:h,kept:T,removed:S}),x}let l=(function(){function p(x,C,w){let{persistentIds:E,idMap:H}=M(x,C),I=f(w),L=I.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(L))throw`Do not understand how to morph style ${L}`;return{target:x,newContent:C,config:I,morphStyle:L,ignoreActive:I.ignoreActive,ignoreActiveValue:I.ignoreActiveValue,restoreFocus:I.restoreFocus,idMap:H,persistentIds:E,pantry:b(),activeElementAndParents:h(x),callbacks:I.callbacks,head:I.head}}function f(x){let C=Object.assign({},e);return Object.assign(C,x),C.callbacks=Object.assign({},e.callbacks,x.callbacks),C.head=Object.assign({},e.head,x.head),C}function b(){let x=document.createElement("div");return x.hidden=!0,document.body.insertAdjacentElement("afterend",x),x}function h(x){let C=[],w=document.activeElement;if((w==null?void 0:w.tagName)!=="BODY"&&x.contains(w))for(;w&&(C.push(w),w!==x);)w=w.parentElement;return C}function S(x){var w;let C=Array.from(x.querySelectorAll("[id]"));return(w=x.getAttribute)!=null&&w.call(x,"id")&&C.push(x),C}function T(x,C,w,E){for(let H of E){let I=H.getAttribute("id");if(C.has(I)){let L=H;for(;L;){let O=x.get(L);if(O==null&&(O=new Set,x.set(L,O)),O.add(I),L===w)break;L=L.parentElement}}}}function M(x,C){let w=S(x),E=S(C),H=k(w,E),I=new Map;T(I,H,x,w);let L=C.__idiomorphRoot||C;return T(I,H,L,E),{persistentIds:H,idMap:I}}function k(x,C){let w=new Set,E=new Map;for(let{id:I,tagName:L}of x)E.has(I)?w.add(I):E.set(I,L);let H=new Set;for(let{id:I,tagName:L}of C)H.has(I)?w.add(I):E.get(I)===L&&H.add(I);for(let I of w)H.delete(I);return H}return p})(),{normalizeElement:u,normalizeParent:m}=(function(){let p=new WeakSet;function f(T){return T instanceof Document?T.documentElement:T}function b(T){if(T==null)return document.createElement("div");if(typeof T=="string")return b(S(T));if(p.has(T))return T;if(T instanceof Node){if(T.parentNode)return new h(T);{let M=document.createElement("div");return M.append(T),M}}else{let M=document.createElement("div");for(let k of[...T])M.append(k);return M}}class h{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],k=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;k&&k!=this.nextSibling;)M.push(k),k=k.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((k,x)=>{if(x instanceof Element){x.matches(M)&&k.push(x);let C=x.querySelectorAll(M);for(let w=0;w<C.length;w++)k.push(C[w])}return k},[])}insertBefore(M,k){return this.realParentNode.insertBefore(M,k)}moveBefore(M,k){return this.realParentNode.moveBefore(M,k)}get __idiomorphRoot(){return this.originalNode}}function S(T){let M=new DOMParser,k=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(k.match(/<\/html>/)||k.match(/<\/head>/)||k.match(/<\/body>/)){let x=M.parseFromString(T,"text/html");if(k.match(/<\/html>/))return p.add(x),x;{let C=x.firstChild;return C&&p.add(C),C}}else{let C=M.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return p.add(C),C}}return{normalizeElement:f,normalizeParent:b}})();return{morph:t,defaults:e}})();var Ml=(r,e,t={})=>{let{preserveTypingAnimation:n=!0}=t;mx.morph(r,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,a){var s,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let d=(s=o.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var kl={index:-1,draft:""};function gx(r){let{direction:e,history:t,currentValue:n,atStart:o,state:a}=r,s=a.index!==-1;if(t.length===0)return{handled:!1,state:a};if(e==="up"){if(!s&&!o)return{handled:!1,state:a};if(!s){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:n}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:t[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<t.length-1){let i=a.index+1;return{handled:!0,value:t[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...kl}}}function hx(r,e){var t,n,o,a,s,i,d,l,u,m,p,f,b,h,S,T,M,k,x,C,w,E,H,I,L,O,$,te,xe,Je,we,De,Ae,qe,He,J,re,Q;return[r.id,r.role,(n=(t=r.content)==null?void 0:t.length)!=null?n:0,(a=(o=r.content)==null?void 0:o.slice(-32))!=null?a:"",r.streaming?"1":"0",(s=r.variant)!=null?s:"",(d=(i=r.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=r.llmContent)==null?void 0:l.length)!=null?u:0,(p=(m=r.approval)==null?void 0:m.status)!=null?p:"",(b=(f=r.toolCall)==null?void 0:f.status)!=null?b:"",(S=(h=r.toolCall)==null?void 0:h.name)!=null?S:"",(k=(M=(T=r.toolCall)==null?void 0:T.chunks)==null?void 0:M.length)!=null?k:0,(E=(w=(C=(x=r.toolCall)==null?void 0:x.chunks)==null?void 0:C[r.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?E:"",typeof((H=r.toolCall)==null?void 0:H.args)=="string"?r.toolCall.args.length:(I=r.toolCall)!=null&&I.args?JSON.stringify(r.toolCall.args).length:0,($=(O=(L=r.reasoning)==null?void 0:L.chunks)==null?void 0:O.length)!=null?$:0,(we=(Je=(xe=(te=r.reasoning)==null?void 0:te.chunks)==null?void 0:xe[r.reasoning.chunks.length-1])==null?void 0:Je.length)!=null?we:0,(He=(qe=(Ae=(De=r.reasoning)==null?void 0:De.chunks)==null?void 0:Ae[r.reasoning.chunks.length-1])==null?void 0:qe.slice(-32))!=null?He:"",(re=(J=r.contentParts)==null?void 0:J.length)!=null?re:0,(Q=r.stopReason)!=null?Q:"",e].join("\0")}function xx(){return new Map}function bx(r,e,t){let n=r.get(e);return n&&n.fingerprint===t?n.wrapper:null}function yx(r,e,t,n){r.set(e,{fingerprint:t,wrapper:n})}function vx(r,e){for(let t of r.keys())e.has(t)||r.delete(t)}function El(r=!0){let e=r;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function vo(r){return Math.max(0,r.scrollHeight-r.clientHeight)}function xa(r,e){return vo(r)-r.scrollTop<=e}function Ll(r){let{following:e,currentScrollTop:t,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=r,u=t-n;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:t}:!e&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Pl(r){let{following:e,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=r;return e&&t<0?"pause":!e&&o&&t>0&&n?"resume":"none"}function Cx(r,e){return!r||r.isCollapsed?!1:e.contains(r.anchorNode)||e.contains(r.focusNode)}function wx(r){let e=Math.max(0,r.anchorOffsetTop-r.topOffset),t=Math.max(0,e+r.viewportHeight-r.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Ax(r){let e=Math.max(0,r.currentContentHeight-r.contentHeightAtAnchor);return Math.max(0,r.initialSpacerHeight-e)}var Kr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Xr=1e5,Uo=Xr+1;var Qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},hv=["pre","code","a","script","style"],Rl=r=>{var e,t,n,o,a;return{type:(e=r==null?void 0:r.type)!=null?e:Qs.type,placeholder:(t=r==null?void 0:r.placeholder)!=null?t:Qs.placeholder,speed:(n=r==null?void 0:r.speed)!=null?n:Qs.speed,duration:(o=r==null?void 0:r.duration)!=null?o:Qs.duration,buffer:(a=r==null?void 0:r.buffer)!=null?a:Qs.buffer}},Tx=[{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"}],Js=new Map;for(let r of Tx)Js.set(r.name,r);var ba=r=>{Js.set(r.name,r)},Gp=r=>{Tx.some(e=>e.name===r)||Js.delete(r)},Kp=()=>Array.from(Js.keys()),Ys=(r,e)=>{var t,n;return r==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,r)?(t=e[r])!=null?t:null:(n=Js.get(r))!=null?n:null},Il=(r,e,t,n,o)=>{if(!o)return r;if(t!=null&&t.bufferContent)return t.bufferContent(r,n);if(!r)return r;if(e==="word"){let a=r.search(/\s(?=\S*$)/);return a<0?"":r.slice(0,a)}if(e==="line"){let a=r.lastIndexOf(`
|
|
62
|
+
`);return a<0?"":r.slice(0,a)}return r},xv=(r,e,t,n)=>{let o=r.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=e,o},bv=(r,e,t,n)=>{let o=r.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=e,o},Vp=/\s/,yv=(r,e)=>{let t=r.parentNode;for(;t;){if(t.nodeType===1){let n=t;if(e.has(n.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},vv=(r,e,t)=>{var d;let n=r.ownerDocument,o=r.parentNode;if(!n||!o)return;let a=(d=r.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(Vp.test(a[i])){let l=i;for(;l<a.length&&Vp.test(a[l]);)l+=1;s.appendChild(n.createTextNode(a.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<a.length&&!Vp.test(a[u]);)l.appendChild(xv(n,a[u],e,t.value)),t.value+=1,u+=1;s.appendChild(l),i=u}o.replaceChild(s,r)},Cv=(r,e,t)=>{var d;let n=r.ownerDocument,o=r.parentNode;if(!n||!o)return;let a=(d=r.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(n.createTextNode(l)):(s.appendChild(bv(n,l,e,t.value)),t.value+=1));o.replaceChild(s,r)},Zs=(r,e,t,n)=>{var m,p;if(!r||typeof document=="undefined")return r;let o=document.createElement("div");o.innerHTML=r;let a=new Set(((m=n==null?void 0:n.skipTags)!=null?m:hv).map(f=>f.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=s.nextNode();for(;d;)yv(d,a)||i.push(d),d=s.nextNode();let l={value:(p=n==null?void 0:n.startIndex)!=null?p:0},u=e==="char"?vv:Cv;for(let f of i)u(f,t,l);return o.innerHTML},Hl=(r=document)=>{let e=r.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ei=(r=document)=>{let e=r.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=r.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Sx=new WeakMap,wv=(r,e)=>{var a;if(!r.styles)return;let t=Sx.get(e);if(t||(t=new Set,Sx.set(e,t)),t.has(r.name)){let s=r.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;t.delete(r.name)}t.add(r.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(a=e.ownerDocument)!=null?a:document).createElement("style");o.setAttribute("data-persona-animation",r.name),o.textContent=r.styles,e.appendChild(o)},jp=new WeakMap,Av=(r,e)=>{if(!r.onAttach)return;let t=jp.get(e);if(t||(t=new Map,jp.set(e,t)),t.has(r.name))return;let n=r.onAttach(e);t.set(r.name,n)},Mx=r=>{let e=jp.get(r);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Xp=(r,e)=>{wv(r,e),Av(r,e)};function Qp(r,e=Xr){let t=r.style.position,n=r.style.zIndex,o=r.style.isolation,a=getComputedStyle(r),s=a.position==="static"||a.position==="";return s&&(r.style.position="relative"),r.style.zIndex=String(e),r.style.isolation="isolate",()=>{s&&(r.style.position=t),r.style.zIndex=n,r.style.isolation=o}}var ti=0,qo=null;function Jp(r=document){var t;if(ti++,ti===1){let n=r.body,a=((t=r.defaultView)!=null?t:window).scrollY||r.documentElement.scrollTop;qo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:a},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${a}px`,n.style.width="100%"}let e=!1;return()=>{var n;if(!e&&(e=!0,ti=Math.max(0,ti-1),ti===0&&qo)){let o=r.body,a=(n=r.defaultView)!=null?n:window;o.style.overflow=qo.originalOverflow,o.style.position=qo.originalPosition,o.style.top=qo.originalTop,o.style.width=qo.originalWidth,a.scrollTo(0,qo.scrollY),qo=null}}}var ri={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Pr=r=>{var e,t;return((t=(e=r==null?void 0:r.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},zo=r=>{var e,t;return((t=(e=r==null?void 0:r.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},Sn=r=>{var t,n,o,a,s,i;let e=(t=r==null?void 0:r.launcher)==null?void 0:t.dock;return{side:(n=e==null?void 0:e.side)!=null?n:ri.side,width:(o=e==null?void 0:e.width)!=null?o:ri.width,animate:(a=e==null?void 0:e.animate)!=null?a:ri.animate,reveal:(s=e==null?void 0:e.reveal)!=null?s:ri.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:ri.maxHeight}};var jn={"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 ni=(r,e)=>{let t=v("button");t.type="button",t.innerHTML=`
|
|
66
63
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
67
64
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
68
65
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -70,14 +67,14 @@ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
70
67
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
71
68
|
</span>
|
|
72
69
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
73
|
-
`,r.addEventListener("click",e);let n=s=>{var 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
|
-
`):""},
|
|
75
|
-
`);let o
|
|
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=`
|
|
70
|
+
`,t.addEventListener("click",e);let n=a=>{var k,x,C,w,E,H,I,L,O,$,te,xe,Je;let s=(k=a.launcher)!=null?k:{},i=Pr(a),d=t.querySelector("[data-role='launcher-title']");if(d){let we=(x=s.title)!=null?x:"Chat Assistant";d.textContent=we,d.setAttribute("title",we)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let we=(C=s.subtitle)!=null?C:"Get answers fast";l.textContent=we,l.setAttribute("title",we)}let u=t.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let m=t.querySelector("[data-role='launcher-icon']");if(m)if(s.agentIconHidden)m.style.display="none";else{let we=(w=s.agentIconSize)!=null?w:"40px";if(m.style.height=we,m.style.width=we,m.innerHTML="",s.agentIconName){let De=parseFloat(we)||24,Ae=Me(s.agentIconName,De*.6,"var(--persona-text-inverse, #ffffff)",2);Ae?(m.appendChild(Ae),m.style.display=""):(m.textContent=(E=s.agentIconText)!=null?E:"\u{1F4AC}",m.style.display="")}else s.iconUrl?m.style.display="none":(m.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",m.style.display="")}let p=t.querySelector("[data-role='launcher-image']");if(p){let we=(I=s.agentIconSize)!=null?I:"40px";p.style.height=we,p.style.width=we,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let f=t.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let we=(L=s.callToActionIconSize)!=null?L:"32px";f.style.height=we,f.style.width=we,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let De=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,De=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",s.callToActionIconName){let Ae=parseFloat(we)||24,qe=Math.max(Ae-De,8),He=Me(s.callToActionIconName,qe,"currentColor",2);He?f.appendChild(He):f.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}else f.textContent=($=s.callToActionIconText)!=null?$:"\u2197"}let b=s.position&&jn[s.position]?jn[s.position]:jn["bottom-right"],h="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?S:`${h} ${b}`,i||(t.style.zIndex=String((te=s.zIndex)!=null?te:Xr));let T="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(xe=s.border)!=null?xe:T,t.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Je=s.collapsedMaxWidth)!=null?Je:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return r&&n(r),{element:t,update:n,destroy:o}};var Sv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Wl=(r,e={})=>{var h,S,T,M,k,x;let{showClose:t=!0,wrapperClassName:n=Sv,buttonSize:o,iconSize:a="28px"}=e,s=(h=r==null?void 0:r.launcher)!=null?h:{},i=(S=o!=null?o:s.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 u=(T=s.closeButtonTooltipText)!=null?T:"Close chat",m=(M=s.closeButtonShowTooltip)!=null?M:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let p=(k=s.closeButtonIconName)!=null?k:"x",f=(x=s.closeButtonIconText)!=null?x:"\xD7";l.style.color=s.closeButtonColor||an.actionIconColor;let b=Me(p,a,"currentColor",1);if(b?(b.style.display="block",l.appendChild(b)):l.textContent=f,s.closeButtonBackgroundColor?(l.style.backgroundColor=s.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let C=s.closeButtonBorderWidth||"0px",w=s.closeButtonBorderColor||"transparent";l.style.border=`${C} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(l.style.borderRadius=s.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(l.style.paddingLeft=s.closeButtonPaddingX,l.style.paddingRight=s.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),s.closeButtonPaddingY?(l.style.paddingTop=s.closeButtonPaddingY,l.style.paddingBottom=s.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&u){let C=null,w=()=>{if(C)return;let H=l.ownerDocument,I=H.body;if(!I)return;C=ro(H,"div","persona-clear-chat-tooltip"),C.textContent=u;let L=ro(H,"div");L.className="persona-clear-chat-tooltip-arrow",C.appendChild(L);let O=l.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Uo),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",I.appendChild(C)},E=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",E),l.addEventListener("focus",w),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",w),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},Tv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Bl=(r,e={})=>{var C,w,E,H,I,L,O,$,te,xe,Je,we,De;let{wrapperClassName:t=Tv,buttonSize:n,iconSize:o="20px"}=e,s=(w=((C=r==null?void 0:r.launcher)!=null?C:{}).clearChat)!=null?w:{},i=(E=n!=null?n:s.size)!=null?E:"32px",d=(H=s.iconName)!=null?H:"refresh-cw",l=(I=s.iconColor)!=null?I:"",u=(L=s.backgroundColor)!=null?L:"",m=(O=s.borderWidth)!=null?O:"",p=($=s.borderColor)!=null?$:"",f=(te=s.borderRadius)!=null?te:"",b=(xe=s.paddingX)!=null?xe:"",h=(Je=s.paddingY)!=null?Je:"",S=(we=s.tooltipText)!=null?we:"Clear chat",T=(De=s.showTooltip)!=null?De:!0,M=v("div",t),k=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",S),k.style.color=l||an.actionIconColor;let x=Me(d,o,"currentColor",1);if(x&&(x.style.display="block",k.appendChild(x)),u&&(k.style.backgroundColor=u,k.classList.remove("hover:persona-bg-gray-100")),m||p){let Ae=m||"0px",qe=p||"transparent";k.style.border=`${Ae} solid ${qe}`,k.classList.remove("persona-border-none")}if(f&&(k.style.borderRadius=f,k.classList.remove("persona-rounded-full")),b&&(k.style.paddingLeft=b,k.style.paddingRight=b),h&&(k.style.paddingTop=h,k.style.paddingBottom=h),M.appendChild(k),T&&S){let Ae=null,qe=()=>{if(Ae)return;let J=k.ownerDocument,re=J.body;if(!re)return;Ae=ro(J,"div","persona-clear-chat-tooltip"),Ae.textContent=S;let Q=ro(J,"div");Q.className="persona-clear-chat-tooltip-arrow",Ae.appendChild(Q);let ge=k.getBoundingClientRect();Ae.style.position="fixed",Ae.style.zIndex=String(Uo),Ae.style.left=`${ge.left+ge.width/2}px`,Ae.style.top=`${ge.top-8}px`,Ae.style.transform="translate(-50%, -100%)",re.appendChild(Ae)},He=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};M.addEventListener("mouseenter",qe),M.addEventListener("mouseleave",He),k.addEventListener("focus",qe),k.addEventListener("blur",He),M._cleanupTooltip=()=>{He(),M.removeEventListener("mouseenter",qe),M.removeEventListener("mouseleave",He),k.removeEventListener("focus",qe),k.removeEventListener("blur",He)}}return{button:k,wrapper:M}};var an={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))"},Co=r=>{var C,w,E,H,I,L,O,$,te,xe,Je,we,De,Ae,qe,He;let{config:e,showClose:t=!0}=r,n=v("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(C=e==null?void 0:e.launcher)!=null?C:{},a=(w=o.headerIconSize)!=null?w:"48px",s=(E=o.closeButtonPlacement)!=null?E:"inline",i=(H=o.headerIconHidden)!=null?H:!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=a,l.style.width=a,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let J=parseFloat(a)||24,re=Me(d,J*.6,"currentColor",1);re?l.replaceChildren(re):l.textContent=(L=(I=e==null?void 0:e.launcher)==null?void 0:I.agentIconText)!=null?L:"\u{1F4AC}"}else if((O=e==null?void 0:e.launcher)!=null&&O.iconUrl){let J=v("img");J.src=e.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=a,J.style.width=a,l.replaceChildren(J)}else l.textContent=(te=($=e==null?void 0:e.launcher)==null?void 0:$.agentIconText)!=null?te:"\u{1F4AC}";let u=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=an.titleColor,m.textContent=(Je=(xe=e==null?void 0:e.launcher)==null?void 0:xe.title)!=null?Je:"Chat Assistant";let p=v("span","persona-text-xs");p.style.color=an.subtitleColor,p.textContent=(De=(we=e==null?void 0:e.launcher)==null?void 0:we.subtitle)!=null?De:"Here to help you get answers fast",u.append(m,p),i?n.append(u):n.append(l,u);let f=(Ae=o.clearChat)!=null?Ae:{},b=(qe=f.enabled)!=null?qe:!0,h=(He=f.placement)!=null?He:"inline",S=null,T=null;if(b){let re=Bl(e,{wrapperClassName:h==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=re.button,T=re.wrapper,h==="top-right"&&(T.style.right="48px"),h==="inline"&&n.appendChild(T)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&h==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:x}=Wl(e,{showClose:t,wrapperClassName:M});return s!=="top-right"&&n.appendChild(x),{header:n,iconHolder:l,headerTitle:m,headerSubtitle:p,closeButton:k,closeButtonWrapper:x,clearChatButton:S,clearChatButtonWrapper:T}},ya=(r,e,t)=>{var s,i,d,l;let n=(s=t==null?void 0:t.launcher)!=null?s:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",a=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";r.appendChild(e.header),o==="top-right"&&(r.style.position="relative",r.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&a==="top-right"&&(r.style.position="relative",r.appendChild(e.clearChatButtonWrapper))};function $o(r){let{items:e,onSelect:t,anchor:n,position:o="bottom-left",portal:a}=r,s=v("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Uo)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",o==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of e){if(f.dividerBefore){let S=document.createElement("hr");s.appendChild(S)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",f.id),f.destructive&&b.setAttribute("data-destructive",""),f.icon){let S=Me(f.icon,16,"currentColor",1.5);S&&b.appendChild(S)}let h=document.createElement("span");h.textContent=f.label,b.appendChild(h),b.addEventListener("click",S=>{S.stopPropagation(),u(),t(f.id)}),s.appendChild(b)}let i=null;function d(){if(!a)return;let f=n.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,o==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function l(){d(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=b=>{!s.contains(b.target)&&!n.contains(b.target)&&u()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function m(){s.classList.contains("persona-hidden")?l():u()}function p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:u,toggle:m,destroy:p}}function Dr(r){let{icon:e,label:t,size:n,strokeWidth:o,className:a,onClick:s,aria:i}=r,d=v("button","persona-icon-btn"+(a?" "+a:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Me(e,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),s&&d.addEventListener("click",s),i)for(let[u,m]of Object.entries(i))d.setAttribute(u,m);return d}function oi(r){let{icon:e,label:t,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:d}=r,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,s&&(l+=" "+s);let u=v("button",l);if(u.type="button",u.setAttribute("aria-label",t),e){let p=Me(e,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let m=v("span");if(m.textContent=t,u.appendChild(m),i&&u.addEventListener("click",i),d)for(let[p,f]of Object.entries(d))u.setAttribute(p,f);return u}function kx(r){let{items:e,selectedId:t,onSelect:n,className:o}=r,a=v("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of e){let m;u.icon?m=Dr({icon:u.icon,label:u.label,onClick:()=>{s=u.id,d(),n(u.id)}}):(m=v("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{s=u.id,d(),n(u.id)})),m.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:m}),a.appendChild(m)}function l(u){s=u,d()}return{element:a,setSelected:l}}function Dl(r){var f,b;let{label:e,icon:t="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:d}=r,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 u=v("span","persona-combo-btn-label");u.textContent=e,l.appendChild(u);let m=Me(t,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=(b=d.padding)!=null?b:"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 h,S;l.style.backgroundColor=(h=d.background)!=null?h:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let p=$o({items:n,onSelect:h=>{l.setAttribute("aria-expanded","false"),o(h)},anchor:l,position:a,portal:s});return s||l.appendChild(p.element),l.addEventListener("click",h=>{h.stopPropagation();let S=!p.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),p.toggle()}),l.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),l.click())}),{element:l,setLabel:h=>{u.textContent=h,l.setAttribute("aria-label",h)},open:()=>{l.setAttribute("aria-expanded","true"),p.show()},close:()=>{l.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let h=!p.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",h?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),l.remove()}}}var Yp=r=>{var n;let e=Co({config:r.config,showClose:r.showClose,onClose:r.onClose,onClearChat:r.onClearChat}),t=(n=r.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),t())}))}return e};function Mv(r,e,t){var n,o,a;if(e!=null&&e.length)for(let s 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=s.ariaLabel)!=null?n:s.label)!=null?o:s.id),s.icon){let d=Me(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let d=v("div","persona-relative");d.appendChild(i);let l=$o({items:s.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),r.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(s.id)),r.appendChild(i)}}var Zp=r=>{var M,k,x,C,w,E,H,I,L;let{config:e,showClose:t=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=r,s=(M=e==null?void 0:e.launcher)!=null?M:{},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,u;if(d)l=Dl({label:(k=s.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=an.titleColor,u=(x=l.querySelector(".persona-combo-btn-label"))!=null?x:l;else{if(l=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=an.titleColor,u.textContent=(C=s.title)!=null?C:"Chat Assistant",l.appendChild(u),Mv(l,o==null?void 0:o.trailingActions,(w=o==null?void 0:o.onAction)!=null?w:a),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=o.onTitleClick;l.addEventListener("click",te=>{te.target.closest("button")||$()}),l.addEventListener("keydown",te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),$())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",l.style.padding=(H=O.padding)!=null?H:"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 $,te;l.style.backgroundColor=($=O.background)!=null?$:"",l.style.borderColor=(te=O.border)!=null?te:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(I=s.closeButtonSize)!=null?I:"32px",p=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=t?"":"none",f.style.color=s.closeButtonColor||an.actionIconColor;let b=(L=s.closeButtonIconName)!=null?L:"x",h=Me(b,"28px","currentColor",1);h?f.appendChild(h):f.textContent="\xD7",n&&f.addEventListener("click",n),p.appendChild(f),i.appendChild(p);let S=v("div");S.style.display="none";let T=v("span");return T.style.display="none",{header:i,iconHolder:S,headerTitle:u,headerSubtitle:T,closeButton:f,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},Fl={default:Yp,minimal:Zp},eu=r=>{var e;return(e=Fl[r])!=null?e:Fl.default},Qa=(r,e,t)=>{var s,i,d;if(e!=null&&e.render){let l=e.render({config:r,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=v("div");u.style.display="none";let m=v("span"),p=v("span"),f=v("button");f.style.display="none";let b=v("div");return b.style.display="none",{header:l,iconHolder:u,headerTitle:m,headerSubtitle:p,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let n=(s=e==null?void 0:e.layout)!=null?s:"default",a=eu(n)({config:r,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(a.iconHolder.style.display="none"),e.showTitle===!1&&(a.headerTitle.style.display="none"),e.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(a.closeButton.style.display="none"),e.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ol=r=>{var s,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(s=r==null?void 0:r.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,n=20;e.style.maxHeight=`${t*n}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*n},a=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:a}},Nl=r=>{var C,w,E,H,I,L,O,$,te,xe,Je,we;let e=(C=r==null?void 0:r.sendButton)!=null?C:{},t=(w=e.useIcon)!=null?w:!1,n=(E=e.iconText)!=null?E:"\u2191",o=e.iconName,a=(H=e.stopIconName)!=null?H:"square",s=(I=e.tooltipText)!=null?I:"Send message",i=(L=e.stopTooltipText)!=null?L:"Stop generating",d=($=(O=r==null?void 0:r.copy)==null?void 0:O.sendButtonLabel)!=null?$:"Send",l=(xe=(te=r==null?void 0:r.copy)==null?void 0:te.stopButtonLabel)!=null?xe:"Stop",u=(Je=e.showTooltip)!=null?Je:!1,m=(we=e.size)!=null?we:"40px",p=e.backgroundColor,f=e.textColor,b=v("div","persona-send-button-wrapper"),h=v("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");h.type="submit",h.setAttribute("data-persona-composer-submit","");let S=null,T=null;if(t){h.style.width=m,h.style.height=m,h.style.minWidth=m,h.style.minHeight=m,h.style.fontSize="18px",h.style.lineHeight="1",h.innerHTML="",f?h.style.color=f:h.style.color="var(--persona-button-primary-fg, #ffffff)";let De=parseFloat(m)||24,Ae=(f==null?void 0:f.trim())||"currentColor";o?(S=Me(o,De,Ae,2),S?h.appendChild(S):h.textContent=n):h.textContent=n,T=Me(a,De,Ae,2),p?h.style.backgroundColor=p:h.classList.add("persona-bg-persona-primary")}else h.textContent=d,f?h.style.color=f:h.classList.add("persona-text-white");e.borderWidth&&(h.style.borderWidth=e.borderWidth,h.style.borderStyle="solid"),e.borderColor&&(h.style.borderColor=e.borderColor),e.paddingX?(h.style.paddingLeft=e.paddingX,h.style.paddingRight=e.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),e.paddingY?(h.style.paddingTop=e.paddingY,h.style.paddingBottom=e.paddingY):(h.style.paddingTop="",h.style.paddingBottom="");let M=null;u&&s&&(M=v("div","persona-send-button-tooltip"),M.textContent=s,b.appendChild(M)),h.setAttribute("aria-label",s),b.appendChild(h);let k="send";return{button:h,wrapper:b,setMode:De=>{if(De===k)return;k=De;let Ae=De==="stop"?i:s;if(h.setAttribute("aria-label",Ae),M&&(M.textContent=Ae),t){if(S&&T){let qe=De==="stop"?T:S;h.replaceChildren(qe)}}else h.textContent=De==="stop"?l:d}}},_l=r=>{var M,k,x,C,w,E,H,I,L,O,$,te;let e=(M=r==null?void 0:r.voiceRecognition)!=null?M:{};if(!(e.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(n||o))return null;let s=(C=(x=r==null?void 0:r.sendButton)==null?void 0:x.size)!=null?C:"40px",i=v("div","persona-send-button-wrapper"),d=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=e.iconName)!=null?w:"mic",u=(E=e.iconSize)!=null?E:s,m=parseFloat(u)||24,p=(I=e.backgroundColor)!=null?I:(H=r==null?void 0:r.sendButton)==null?void 0:H.backgroundColor,f=(O=e.iconColor)!=null?O:(L=r==null?void 0:r.sendButton)==null?void 0:L.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",f?d.style.color=f:d.style.color="var(--persona-text, #111827)";let h=Me(l,m,f||"currentColor",1.5);h?d.appendChild(h):d.textContent="\u{1F3A4}",p&&(d.style.backgroundColor=p),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=($=e.tooltipText)!=null?$:"Start voice recognition";if(((te=e.showTooltip)!=null?te:!1)&&S){let xe=v("div","persona-send-button-tooltip");xe.textContent=S,i.appendChild(xe)}return{button:d,wrapper:i}},Ul=r=>{var b,h,S,T,M,k,x,C;let e=(b=r==null?void 0:r.attachments)!=null?b:{};if(e.enabled!==!0)return null;let t=(S=(h=r==null?void 0:r.sendButton)==null?void 0:h.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=((T=e.allowedTypes)!=null?T:yo).join(","),o.multiple=((M=e.maxFiles)!=null?M:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let a=v("div","persona-send-button-wrapper"),s=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");s.type="button",s.setAttribute("aria-label",(k=e.buttonTooltipText)!=null?k:"Attach file");let i=(x=e.buttonIconName)!=null?x:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);s.style.width=d,s.style.height=d,s.style.minWidth=d,s.style.minHeight=d,s.style.fontSize="18px",s.style.lineHeight="1",s.style.backgroundColor="transparent",s.style.color="var(--persona-primary, #111827)",s.style.border="none",s.style.borderRadius="6px",s.style.transition="background-color 0.15s ease",s.addEventListener("mouseenter",()=>{s.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),s.addEventListener("mouseleave",()=>{s.style.backgroundColor="transparent"});let m=Me(i,u,"currentColor",1.5);m?s.appendChild(m):s.textContent="\u{1F4CE}",s.addEventListener("click",w=>{w.preventDefault(),o.click()}),a.appendChild(s);let p=(C=e.buttonTooltipText)!=null?C:"Attach file",f=v("div","persona-send-button-tooltip");return f.textContent=p,a.appendChild(f),{button:s,wrapper:a,input:o,previewsContainer:n}},ql=r=>{var s,i,d;let e=(s=r==null?void 0:r.statusIndicator)!=null?s:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",n=v("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;n.style.display=o?"":"none";let a=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=v("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=a;return n},zl=()=>v("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ja=r=>{var b,h,S,T,M,k;let{config:e}=r,t=v("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=zl(),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:a,attachAutoResize:s}=Ol(e);s();let i=Nl(e),d=_l(e),l=Ul(e),u=ql(e);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(a);let m=v("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),p=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&&p.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(p,f),o.append(m),o.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==(d==null?void 0:d.button)&&x.target!==(d==null?void 0:d.wrapper)&&x.target!==(l==null?void 0:l.button)&&x.target!==(l==null?void 0:l.wrapper)&&a.focus()}),t.append(n,o,u),{footer:t,suggestions:n,composerForm:o,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(h=d==null?void 0:d.wrapper)!=null?h:null,statusText:u,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(M=l==null?void 0:l.input)!=null?M:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Ex=()=>{let r=v("button","persona-pill-peek");r.type="button",r.setAttribute("data-persona-pill-peek",""),r.setAttribute("aria-label","Show conversation"),r.setAttribute("tabindex","-1");let e=v("span","persona-pill-peek__icon"),t=Me("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let n=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),a=Me("chevron-up",16,"currentColor",1.5);return a&&o.appendChild(a),r.append(e,n,o),{root:r,textNode:n}},Lx=r=>{var b,h,S,T,M,k;let{config:e}=r,t=v("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let n=zl();n.style.display="none";let o=ql(e);o.style.display="none";let{textarea:a,attachAutoResize:s}=Ol(e);a.style.maxHeight="100px",s();let i=Nl(e),d=_l(e),l=Ul(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=v("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let m=v("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let p=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&p.append(d.wrapper),p.append(i.wrapper),u.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==(d==null?void 0:d.button)&&x.target!==(d==null?void 0:d.wrapper)&&x.target!==(l==null?void 0:l.button)&&x.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&u.append(l.input),u.append(m,a,p),l&&t.append(l.previewsContainer),t.append(u,n,o);let f=u;return{footer:t,suggestions:n,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(h=d==null?void 0:d.wrapper)!=null?h:null,statusText:o,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(M=l==null?void 0:l.input)!=null?M:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:m,rightActions:p,setSendButtonMode:i.setMode}};var Px=r=>{var u,m,p,f,b,h,S,T,M,k,x,C,w,E,H,I,L;let e=(m=(u=r==null?void 0:r.launcher)==null?void 0:u.enabled)!=null?m:!0,t=Pr(r);if(zo(r)){let O=(f=(p=r==null?void 0:r.launcher)==null?void 0:p.composerBar)!=null?f:{},$=v("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(b=O.expandedSize)!=null?b:"anchored",$.style.zIndex=String((S=(h=r==null?void 0:r.launcher)==null?void 0:h.zIndex)!=null?S:Xr);let te=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");te.style.width="100%",$.appendChild(te);let xe=v("div","persona-widget-pill-root");return xe.setAttribute("data-persona-composer-bar",""),xe.dataset.state="collapsed",xe.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",xe.style.zIndex=String((k=(M=r==null?void 0:r.launcher)==null?void 0:M.zIndex)!=null?k:Xr),{wrapper:$,panel:te,pillRoot:xe}}if(t){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("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild($),{wrapper:O,panel:$}}if(!e){let O=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),te=(C=(x=r==null?void 0:r.launcher)==null?void 0:x.width)!=null?C:"100%";return O.style.width=te,$.style.width="100%",O.appendChild($),{wrapper:O,panel:$}}let o=(w=r==null?void 0:r.launcher)!=null?w:{},a=o.position&&jn[o.position]?jn[o.position]:jn["bottom-right"],s=v("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(E=r==null?void 0:r.launcher)==null?void 0:E.zIndex)!=null?H:Xr);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(L=(I=r==null?void 0:r.launcher)==null?void 0:I.width)!=null?L:r==null?void 0:r.launcherWidth,l=d!=null?d:An;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},kv=(r,e)=>{var x,C,w,E,H,I,L,O,$;let t=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Wl(r,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=(w=(C=(x=r==null?void 0:r.launcher)==null?void 0:x.clearChat)==null?void 0:C.enabled)!=null?w:!0,s=null,i=null;if(a){let te=Bl(r,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=te.button,i=te.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"),l.style.setProperty("scrollbar-gutter","stable");let u=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let m=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(H=(E=r==null?void 0:r.copy)==null?void 0:E.welcomeTitle)!=null?H:"Hello \u{1F44B}";let p=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(I=r==null?void 0:r.copy)==null?void 0:I.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",u.append(m,p);let f=v("div","persona-flex persona-flex-col persona-gap-3"),b=(O=r==null?void 0:r.layout)==null?void 0:O.contentMaxWidth;b&&(f.style.maxWidth=b,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),(($=r==null?void 0:r.copy)==null?void 0:$.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,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 T=Lx({config:r}),{root:M,textNode:k}=Ex();return t.append(d,o,l,S),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:f,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:m,introSubtitle:p,closeButton:n,closeButtonWrapper:o,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:M,peekTextNode:k}},Rx=(r,e=!0)=>{var S,T,M,k,x,C,w,E,H;if(zo(r))return kv(r,e);let t=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");t.setAttribute("data-persona-theme-zone","container");let n=(S=r==null?void 0:r.layout)==null?void 0:S.header,o=((T=r==null?void 0:r.layout)==null?void 0:T.showHeader)!==!1,a=n?Qa(r,n,{showClose:e}):Co({config:r,showClose:e}),s=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");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages"),s.style.setProperty("scrollbar-gutter","stable");let i=v("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Pr(r)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=v("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(M=r==null?void 0:r.copy)==null?void 0:M.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=v("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(C=(x=r==null?void 0:r.copy)==null?void 0:x.welcomeSubtitle)!=null?C:"Ask anything about your account or products.",i.append(d,l);let u=v("div","persona-flex persona-flex-col persona-gap-3"),m=(w=r==null?void 0:r.layout)==null?void 0:w.contentMaxWidth;m&&(u.style.maxWidth=m,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((E=r==null?void 0:r.copy)==null?void 0:E.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,u);let f=Ja({config:r}),b=((H=r==null?void 0:r.layout)==null?void 0:H.showFooter)!==!1;o?ya(t,a,r):(a.header.style.display="none",ya(t,a,r)),t.append(s);let h=v("div","persona-composer-overlay persona-pointer-events-none");return h.setAttribute("data-persona-composer-overlay",""),h.style.position="absolute",h.style.left="0",h.style.right="0",h.style.bottom="0",h.style.zIndex="20",b||(f.footer.style.display="none"),t.append(f.footer),t.append(h),{container:t,body:s,messagesWrapper:u,composerOverlay:h,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:d,introSubtitle:l,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Ev=r=>{switch(r){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Lv=(r,e)=>{if(!r)return null;let t=Ev(r);if(t===null)return null;let n=e==null?void 0:e[r],o=n!==void 0?n:t;return o||null},Pv=(r,e)=>{let t=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",r),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},Rv=r=>{let e=r.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(r)||e.startsWith("data:image/")||!r.includes(":"))},tu=r=>{let e=r.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(r)||e.startsWith("data:")||!r.includes(":"))},ru=320,Hx=320,Iv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Hv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Wv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Bv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Dv=(r,e,t)=>{if(r.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,a=!1,s=()=>{a||(a=!0,n.remove(),t==null||t())};return r.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=`${ru}px`,l.style.maxHeight=`${Hx}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 u=!1;o+=1,l.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),l.remove(),o===0&&s())}),l.addEventListener("load",()=>{u=!0}),Rv(i.image)?(l.src=i.image,n.appendChild(l)):(u=!0,o=Math.max(0,o-1),l.remove())}),o===0?(s(),null):n}catch{return t==null||t(),null}},Fv=r=>{if(r.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return r.forEach(n=>{if(!tu(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=`${ru}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Ov=r=>{if(r.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return r.forEach(n=>{if(!tu(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=`${ru}px`,o.style.maxHeight=`${Hx}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Nv=r=>{if(r.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return r.forEach(n=>{if(!tu(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),t+=1}),t===0?(e.remove(),null):e}catch{return null}},va=()=>{let r=document.createElement("div");r.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",r.appendChild(e),r.appendChild(t),r.appendChild(n),r.appendChild(o),r},nu=(r,e,t)=>{let n={config:t!=null?t:{},streaming:!0,location:r,defaultRenderer:va};if(e){let o=e(n);if(o!==null)return o}return va()},_v=(r,e)=>{let t=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"?r.userAvatar:r.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",t.appendChild(o)}else t.textContent=n,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Ix=(r,e)=>{let t=v("div","persona-text-xs persona-text-persona-muted"),n=new Date(r.createdAt);return e.format?t.textContent=e.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Uv=(r,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},ou=(r,e,t)=>{var f,b,h,S,T,M;let n=(f=e.showCopy)!=null?f:!0,o=(b=e.showUpvote)!=null?b:!0,a=(h=e.showDownvote)!=null?h:!0;if(!n&&!o&&!a){let k=v("div");return k.style.display="none",k.id=`actions-${r.id}`,k.setAttribute("data-actions-for",r.id),k}let s=(S=e.visibility)!=null?S:"hover",i=(T=e.align)!=null?T:"right",d=(M=e.layout)!=null?M:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"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} ${u} ${s==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${r.id}`,m.setAttribute("data-actions-for",r.id);let p=(k,x,C)=>{let w=Dr({icon:k,label:x,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",C),w};return n&&m.appendChild(p("copy","Copy message","copy")),o&&m.appendChild(p("thumbs-up","Upvote","upvote")),a&&m.appendChild(p("thumbs-down","Downvote","downvote")),m},Ya=(r,e,t,n,o,a)=>{var J,re,Q,ge,Z,G,pe,ke,le,ne,de,Et,wt,We,he,at,Re;let s=t!=null?t:{},i=(J=s.layout)!=null?J:"bubble",d=s.avatar,l=s.timestamp,u=(re=d==null?void 0:d.show)!=null?re:!1,m=(Q=l==null?void 0:l.show)!=null?Q:!1,p=(ge=d==null?void 0:d.position)!=null?ge:"left",f=(Z=l==null?void 0:l.position)!=null?Z:"below",b=Uv(r.role,i),h=v("div",b.join(" "));h.id=`bubble-${r.id}`,h.setAttribute("data-message-id",r.id),h.setAttribute("data-persona-theme-zone",r.role==="user"?"user-message":"assistant-message"),r.role==="user"?(h.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",h.style.color="var(--persona-message-user-text, white)"):r.role==="assistant"&&(h.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",h.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Iv(r),T=(pe=(G=r.content)==null?void 0:G.trim())!=null?pe:"",k=S.length>0&&T===al,x=Rl((le=(ke=a==null?void 0:a.widgetConfig)==null?void 0:ke.features)==null?void 0:le.streamAnimation),C=(Et=(de=(ne=a==null?void 0:a.widgetConfig)==null?void 0:ne.features)==null?void 0:de.streamAnimation)==null?void 0:Et.plugins,w=r.role==="assistant"&&x.type!=="none"?Ys(x.type,C):null,E=r.role==="assistant"&&((wt=w==null?void 0:w.isAnimating)==null?void 0:wt.call(w,r))===!0,H=r.role==="assistant"&&w!==null&&(!!r.streaming||E);H&&(w!=null&&w.bubbleClass)&&h.classList.add(w.bubbleClass);let I=document.createElement("div");I.classList.add("persona-message-content"),H&&w&&(w.containerClass&&I.classList.add(w.containerClass),I.style.setProperty("--persona-stream-step",`${x.speed}ms`),I.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let L=H?Il((We=r.content)!=null?We:"",x.buffer,w,r,!!r.streaming):(he=r.content)!=null?he:"",O=e({text:L,message:r,streaming:!!r.streaming,raw:r.rawContent}),$=O;H&&(w==null?void 0:w.wrap)==="char"?$=Zs(O,"char",r.id,{skipTags:w.skipTags}):H&&(w==null?void 0:w.wrap)==="word"&&($=Zs(O,"word",r.id,{skipTags:w.skipTags}));let te=null;if(k?(te=document.createElement("div"),te.innerHTML=$,te.style.display="none",I.appendChild(te)):I.innerHTML=$,H&&(w!=null&&w.useCaret)&&!k&&T){let j=Hl(),ue=I.querySelectorAll(".persona-stream-char, .persona-stream-word"),nt=ue[ue.length-1];if(nt!=null&&nt.parentNode)nt.parentNode.insertBefore(j,nt.nextSibling);else{let Rt=I.lastElementChild;Rt?Rt.appendChild(j):I.appendChild(j)}}if(m&&f==="inline"&&r.createdAt){let j=Ix(r,l);j.classList.add("persona-ml-2","persona-inline"),I.appendChild(j)}if(S.length>0){let j=Dv(S,!k&&!!T,()=>{k&&te&&(te.style.display="")});j?h.appendChild(j):k&&te&&(te.style.display="")}let xe=Hv(r);if(xe.length>0){let j=Fv(xe);j&&h.appendChild(j)}let Je=Wv(r);if(Je.length>0){let j=Ov(Je);j&&h.appendChild(j)}let we=Bv(r);if(we.length>0){let j=Nv(we);j&&h.appendChild(j)}if(h.appendChild(I),m&&f==="below"&&r.createdAt){let j=Ix(r,l);j.classList.add("persona-mt-1"),h.appendChild(j)}let De=r.role==="assistant"?Lv(r.stopReason,(Re=(at=a==null?void 0:a.widgetConfig)==null?void 0:at.copy)==null?void 0:Re.stopReasonNotice):null;if(r.streaming&&r.role==="assistant"){let j=!!(L&&L.trim()),ue=x.placeholder==="skeleton",nt=ue&&x.buffer==="line"&&j;if(j)nt&&h.appendChild(ei());else if(ue)h.appendChild(ei());else{let Rt=nu("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Rt&&h.appendChild(Rt)}}if(De&&r.stopReason&&!r.streaming&&(T||(I.style.display="none"),h.appendChild(Pv(r.stopReason,De))),r.role==="assistant"&&!r.streaming&&r.content&&r.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let j=ou(r,n,o);h.appendChild(j)}if(!u||r.role==="system")return h;let qe=v("div",`persona-flex persona-gap-2 ${r.role==="user"?"persona-flex-row-reverse":""}`),He=_v(d,r.role);return p==="right"||p==="left"&&r.role==="user"?qe.append(h,He):qe.append(He,h),h.classList.remove("persona-max-w-[85%]"),h.classList.add("persona-max-w-[calc(85%-2.5rem)]"),qe},Wx=(r,e,t,n,o,a)=>{let s=t!=null?t:{};return r.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:r,config:{},streaming:!!r.streaming}):r.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:r,config:{},streaming:!!r.streaming}):Ya(r,e,t,n,o,a)};var Za=new Set,qv=(r,e)=>e==null?!1:typeof e=="string"?(r.textContent=e,!0):(r.appendChild(e),!0),zv=(r,e)=>{var n,o;let t=(o=(n=r.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
|
|
71
|
+
`):""},Bx=(r,e)=>{let t=Za.has(r),n=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),a=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",t?"true":"false");let s=n.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Me(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",a&&(a.style.display=t?"none":a.textContent||a.childNodes.length?"":"none")},au=(r,e)=>{var Je,we,De,Ae,qe,He,J,re,Q,ge,Z;let t=r.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-${r.id}`,n.setAttribute("data-message-id",r.id),!t)return n;let o=(we=(Je=e==null?void 0:e.features)==null?void 0:Je.reasoningDisplay)!=null?we:{},a=o.expandable!==!1,s=a&&Za.has(r.id),i=t.status!=="complete",d=zv(r,(De=o.previewMaxLines)!=null?De:3),l=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");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),p="Thinking...",f=(Ae=e==null?void 0:e.reasoning)!=null?Ae:{},b=String((qe=t.startedAt)!=null?qe:Date.now()),h=()=>{let G=v("span","");return G.setAttribute("data-tool-elapsed",b),G.textContent=Ji(t),G},S=(He=f.renderCollapsedSummary)==null?void 0:He.call(f,{message:r,reasoning:t,defaultSummary:p,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ji(t),createElapsedElement:h});typeof S=="string"&&S.trim()?(m.textContent=S,u.appendChild(m)):S instanceof HTMLElement?u.appendChild(S):(m.textContent=p,u.appendChild(m));let T=v("span","persona-text-xs persona-text-persona-primary");T.textContent=$h(t),u.appendChild(T);let M=(J=o.loadingAnimation)!=null?J:"none",k=f.activeTextTemplate,x=f.completeTextTemplate,C=i?k:x,w=S instanceof HTMLElement,E=(G,pe,ke)=>{let le=ke;for(let ne of pe){let de=v("span","persona-tool-char");de.style.setProperty("--char-index",String(le)),de.textContent=ne===" "?"\xA0":ne,G.appendChild(de),le++}return le},H=(G,pe)=>{m.textContent="";let ke=Yi(G,""),le=0;for(let ne of ke){let de=ne.styles.length>0?(()=>{let Et=v("span",ne.styles.map(wt=>`persona-tool-text-${wt}`).join(" "));return m.appendChild(Et),Et})():m;if(ne.isDuration&&i)de.appendChild(h());else{let Et=ne.isDuration?Ji(t):ne.text;pe?le=E(de,Et,le):de.appendChild(document.createTextNode(Et))}}};if(!w&&C)if(T.style.display="none",m.style.display="",i&&M!=="none"){let G=(re=f.loadingAnimationDuration)!=null?re:2e3;m.setAttribute("data-preserve-animation","true"),M==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`),H(C,!1)):(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="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)),H(C,!0))}else H(C,!1);else if(!w&&i&&M!=="none"){m.style.display="";let G=(Q=f.loadingAnimationDuration)!=null?Q:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="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 pe=m.textContent||p;m.textContent="",E(m,pe,0)}t.status==="complete"&&(m.style.display="none")}else w||(t.status==="complete"?m.style.display="none":m.style.display="");let I=null;if(a){I=v("div","persona-flex persona-items-center");let pe=Me(s?"chevron-up":"chevron-down",16,"currentColor",2);pe?I.appendChild(pe):I.textContent=s?"Hide":"Show";let ke=v("div","persona-flex persona-items-center persona-ml-auto");ke.append(I),l.append(u,ke)}else l.append(u);let L=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(L.setAttribute("data-persona-collapsed-preview","reasoning"),L.style.display="none",L.style.whiteSpace="pre-wrap",!s&&i&&o.activePreview&&d){let G=(Z=(ge=e==null?void 0:e.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:Z.call(ge,{message:r,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});qv(L,G)||(L.textContent=d),L.style.display=""}if(!s&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!a)return n.append(l,L),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=s?"":"none";let $=t.chunks.join(""),te=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return te.textContent=$||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(te),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),I){I.innerHTML="";let pe=Me(s?"chevron-up":"chevron-down",16,"currentColor",2);pe?I.appendChild(pe):I.textContent=s?"Hide":"Show"}O.style.display=s?"":"none",L.style.display=s?"none":L.textContent||L.childNodes.length?"":"none"})(),n.append(l,L,O),n};var es=new Set,$v=(r,e)=>e==null?!1:typeof e=="string"?(r.textContent=e,!0):(r.appendChild(e),!0),Vv=(r,e)=>{var a;let t=r.toolCall;if(!t)return"";let n=((a=t.chunks)!=null?a:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
|
|
72
|
+
`);let o=$a(t.args).trim();return o?o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
73
|
+
`):""},jv=(r,e)=>{var u,m,p,f,b;let t=r.toolCall,n=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(m=n==null?void 0:n.collapsedMode)!=null?m:"tool-call",a=Vv(r,(p=n==null?void 0:n.previewMaxLines)!=null?p:3),s=t?Vh(t):"";if(!t)return{summary:s,previewText:a,isActive:!1};let i=t.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},l=s;return o==="tool-name"?l=((b=t.name)==null?void 0:b.trim())||s:o==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=zd(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=zd(t,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},Dx=(r,e,t)=>{var u;let n=es.has(r),o=(u=t==null?void 0:t.toolCall)!=null?u:{},a=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",n?"true":"false");let d=a.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=o.toggleTextColor||o.headerTextColor||"currentColor",p=Me(n?"chevron-up":"chevron-down",16,m,2);p?l.appendChild(p):l.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},su=(r,e)=>{var $,te,xe,Je,we,De,Ae,qe,He;let t=r.toolCall,n=($=e==null?void 0:e.toolCall)!=null?$:{},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-${r.id}`,o.setAttribute("data-message-id",r.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),o.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let a=(xe=(te=e==null?void 0:e.features)==null?void 0:te.toolCallDisplay)!=null?xe:{},s=a.expandable!==!1,i=s&&es.has(r.id),{summary:d,previewText:l,isActive:u}=jv(r,e),m=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");m.type="button",s&&(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 p=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 b=String((Je=t.startedAt)!=null?Je:Date.now()),h=()=>{let J=v("span","");return J.setAttribute("data-tool-elapsed",b),J.textContent=zs(t),J},S=(De=n.renderCollapsedSummary)==null?void 0:De.call(n,{message:r,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(we=a.collapsedMode)!=null?we:"tool-call",isActive:u,config:e!=null?e:{},elapsed:zs(t),createElapsedElement:h});typeof S=="string"&&S.trim()?(f.textContent=S,p.appendChild(f)):S instanceof HTMLElement?p.appendChild(S):(f.textContent=d,p.appendChild(f));let T=(Ae=a.loadingAnimation)!=null?Ae:"none",M=n.activeTextTemplate,k=n.completeTextTemplate,x=u?M:k,C=S instanceof HTMLElement,w=(J,re,Q)=>{let ge=Q;for(let Z of re){let G=v("span","persona-tool-char");G.style.setProperty("--char-index",String(ge)),G.textContent=Z===" "?"\xA0":Z,J.appendChild(G),ge++}return ge},E=(J,re)=>{var G;f.textContent="";let Q=((G=t.name)==null?void 0:G.trim())||"tool",ge=Yi(J,Q),Z=0;for(let pe of ge){let ke=pe.styles.length>0?(()=>{let le=v("span",pe.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return f.appendChild(le),le})():f;if(pe.isDuration&&u)ke.appendChild(h());else{let le=pe.isDuration?zs(t):pe.text;re?Z=w(ke,le,Z):ke.appendChild(document.createTextNode(le))}}};if(!C)if(u&&T!=="none"){let J=(qe=n.loadingAnimationDuration)!=null?qe:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${J}ms`),x&&E(x,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${J}ms`),T==="shimmer-color"&&(n.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),x)E(x,!0);else{let re=f.textContent||d;f.textContent="",w(f,re,0)}}else x&&E(x,!1);let H=null;if(s){H=v("div","persona-flex persona-items-center");let J=n.toggleTextColor||n.headerTextColor||"currentColor",re=Me(i?"chevron-up":"chevron-down",16,J,2);re?H.appendChild(re):H.textContent=i?"Hide":"Show";let Q=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(H),m.append(p,Q)}else m.append(p);let I=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","tool"),I.style.display="none",I.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&l){let J=(He=n.renderCollapsedPreview)==null?void 0:He.call(n,{message:r,toolCall:t,defaultPreview:l,isActive:u,config:e!=null?e:{}});$v(I,J)||(I.textContent=l),I.style.display=""}if(!i&&u&&a.activeMinHeight&&(o.style.minHeight=a.activeMinHeight),!s)return o.append(m,I),o;let L=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",n.contentBackgroundColor&&(L.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(L.style.color=n.contentTextColor),n.contentPaddingX&&(L.style.paddingLeft=n.contentPaddingX,L.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(L.style.paddingTop=n.contentPaddingY,L.style.paddingBottom=n.contentPaddingY),t.name){let J=v("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?J.style.color=n.contentTextColor:n.headerTextColor&&(J.style.color=n.headerTextColor),J.textContent=t.name,L.appendChild(J)}if(t.args!==void 0){let J=v("div","persona-space-y-1"),re=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(re.style.color=n.labelTextColor),re.textContent="Arguments";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(Q.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(Q.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(Q.style.color=n.codeBlockTextColor),Q.textContent=$a(t.args),J.append(re,Q),L.appendChild(J)}if(t.chunks&&t.chunks.length){let J=v("div","persona-space-y-1"),re=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(re.style.color=n.labelTextColor),re.textContent="Activity";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(Q.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(Q.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(Q.style.color=n.codeBlockTextColor),Q.textContent=t.chunks.join(""),J.append(re,Q),L.appendChild(J)}if(t.status==="complete"&&t.result!==void 0){let J=v("div","persona-space-y-1"),re=v("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(re.style.color=n.labelTextColor),re.textContent="Result";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(Q.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(Q.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(Q.style.color=n.codeBlockTextColor),Q.textContent=$a(t.result),J.append(re,Q),L.appendChild(J)}if(t.status==="complete"&&typeof t.duration=="number"){let J=v("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(J.style.color=n.contentTextColor),J.textContent=`Duration: ${t.duration}ms`,L.appendChild(J)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let J=n.toggleTextColor||n.headerTextColor||"currentColor",re=Me(i?"chevron-up":"chevron-down",16,J,2);re?H.appendChild(re):H.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",I.style.display=i?"none":I.textContent||I.childNodes.length?"":"none"})(),o.append(m,I,L),o};var $l=new Map,Gv=r=>{let t=(r.startsWith(go)?r.slice(go.length):r).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return r;let n=t.join(" ").toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},Fx=r=>(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,Ox=(r,e)=>{var n,o,a;let t=(o=(n=Fx(e))==null?void 0:n.detailsDisplay)!=null?o:"collapsed";return(a=$l.get(r))!=null?a:t==="expanded"},Nx=(r,e,t)=>{var s,i;let n=Fx(t);r.setAttribute("aria-expanded",e?"true":"false");let o=r.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(s=n==null?void 0:n.hideDetailsLabel)!=null?s:"Hide details":(i=n==null?void 0:n.showDetailsLabel)!=null?i:"Show details");let a=r.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let d=Me(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&a.appendChild(d)}},_x=(r,e,t)=>{let n=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!n||!o)return;let a=Ox(r,t);Nx(n,a,t),o.style.display=a?"":"none"};var Vl=(r,e)=>{var E,H,I,L,O,$,te,xe,Je,we,De,Ae,qe,He,J;let t=r.approval,n=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",a=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(a.id=`bubble-${r.id}`,a.setAttribute("data-message-id",r.id),a.style.backgroundColor=(E=n==null?void 0:n.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=n==null?void 0:n.borderColor)!=null?H:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(n==null?void 0:n.shadow)!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return a;let s=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=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=n==null?void 0:n.titleColor)!=null?I:"currentColor",u=Me(d,20,l,2);u&&i.appendChild(u);let m=v("div","persona-flex-1 persona-min-w-0"),p=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=(L=n==null?void 0:n.title)!=null?L:"Approval Required",p.appendChild(f),!o){let re=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");re.setAttribute("data-approval-status",t.status),t.status==="approved"?(re.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",re.style.color="var(--persona-palette-colors-success-700, #15803d)",re.textContent="Approved"):t.status==="denied"?(re.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",re.style.color="var(--persona-palette-colors-error-700, #b91c1c)",re.textContent="Denied"):t.status==="timeout"&&(re.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",re.style.color="var(--persona-palette-colors-warning-700, #b45309)",re.textContent="Timeout"),p.appendChild(re)}m.appendChild(p);let h=t.toolType==="webmcp"||t.toolName.startsWith(go)?Rd(t.toolName):void 0,S=(O=n==null?void 0:n.formatDescription)==null?void 0:O.call(n,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...h?{displayTitle:h}:{},...t.reason?{reason:t.reason}:{}}),T=!t.toolName,M=S||(T?t.description:`The assistant wants to use \u201C${h!=null?h:Gv(t.toolName)}\u201D.`),k=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),n!=null&&n.descriptionColor&&(k.style.color=n.descriptionColor),k.textContent=M,m.appendChild(k),t.reason){let re=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");re.setAttribute("data-approval-reason","true"),n!=null&&n.reasonColor?re.style.color=n.reasonColor:n!=null&&n.descriptionColor&&(re.style.color=n.descriptionColor);let Q=v("span","persona-font-medium");Q.textContent=`${($=n==null?void 0:n.reasonLabel)!=null?$:"Agent's stated reason:"} `,re.appendChild(Q),re.appendChild(document.createTextNode(t.reason)),m.appendChild(re)}let x=(te=n==null?void 0:n.detailsDisplay)!=null?te:"collapsed",C=!!t.description&&!T,w=C||!!t.parameters;if(x!=="hidden"&&w){let re=Ox(r.id,e),Q=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");Q.type="button",Q.setAttribute("data-expand-header","true"),Q.setAttribute("data-bubble-type","approval"),n!=null&&n.descriptionColor&&(Q.style.color=n.descriptionColor);let ge=v("span");ge.setAttribute("data-approval-details-label","true");let Z=v("span","persona-inline-flex persona-items-center");Z.setAttribute("data-approval-details-chevron","true"),Q.append(ge,Z),Nx(Q,re,e),m.appendChild(Q);let G=v("div");if(G.setAttribute("data-approval-details","true"),G.style.display=re?"":"none",C){let pe=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");n!=null&&n.descriptionColor&&(pe.style.color=n.descriptionColor),pe.textContent=t.description,G.appendChild(pe)}if(t.parameters){let pe=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&&(pe.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(pe.style.color=n.parameterTextColor),pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",pe.textContent=$a(t.parameters),G.appendChild(pe)}m.appendChild(G)}if(o){let re=v("div","persona-flex persona-gap-2 persona-mt-2");re.setAttribute("data-approval-buttons","true");let Q=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");Q.type="button",Q.style.backgroundColor=(xe=n==null?void 0:n.approveButtonColor)!=null?xe:"var(--persona-approval-approve-bg, #22c55e)",Q.style.color=(Je=n==null?void 0:n.approveButtonTextColor)!=null?Je:"#ffffff",Q.setAttribute("data-approval-action","approve");let ge=Me("shield-check",14,(we=n==null?void 0:n.approveButtonTextColor)!=null?we:"#ffffff",2);ge&&(ge.style.marginRight="4px",Q.appendChild(ge));let Z=document.createTextNode((De=n==null?void 0:n.approveLabel)!=null?De:"Approve");Q.appendChild(Z);let G=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");G.type="button",G.style.backgroundColor=(Ae=n==null?void 0:n.denyButtonColor)!=null?Ae:"transparent",G.style.color=(qe=n==null?void 0:n.denyButtonTextColor)!=null?qe:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let pe=Me("shield-x",14,(He=n==null?void 0:n.denyButtonTextColor)!=null?He:"var(--persona-feedback-error, #dc2626)",2);pe&&(pe.style.marginRight="4px",G.appendChild(pe));let ke=document.createTextNode((J=n==null?void 0:n.denyLabel)!=null?J:"Deny");G.appendChild(ke),re.append(Q,G),m.appendChild(re)}return s.append(i,m),a.appendChild(s),a};var Ux=r=>{let e=[],t=null;return{buttons:e,render:(o,a,s,i,d,l)=>{r.innerHTML="",e.length=0;let u=(l==null?void 0:l.agentPushed)===!0;if(u||(t=null),!o||!o.length||!u&&(i!=null?i:a?a.getMessages():[]).some(S=>S.role==="user"))return;let m=document.createDocumentFragment(),p=a?a.isStreaming():!1,f=b=>{switch(b){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'}};if(o.forEach(b=>{let h=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");h.type="button",h.textContent=b,h.disabled=p,d!=null&&d.fontFamily&&(h.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(h.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(h.style.paddingLeft=d.paddingX,h.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(h.style.paddingTop=d.paddingY,h.style.paddingBottom=d.paddingY),h.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",u&&r.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),a.sendMessage(b))}),m.appendChild(h),e.push(h)}),r.appendChild(m),u){let b=JSON.stringify(o);b!==t&&(t=b,r.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ai=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var si=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,e()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(n){t(n)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{e()},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)n.put(o)}catch{}}};var Kv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Xv=new Set(["step_start","execution_start"]),Qv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Jv=new Set(["step_complete","agent_turn_complete"]),Yv=new Set(["flow_complete","agent_complete"]),qx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$x=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Tn=r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,Ca=(r,e)=>{let t=r[e];return $x(t)?t:void 0};function iu(r){return r>0?Math.max(1,Math.ceil(r/4)):0}function jl(r,e){if(!(r<=0||e===void 0||e<250))return r/(e/1e3)}function Zv(r,e){return typeof e.type=="string"?e.type:r}function eC(r){return typeof r.text=="string"?r.text:typeof r.delta=="string"?r.delta:typeof r.content=="string"?r.content:typeof r.chunk=="string"?r.chunk:""}function tC(r,e){return r==="step_delta"||r==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":r!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function zx(r){var n,o,a,s,i;let e=Ca(r,"result"),t=[Ca(r,"tokens"),Ca(r,"totalTokens"),e?Ca(e,"tokens"):void 0,Ca(r,"usage"),e?Ca(e,"usage"):void 0];for(let d of t){if(!d)continue;let l=(o=(n=Tn(d.output))!=null?n:Tn(d.outputTokens))!=null?o:Tn(d.completionTokens);if(l!==void 0)return l}return(i=(a=Tn(r.outputTokens))!=null?a:Tn(r.completionTokens))!=null?i:e?(s=Tn(e.outputTokens))!=null?s:Tn(e.completionTokens):void 0}function rC(r){var t,n,o,a,s;let e=Ca(r,"result");return(s=(o=(n=(t=Tn(r.executionTime))!=null?t:Tn(r.executionTimeMs))!=null?n:Tn(r.execution_time))!=null?o:Tn(r.duration))!=null?s:e?(a=Tn(e.executionTime))!=null?a:Tn(e.executionTimeMs):void 0}function nC(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ii=class{constructor(e=nC){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:jl(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var a;if(!$x(t)){qx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let n=Zv(e,t),o=this.now();if(Kv.has(n)){this.startRun(o);return}if(Xv.has(n)){this.run||this.startRun(o);return}if(Qv.has(n)){if(!tC(n,t))return;let s=eC(t);if(!s)return;this.run||this.startRun(o);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=s.length;let d=i.exactOutputTokens+iu(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:jl(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Jv.has(n)){if(!this.run)return;let s=this.run,i=zx(t);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let d=s.exactOutputTokens>0,l=s.exactOutputTokens+iu(s.visibleCharCount),u=this.resolveDuration(s,t,o);this.metric={status:"running",tokensPerSecond:jl(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Yv.has(n)){if(!this.run)return;let s=this.run,i=zx(t),d=i!=null?i:s.exactOutputTokens+iu(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,t,o);this.metric={status:"complete",tokensPerSecond:jl(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(qx.has(n)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,n){let o=e.firstDeltaAt!==void 0?n-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let a=rC(t);return a!=null?a:n-e.startedAt}};function ts(r,e){e&&e.split(/\s+/).forEach(t=>t&&r.classList.add(t))}var oC={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)"}},aC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},sC=["flowName","stepName","reasoningText","text","name","tool","toolName"],iC=100;function lC(r,e){let t={...oC,...e};if(t[r])return t[r];for(let n of Object.keys(t))if(n.endsWith("_")&&r.startsWith(n))return t[n];return aC}function dC(r,e){return`+${((r-e)/1e3).toFixed(3)}s`}function cC(r){let e=new Date(r),t=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),a=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${o}.${a}`}function pC(r,e){try{let t=JSON.parse(r);if(typeof t!="object"||t===null)return null;for(let n of e){let o=n.split("."),a=t;for(let s of o)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function uC(r){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(r):new Promise(t=>{let n=document.createElement("textarea");n.value=r,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function fC(r){let e;try{e=JSON.parse(r.payload)}catch{e=r.payload}return JSON.stringify({type:r.type,timestamp:new Date(r.timestamp).toISOString(),payload:e},null,2)}function mC(r){return r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)?"-- tok/s":`${r.tokensPerSecond.toFixed(1)} tok/s`}function gC(r){let e=[];return r.outputTokens!==void 0&&e.push(`${r.outputTokens.toLocaleString()} tok`),r.durationMs!==void 0&&e.push(`${(r.durationMs/1e3).toFixed(2)}s`),r.source&&e.push(r.source),e.join(" \xB7 ")}function hC(r,e,t){let n,o;try{o=JSON.parse(r.payload),n=JSON.stringify(o,null,2)}catch{o=r.payload,n=r.payload}let a=e.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&t){let i=a.renderEventStreamPayload({event:r,config:t,defaultRenderer:()=>s(),parsedPayload:o});if(i)return i}return s();function s(){let i=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 lu(r,e,t,n,o,a,s,i){var p;let d=o.has(r.id),l=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ts(l,(p=n.classNames)==null?void 0:p.eventRow);let u=s.find(f=>f.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let f=u.renderEventStreamRow({event:r,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>a(r.id)});if(f)return l.appendChild(f),l}return l.appendChild(m()),l;function m(){var $,te;let f=v("div",""),b=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");b.setAttribute("data-event-id",r.id);let h=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=Me(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&h.appendChild(S);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=($=n.timestampFormat)!=null?$:"relative";T.textContent=M==="relative"?dC(r.timestamp,t):cC(r.timestamp);let k=null;n.showSequenceNumbers!==!1&&(k=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let x=lC(r.type,n.badgeColors),C=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");C.style.backgroundColor=x.bg,C.style.color=x.text,C.style.borderColor=x.text+"50",C.textContent=r.type;let w=(te=n.descriptionFields)!=null?te:sC,E=pC(r.payload,w),H=null;E&&(H=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=E);let I=v("div","persona-flex-1 persona-min-w-0"),L=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=Me("clipboard","12px","currentColor",1.5);return O&&L.appendChild(O),L.addEventListener("click",async xe=>{xe.stopPropagation(),await uC(fC(r)),L.innerHTML="";let Je=Me("check","12px","currentColor",1.5);Je&&L.appendChild(Je),setTimeout(()=>{L.innerHTML="";let we=Me("clipboard","12px","currentColor",1.5);we&&L.appendChild(we)},1500)}),b.appendChild(h),b.appendChild(T),k&&b.appendChild(k),b.appendChild(C),H&&b.appendChild(H),b.appendChild(I),b.appendChild(L),f.appendChild(b),d&&f.appendChild(hC(r,s,i)),f}}function Vx(r){var b,h,S,T,M;let{buffer:e,getFullHistory:t,onClose:n,config:o,plugins:a=[],getThroughput:s}=r,i=(b=o==null?void 0:o.features)==null?void 0:b.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(h=i==null?void 0:i.iconName)!=null?h:"arrow-down",u=(S=i==null?void 0:i.label)!=null?S:"",m=(M=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?M:{},p=a.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let k=p.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=m.classNames,x=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ts(x,k==null?void 0:k.panel);let C=[],w="",E="",H=null,I=[],L={},O=0,$=El(),te=0,xe=0,Je=!1,we=null,De=!1,Ae=0,qe=new Set,He=new Map,J="",re="",Q=null,ge,Z,G,pe,ke,le=null,ne=null,de=null;function Et(){let ye=v("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ie=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");ts(ie,k==null?void 0:k.headerBar);let st=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(st.textContent="Events",ge=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"),ge.textContent="0",s){ne=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let sr=v("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");sr.textContent="Throughput",le=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"),le.textContent="-- tok/s",de=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"),de.style.display="none",de.style.pointerEvents="none";let ur=ne,Mr=de,un=()=>{if(!Mr.textContent)return;let qr=ur.getBoundingClientRect(),xr=ye.getBoundingClientRect();Mr.style.left=`${qr.left-xr.left}px`,Mr.style.top=`${qr.bottom-xr.top+4}px`,Mr.style.display="block"},St=()=>{Mr.style.display="none"};ne.addEventListener("mouseenter",un),ne.addEventListener("mouseleave",St),ne.appendChild(sr),ne.appendChild(le)}let pr=v("div","persona-flex-1");Z=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 pt=v("option","");pt.value="",pt.textContent="All events",Z.appendChild(pt),G=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"),G.type="button",G.title="Copy All";let Rr=Me("clipboard-copy","12px","currentColor",1.5);Rr&&G.appendChild(Rr);let ut=v("span","persona-text-xs");ut.textContent="Copy All",G.appendChild(ut),ie.appendChild(st),ie.appendChild(ge),ne&&ie.appendChild(ne),ie.appendChild(pr),ie.appendChild(Z),ie.appendChild(G);let Lt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ts(Lt,k==null?void 0:k.searchBar);let tt=Me("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=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");tt&&zt.appendChild(tt),pe=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"),ts(pe,k==null?void 0:k.searchInput),pe.type="text",pe.placeholder="Search event payloads...",ke=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ke.type="button",ke.style.display="none";let vr=Me("x","12px","currentColor",2);return vr&&ke.appendChild(vr),Lt.appendChild(zt),Lt.appendChild(pe),Lt.appendChild(ke),ye.appendChild(ie),ye.appendChild(Lt),de&&ye.appendChild(de),ye}let wt,We=a.find(ye=>ye.renderEventStreamToolbar);if(We!=null&&We.renderEventStreamToolbar&&o){let ye=We.renderEventStreamToolbar({config:o,defaultRenderer:()=>Et(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ie=>{w=ie,or(),F()},onSearchChange:ie=>{E=ie,or(),F()}});wt=ye!=null?ye:Et()}else wt=Et();let he=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");he.style.display="none";function at(){if(!s||!le||!ne)return;let ye=s();le.textContent=mC(ye);let ie=gC(ye);de&&(de.textContent=ie,ie||(de.style.display="none")),ie?ne.setAttribute("aria-label",ie):ne.removeAttribute("aria-label")}let Re=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 ue=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");ts(ue,k==null?void 0:k.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let nt=Me(l,"14px","currentColor",2);nt&&ue.appendChild(nt);let Rt=v("span","");Rt.textContent=u,ue.appendChild(Rt);let ee=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ee.style.display="none",Re.appendChild(j),Re.appendChild(ee),Re.appendChild(ue),x.setAttribute("tabindex","0"),x.appendChild(wt),x.appendChild(he),x.appendChild(Re);function Ge(){let ye=e.getAll(),ie={};for(let ut of ye)ie[ut.type]=(ie[ut.type]||0)+1;let st=Object.keys(ie).sort(),pr=st.length!==I.length||!st.every((ut,Lt)=>ut===I[Lt]),pt=!pr&&st.some(ut=>ie[ut]!==L[ut]),yr=ye.length!==Object.values(L).reduce((ut,Lt)=>ut+Lt,0);if(!pr&&!pt&&!yr||(I=st,L=ie,!Z))return;let Rr=Z.value;if(Z.options[0].textContent="All events",pr){for(;Z.options.length>1;)Z.remove(1);for(let ut of st){let Lt=v("option","");Lt.value=ut,Lt.textContent=`${ut} (${ie[ut]||0})`,Z.appendChild(Lt)}Rr&&st.includes(Rr)?Z.value=Rr:Rr&&(Z.value="",w="")}else for(let ut=1;ut<Z.options.length;ut++){let Lt=Z.options[ut];Lt.textContent=`${Lt.value} (${ie[Lt.value]||0})`}}function Fr(){let ye=e.getAll();if(w&&(ye=ye.filter(ie=>ie.type===w)),E){let ie=E.toLowerCase();ye=ye.filter(st=>st.type.toLowerCase().includes(ie)||st.payload.toLowerCase().includes(ie))}return ye}function Bt(){return w!==""||E!==""}function or(){O=0,te=0,$.resume(),ue.style.display="none"}function hr(ye){qe.has(ye)?qe.delete(ye):qe.add(ye),Q=ye;let ie=j.scrollTop,st=$.isFollowing();De=!0,$.pause(),F(),j.scrollTop=ie,st&&$.resume(),De=!1}function sn(){return xa(j,50)}function F(){xe=Date.now(),Je=!1,at(),Ge();let ye=e.getEvictedCount();ye>0?(he.textContent=`${ye.toLocaleString()} older events truncated`,he.style.display=""):he.style.display="none",C=Fr();let ie=C.length,st=e.getSize()>0;ge&&(ge.textContent=String(e.getSize())),ie===0&&st&&Bt()?(ee.textContent=E?`No events matching '${E}'`:"No events matching filter",ee.style.display="",j.style.display="none"):(ee.style.display="none",j.style.display=""),G&&(G.title=Bt()?`Copy Filtered (${ie})`:"Copy All"),d&&!$.isFollowing()&&ie>O&&(te+=ie-O,Rt.textContent=u?`${u}${te>0?` (${te})`:""}`:"",ue.style.display=""),O=ie;let pr=e.getAll(),pt=pr.length>0?pr[0].timestamp:0,yr=new Set(C.map(Lt=>Lt.id));for(let Lt of qe)yr.has(Lt)||qe.delete(Lt);let Rr=w!==J||E!==re,ut=He.size===0&&C.length>0;if(Rr||ut||C.length===0){j.innerHTML="",He.clear();let Lt=document.createDocumentFragment();for(let tt=0;tt<C.length;tt++){let zt=lu(C[tt],tt,pt,m,qe,hr,a,o);He.set(C[tt].id,zt),Lt.appendChild(zt)}j.appendChild(Lt),J=w,re=E,Q=null}else{if(Q!==null){let tt=He.get(Q);if(tt&&tt.parentNode===j){let zt=C.findIndex(vr=>vr.id===Q);if(zt>=0){let vr=lu(C[zt],zt,pt,m,qe,hr,a,o);j.insertBefore(vr,tt),tt.remove(),He.set(Q,vr)}}Q=null}let Lt=new Set(C.map(tt=>tt.id));for(let[tt,zt]of He)Lt.has(tt)||(zt.remove(),He.delete(tt));for(let tt=0;tt<C.length;tt++){let zt=C[tt];if(!He.has(zt.id)){let vr=lu(zt,tt,pt,m,qe,hr,a,o);He.set(zt.id,vr),j.appendChild(vr)}}}$.isFollowing()&&(j.scrollTop=j.scrollHeight)}function fe(){if(Date.now()-xe>=iC){we!==null&&(cancelAnimationFrame(we),we=null),F();return}Je||(Je=!0,we=requestAnimationFrame(()=>{we=null,F()}))}let Ie=(ye,ie)=>{if(!G)return;G.innerHTML="";let st=Me(ye,"12px","currentColor",1.5);st&&G.appendChild(st);let pr=v("span","persona-text-xs");pr.textContent="Copy All",G.appendChild(pr),setTimeout(()=>{G.innerHTML="";let pt=Me("clipboard-copy","12px","currentColor",1.5);pt&&G.appendChild(pt);let yr=v("span","persona-text-xs");yr.textContent="Copy All",G.appendChild(yr),G.disabled=!1},ie)},Xe=async()=>{if(G){G.disabled=!0;try{let ye;Bt()?ye=C:t?(ye=await t(),ye.length===0&&(ye=e.getAll())):ye=e.getAll();let ie=ye.map(st=>{try{return JSON.parse(st.payload)}catch{return st.payload}});await navigator.clipboard.writeText(JSON.stringify(ie,null,2)),Ie("check",1500)}catch{Ie("x",1500)}}},Fe=()=>{Z&&(w=Z.value,or(),F())},Ne=()=>{!pe||!ke||(ke.style.display=pe.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{E=pe.value,or(),F()},150))},Ye=()=>{!pe||!ke||(pe.value="",E="",ke.style.display="none",H&&clearTimeout(H),or(),F())},At=()=>{if(De)return;let ye=j.scrollTop,{action:ie,nextLastScrollTop:st}=Ll({following:$.isFollowing(),currentScrollTop:ye,lastScrollTop:Ae,nearBottom:sn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ae=st,ie==="resume"?($.resume(),te=0,ue.style.display="none"):ie==="pause"&&($.pause(),d&&(Rt.textContent=u,ue.style.display=""))},Xt=ye=>{let ie=Pl({following:$.isFollowing(),deltaY:ye.deltaY,nearBottom:sn(),resumeWhenNearBottom:!0});ie==="pause"?($.pause(),d&&(Rt.textContent=u,ue.style.display="")):ie==="resume"&&($.resume(),te=0,ue.style.display="none")},ar=()=>{d&&(j.scrollTop=j.scrollHeight,$.resume(),te=0,ue.style.display="none")},K=ye=>{let ie=ye.target;if(!ie||ie.closest("button"))return;let st=ie.closest("[data-event-id]");if(!st)return;let pr=st.getAttribute("data-event-id");pr&&hr(pr)},mt=ye=>{if((ye.metaKey||ye.ctrlKey)&&ye.key==="f"){ye.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}ye.key==="Escape"&&(pe&&document.activeElement===pe?(Ye(),pe.blur(),x.focus()):n&&n())};G&&G.addEventListener("click",Xe),Z&&Z.addEventListener("change",Fe),pe&&pe.addEventListener("input",Ne),ke&&ke.addEventListener("click",Ye),j.addEventListener("scroll",At),j.addEventListener("wheel",Xt,{passive:!0}),j.addEventListener("click",K),ue.addEventListener("click",ar),x.addEventListener("keydown",mt);function it(){H&&clearTimeout(H),we!==null&&(cancelAnimationFrame(we),we=null),Je=!1,He.clear(),G&&G.removeEventListener("click",Xe),Z&&Z.removeEventListener("change",Fe),pe&&pe.removeEventListener("input",Ne),ke&&ke.removeEventListener("click",Ye),j.removeEventListener("scroll",At),j.removeEventListener("wheel",Xt),j.removeEventListener("click",K),ue.removeEventListener("click",ar),x.removeEventListener("keydown",mt)}return{element:x,update:fe,destroy:it}}}function jx(r,e){let t=typeof r.title=="string"&&r.title?r.title:"Untitled artifact",n=typeof r.artifactId=="string"?r.artifactId:"",o=r.status==="streaming"?"streaming":"complete",s=(typeof r.artifactType=="string"?r.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;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 p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(p);let f=document.createElement("span");f.textContent=`Generating ${s.toLowerCase()}...`,m.appendChild(f)}else m.textContent=s;if(l.append(u,m),i.append(d,l),o==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${t}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",n),i.append(p)}return i}var Gx=(r,e)=>{var n,o,a;let t=(a=(o=(n=e==null?void 0:e.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:a.renderCard;if(t){let s=typeof r.title=="string"&&r.title?r.title:"Untitled artifact",i=typeof r.artifactId=="string"?r.artifactId:"",d=r.status==="streaming"?"streaming":"complete",l=typeof r.artifactType=="string"?r.artifactType:"markdown",u=t({artifact:{artifactId:i,title:s,artifactType:l,status:d},config:e.config,defaultRenderer:()=>jx(r,e)});if(u)return u}return jx(r,e)};var du=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,n])=>{this.register(t,n)})}},wo=new du;wo.register("PersonaArtifactCard",Gx);function xC(r){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=v("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=r.component?`Component: ${r.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=r.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(n),e}function Kx(r,e){var Z,G,pe,ke;let t=(G=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:G.layout,o=((pe=t==null?void 0:t.toolbarPreset)!=null?pe:"default")==="document",a=(ke=t==null?void 0:t.panePadding)==null?void 0:ke.trim(),s=r.markdown?ia(r.markdown):null,i=Na(r.sanitize),d=le=>{let ne=s?s(le):la(le);return i?i(ne):ne},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,u=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var le;u(),(le=e.onDismiss)==null||le.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 p=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");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&p.classList.add("persona-artifact-toolbar-document");let f=v("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let b=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");b.type="button",b.textContent="Close",b.setAttribute("aria-label","Close artifacts panel"),b.addEventListener("click",()=>{var le;u(),(le=e.onDismiss)==null||le.call(e)});let h="rendered",S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Dr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Dr({icon:"eye",label:"Rendered view"}),M=o?Dr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Dr({icon:"code-2",label:"Source"}),k=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),x=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,C=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(C&&w&&w.length>0),H=null,I,L=null,O=null;if(o&&(x||C)&&!E){if(I=x?oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),C){let le=Me("chevron-down",14,"currentColor",2);le&&I.appendChild(le)}}else o&&E?(H=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),I=x?oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=Dr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),H.append(I,L)):o?I=Dr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):I=Dr({icon:"copy",label:"Copy"});let $=o?Dr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Dr({icon:"refresh-cw",label:"Refresh"}),te=o?Dr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Dr({icon:"x",label:"Close"}),xe=()=>{var wt,We,he;let le=(wt=He.find(at=>at.id===J))!=null?wt:He[He.length-1],ne=(We=le==null?void 0:le.id)!=null?We:null,de=(le==null?void 0:le.artifactType)==="markdown"&&(he=le.markdown)!=null?he:"",Et=le?JSON.stringify({component:le.component,props:le.props},null,2):"";return{markdown:de,jsonPayload:Et,id:ne}},Je=async()=>{var wt;let{markdown:le,jsonPayload:ne}=xe(),de=(wt=He.find(We=>We.id===J))!=null?wt:He[He.length-1],Et=(de==null?void 0:de.artifactType)==="markdown"?le:de?ne:"";try{await navigator.clipboard.writeText(Et)}catch{}};if(I.addEventListener("click",async()=>{let le=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(le&&E){let{markdown:ne,jsonPayload:de,id:Et}=xe();try{await le({actionId:"primary",artifactId:Et,markdown:ne,jsonPayload:de})}catch{}return}await Je()}),L&&(w!=null&&w.length)){let le=()=>{var de;return(de=m.closest("[data-persona-root]"))!=null?de:document.body},ne=()=>{O=$o({items:w.map(de=>({id:de.id,label:de.label})),onSelect:async de=>{let{markdown:Et,jsonPayload:wt,id:We}=xe(),he=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{he?await he({actionId:de,artifactId:We,markdown:Et,jsonPayload:wt}):de==="markdown"||de==="md"?await navigator.clipboard.writeText(Et):de==="json"||de==="source"?await navigator.clipboard.writeText(wt):await navigator.clipboard.writeText(Et||wt)}catch{}},anchor:H!=null?H:L,position:"bottom-right",portal:le()})};m.isConnected?ne():requestAnimationFrame(ne),L.addEventListener("click",de=>{de.stopPropagation(),O==null||O.toggle()})}$.addEventListener("click",async()=>{var le;try{await((le=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:le.call(t))}catch{}Q()}),te.addEventListener("click",()=>{var le;u(),(le=e.onDismiss)==null||le.call(e)});let we=()=>{o&&(T.setAttribute("aria-pressed",h==="rendered"?"true":"false"),M.setAttribute("aria-pressed",h==="source"?"true":"false"))};T.addEventListener("click",()=>{h="rendered",we(),Q()}),M.addEventListener("click",()=>{h="source",we(),Q()});let De=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?(p.replaceChildren(),S.append(T,M),H?k.append(H,$,te):k.append(I,$,te),p.append(S,De,k),we()):(p.appendChild(f),p.appendChild(b)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let Ae=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"),qe=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ae.style.paddingLeft=a,Ae.style.paddingRight=a,qe.style.padding=a),m.appendChild(p),m.appendChild(Ae),m.appendChild(qe);let He=[],J=null,re=!1,Q=()=>{var Et,wt,We,he;let le=o&&He.length<=1;Ae.classList.toggle("persona-hidden",le),Ae.replaceChildren();for(let at of He){let Re=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");Re.type="button",Re.textContent=at.title||at.id.slice(0,8),at.id===J&&Re.classList.add("persona-bg-persona-container","persona-border-persona-border"),Re.addEventListener("click",()=>e.onSelect(at.id)),Ae.appendChild(Re)}qe.replaceChildren();let ne=J&&He.find(at=>at.id===J)||He[He.length-1];if(!ne)return;if(o){let at=ne.artifactType==="markdown"?"MD":(Et=ne.component)!=null?Et:"Component",j=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";De.textContent=`${j} \xB7 ${at}`}else f.textContent="Artifacts";if(ne.artifactType==="markdown"){if(o&&h==="source"){let Re=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Re.textContent=(wt=ne.markdown)!=null?wt:"",qe.appendChild(Re);return}let at=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");at.innerHTML=d((We=ne.markdown)!=null?We:""),qe.appendChild(at);return}let de=ne.component?wo.get(ne.component):void 0;if(de){let Re={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:r,updateProps:()=>{}};try{let j=de((he=ne.props)!=null?he:{},Re);if(j){qe.appendChild(j);return}}catch{}}qe.appendChild(xC(ne))},ge=()=>{var ne;let le=He.length>0;if(m.classList.toggle("persona-hidden",!le),l){let de=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,wt=((ne=de==null?void 0:de.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;le&&wt&&re?(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(le){var ne,de,Et;He=le.artifacts,J=(Et=(de=le.selectedId)!=null?de:(ne=le.artifacts[le.artifacts.length-1])==null?void 0:ne.id)!=null?Et:null,He.length>0&&(re=!0),Q(),ge()},setMobileOpen(le){re=le,!le&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ge()}}}function Bn(r){var e,t;return((t=(e=r==null?void 0:r.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function Xx(r,e){var a,s,i,d;if(r.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),r.style.removeProperty("--persona-artifact-pane-border"),r.style.removeProperty("--persona-artifact-pane-border-left"),!Bn(e))return;let t=(s=(a=e.features)==null?void 0:a.artifacts)==null?void 0:s.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(r.classList.add("persona-artifact-border-full"),r.style.setProperty("--persona-artifact-pane-border",n)):o&&(r.classList.add("persona-artifact-border-left"),r.style.setProperty("--persona-artifact-pane-border-left",o))}function bC(r){r.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),r.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),r.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Gl(r,e){var d,l,u,m,p,f,b,h,S,T;if(!Bn(e)){r.style.removeProperty("--persona-artifact-split-gap"),r.style.removeProperty("--persona-artifact-pane-width"),r.style.removeProperty("--persona-artifact-pane-max-width"),r.style.removeProperty("--persona-artifact-pane-min-width"),r.style.removeProperty("--persona-artifact-pane-bg"),r.style.removeProperty("--persona-artifact-pane-padding"),bC(r),Xx(r,e);return}let t=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;r.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),r.style.setProperty("--persona-artifact-pane-width",(m=t==null?void 0:t.paneWidth)!=null?m:"40%"),r.style.setProperty("--persona-artifact-pane-max-width",(p=t==null?void 0:t.paneMaxWidth)!=null?p:"28rem"),t!=null&&t.paneMinWidth?r.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):r.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=t==null?void 0:t.paneBackground)==null?void 0:f.trim();n?r.style.setProperty("--persona-artifact-pane-bg",n):r.style.removeProperty("--persona-artifact-pane-bg");let o=(b=t==null?void 0:t.panePadding)==null?void 0:b.trim();o?r.style.setProperty("--persona-artifact-pane-padding",o):r.style.removeProperty("--persona-artifact-pane-padding");let a=(h=t==null?void 0:t.documentToolbarIconColor)==null?void 0:h.trim();a?r.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):r.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(S=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:S.trim();s?r.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):r.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?r.style.setProperty("--persona-artifact-doc-toggle-active-border",i):r.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Xx(r,e)}var Qx=["panel","seamless"];function Kl(r,e){var i,d,l,u,m,p;for(let f of Qx)r.classList.remove(`persona-artifact-appearance-${f}`);if(r.classList.remove("persona-artifact-unified-split"),r.style.removeProperty("--persona-artifact-pane-radius"),r.style.removeProperty("--persona-artifact-pane-shadow"),r.style.removeProperty("--persona-artifact-unified-outer-radius"),!Bn(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",o=Qx.includes(n)?n:"panel";r.classList.add(`persona-artifact-appearance-${o}`);let a=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();a&&r.style.setProperty("--persona-artifact-pane-radius",a);let s=(m=t==null?void 0:t.paneShadow)==null?void 0:m.trim();if(s&&r.style.setProperty("--persona-artifact-pane-shadow",s),(t==null?void 0:t.unifiedSplitChrome)===!0){r.classList.add("persona-artifact-unified-split");let f=((p=t.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;f&&r.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Jx(r,e){var t,n,o;return!e||!Bn(r)?!1:((o=(n=(t=r.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function yC(r,e){if(!(r!=null&&r.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(r.trim());return t?Math.max(0,Number(t[1])):e}function vC(r){if(!(r!=null&&r.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(r.trim());return e?Math.max(0,Number(e[1])):null}function CC(r,e,t){return t<e?e:Math.min(t,Math.max(e,r))}function wC(r,e,t,n){let o=r-n-2*e-t;return Math.max(0,o)}function Yx(r,e){var s;let n=(s=(e.getComputedStyle(r).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function Zx(r,e,t,n,o,a){let s=yC(o,200),i=wC(e,t,n,200);i=Math.max(s,i);let d=vC(a);return d!==null&&(i=Math.min(i,d)),CC(r,s,i)}var eb={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=(r,e,t,n)=>{let o=r.querySelectorAll("[data-tv-form]");o.length&&o.forEach(a=>{var b,h,S;if(a.dataset.enhanced==="true")return;let s=(b=a.dataset.tvForm)!=null?b:"init";a.dataset.enhanced="true";let i=(h=eb[s])!=null?h:eb.init;a.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),l=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=v("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var w,E;let M=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${e.id}-${s}-${T.name}`;let k=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,M.appendChild(k);let x=(w=T.type)!=null?w:"text",C;x==="textarea"?(C=document.createElement("textarea"),C.rows=3):(C=document.createElement("input"),C.type=x),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}-${s}-${T.name}`,C.name=T.name,C.placeholder=(E=T.placeholder)!=null?E:"",T.required&&(C.required=!0),M.appendChild(C),u.appendChild(M)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=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(p),m.appendChild(f),u.appendChild(m),a.replaceChildren(d,u),u.addEventListener("submit",async T=>{var C,w;T.preventDefault();let M=(C=t.formEndpoint)!=null?C:"/form",k=new FormData(u),x={};k.forEach((E,H)=>{x[H]=E}),x.type=s,f.disabled=!0,p.textContent="Submitting\u2026";try{let E=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let H=await E.json();p.textContent=(w=H.message)!=null?w:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await n.sendMessage(String(H.nextPrompt))}catch(E){p.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var pu=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var n;let t=this.plugins.get(e);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var n,o;return((n=t.priority)!=null?n:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(a=>a.id));return[...t.filter(a=>!n.has(a.id)),...e].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},li=new pu;var tb=()=>{let r=new Map,e=(o,a)=>(r.has(o)||r.set(o,new Set),r.get(o).add(a),()=>t(o,a)),t=(o,a)=>{var s;(s=r.get(o))==null||s.delete(a)};return{on:e,off:t,emit:(o,a)=>{var s;(s=r.get(o))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var AC=r=>{let e=r.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:r},SC=r=>{let e=r.trim(),t=e.indexOf("{");if(t===-1)return null;let n=0;for(let o=t;o<e.length;o+=1){let a=e[o];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return e.slice(t,o+1)}return null},di=({text:r})=>{if(!r||!r.includes("{"))return null;try{let e=AC(r),t=SC(e);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},uu=r=>typeof r=="string"?r:r==null?"":String(r),wa={message:r=>r.type!=="message"?void 0:{handled:!0,displayText:uu(r.payload.text)},messageAndClick:(r,e)=>{var o;if(r.type!=="message_and_click")return;let t=r.payload,n=uu(t.element);if(n&&((o=e.document)!=null&&o.querySelector)){let a=e.document.querySelector(n);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:uu(t.text)}}},rb=r=>Array.isArray(r)?r.map(e=>String(e)):[],ci=r=>{let e=new Set(rb(r.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(rb(r.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(e);r.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||e.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?r.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;e.add(a.message.id),n();let d={action:i,message:a.message};r.emit("action:detected",d);for(let l of r.handlers)if(l)try{let u=()=>{r.emit("action:resubmit",d)},m=l(i,{message:a.message,metadata:r.getSessionMetadata(),updateMetadata:r.updateSessionMetadata,document:r.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let p=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:p,resubmit:m.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var TC=r=>{if(!r)return null;try{return JSON.parse(r)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},MC=r=>r.map(e=>({...e,streaming:!1})),kC=r=>r.map(e=>({...e,status:"complete"})),Xl=(r="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?TC(t.getItem(r)):null},save:t=>{let n=e();if(n)try{let o={...t,messages:t.messages?MC(t.messages):void 0,artifacts:t.artifacts?kC(t.artifacts):void 0};n.setItem(r,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(r)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var rs=Li(zi(),1);function EC(r){if(!r||typeof r!="object"||!("component"in r))return!1;let e=r.component;return typeof e=="string"&&e.length>0}function LC(r,e){if(!EC(r))return null;let t=r.props&&typeof r.props=="object"&&r.props!==null?r.props:{};return{component:r.component,props:t,raw:e}}function Ql(){let r=null,e=0;return{getExtractedDirective:()=>r,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=e)return r;try{let o=(0,rs.parse)(t,rs.STR|rs.OBJ),a=LC(o,t);a&&(r=a)}catch{}return e=t.length,r},reset:()=>{r=null,e=0}}}function nb(r){return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"&&"props"in r&&typeof r.props=="object"}function Jl(r,e){let{config:t,message:n,onPropsUpdate:o}=e,a=wo.get(r.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${r.component}" not found in registry. Falling back to default rendering.`),null;let s={message:n,config:t,updateProps:i=>{o&&o(i)}};try{return a(r.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${r.component}":`,i),null}}function ob(){let r=Ql();return{processChunk:e=>r.processChunk(e),getDirective:()=>r.getExtractedDirective(),reset:()=>{r.reset()}}}function ab(r){if(typeof r.rawContent=="string"&&r.rawContent.length>0)return r.rawContent;if(typeof r.content=="string"){let e=r.content.trim();if(e.startsWith("{")||e.startsWith("["))return r.content}return null}function Yl(r){let e=ab(r);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Zl(r){let e=ab(r);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let n=t;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e}}}catch{}return null}var PC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ed(r){let{onSubmit:e,onDismiss:t,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=PC}=r,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,p=document.createElement("div");p.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=n,f.appendChild(b);let h=document.createElement("p");h.className="persona-feedback-subtitle",h.textContent=o,f.appendChild(h),p.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 T=[];for(let w=1;w<=5;w++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),E.title=l[w-1],E.dataset.rating=String(w),E.innerHTML=`
|
|
77
74
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
78
75
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
79
76
|
</svg>
|
|
80
|
-
`,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=`
|
|
77
|
+
`,E.addEventListener("click",()=>{m=w,T.forEach((H,I)=>{let L=I<w;H.classList.toggle("selected",L),H.setAttribute("aria-checked",I===w-1?"true":"false")})}),T.push(E),S.appendChild(E)}p.appendChild(S);let M=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),w.appendChild(M),p.appendChild(w)}let k=document.createElement("div");k.className="persona-feedback-actions";let x=document.createElement("button");x.type="button",x.className="persona-feedback-btn persona-feedback-btn-skip",x.textContent=i,x.addEventListener("click",()=>{t==null||t(),u.remove()});let C=document.createElement("button");return C.type="button",C.className="persona-feedback-btn persona-feedback-btn-submit",C.textContent=s,C.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}C.disabled=!0,C.textContent="Submitting...";try{let w=(M==null?void 0:M.value.trim())||void 0;await e(m,w),u.remove()}catch(w){C.disabled=!1,C.textContent=s,console.error("[CSAT Feedback] Failed to submit:",w)}}),k.appendChild(x),k.appendChild(C),p.appendChild(k),u.appendChild(p),u}function td(r){let{onSubmit:e,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=r,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 p=null,f=document.createElement("div");f.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=n,b.appendChild(h);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,b.appendChild(S),f.appendChild(b);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=u,M.appendChild(k),M.appendChild(x);let C=document.createElement("div");C.className="persona-feedback-numbers";let w=[];for(let O=0;O<=10;O++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${O} out of 10`),$.textContent=String(O),$.dataset.rating=String(O),O<=6?$.classList.add("persona-feedback-detractor"):O<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{p=O,w.forEach((te,xe)=>{te.classList.toggle("selected",xe===O),te.setAttribute("aria-checked",xe===O?"true":"false")})}),w.push($),C.appendChild($)}T.appendChild(M),T.appendChild(C),f.appendChild(T);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=a,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),f.appendChild(O)}let H=document.createElement("div");H.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{t==null||t(),m.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=s,L.addEventListener("click",async()=>{if(p===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await e(p,O),m.remove()}catch(O){L.disabled=!1,L.textContent=s,console.error("[NPS Feedback] Failed to submit:",O)}}),H.appendChild(I),H.appendChild(L),f.appendChild(H),m.appendChild(f),m}var ns="persona-chat-history",RC=30*1e3,IC={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function HC(r){var n,o,a;if(!r)return[];let e=[],t=Array.from((n=r.items)!=null?n:[]);for(let s of t){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=IC[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let s of Array.from((a=r.files)!=null?a:[]))s.type.startsWith("image/")&&e.push(s);return e}function rd(r){if(!r)return!1;let e=r.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function WC(r){var e,t,n,o,a,s,i,d,l;return r?r===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=r.storage)!=null?e:"session",keyPrefix:(t=r.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(n=r.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(s=(a=r.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=r.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=r.clearOnChatClear)!=null?l:!0}:null}function BC(r){try{let e=r==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var fu=r=>!r||typeof r!="object"?{}:{...r},sb=r=>r.map(e=>({...e,streaming:!1})),ib=(r,e,t)=>{let n=r!=null&&r.markdown?ia(r.markdown):null,o=Na(r==null?void 0:r.sanitize);return r!=null&&r.postprocessMessage&&o&&(r==null?void 0:r.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var l,u,m;let s=(l=a.text)!=null?l:"",i=(u=a.message.rawContent)!=null?u:null;if(e){let p=e.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&t&&t())}let d;return r!=null&&r.postprocessMessage?d=r.postprocessMessage({...a,text:s,raw:(m=i!=null?i:a.text)!=null?m:""}):n?d=n(s):d=la(s),o?o(d):d}};function lb(r){var i,d,l,u;let e=v("div","persona-attachment-drop-overlay");r!=null&&r.background&&e.style.setProperty("--persona-drop-overlay-bg",r.background),(r==null?void 0:r.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",r.backdropBlur),r!=null&&r.border&&e.style.setProperty("--persona-drop-overlay-border",r.border),r!=null&&r.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",r.borderRadius),r!=null&&r.inset&&e.style.setProperty("--persona-drop-overlay-inset",r.inset),r!=null&&r.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",r.labelSize),r!=null&&r.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",r.labelColor);let t=(i=r==null?void 0:r.iconName)!=null?i:"upload",n=(d=r==null?void 0:r.iconSize)!=null?d:"48px",o=(l=r==null?void 0:r.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(u=r==null?void 0:r.iconStrokeWidth)!=null?u:.5,s=Me(t,n,o,a);if(s&&e.appendChild(s),r!=null&&r.label){let m=v("span","persona-drop-overlay-label");m.textContent=r.label,e.appendChild(m)}return e}var nd=(r,e,t)=>{var Vu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,bf,yf,vf,Cf,wf,Af,Sf,Tf,Mf,kf,Ef,Lf,Pf,Rf,If,Hf,Wf,Bf,Df,Ff,Of,Nf,_f,Uf;if(r==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');r.id&&!r.getAttribute("data-persona-instance")&&r.setAttribute("data-persona-instance",r.id),r.hasAttribute("data-persona-root")||r.setAttribute("data-persona-root","true");let n=wl(e),o=li.getForInstance(n.plugins);n.components&&wo.registerAll(n.components);let a=tb(),i=n.persistState===!1?null:(Vu=n.storageAdapter)!=null?Vu:Xl(),d={},l=null,u=!1,m=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:A}=g;return A&&(u=!0),y}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 y=g!=null?g:{messages:[],metadata:{}};return m(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=m(g);y.metadata&&(d=fu(y.metadata)),(ju=y.messages)!=null&&ju.length&&(n={...n,initialMessages:y.messages}),(Gu=y.artifacts)!=null&&Gu.length&&(n={...n,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Ku=y.selectedArtifactId)!=null?Ku: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:{}});(Xu=c.messages)!=null&&Xu.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let p=()=>d,f=c=>{var y;d=(y=c({...d}))!=null?y:{},La()},b=n.actionParsers&&n.actionParsers.length?n.actionParsers:[di],h=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[wa.message,wa.messageAndClick],S=ci({parsers:b,handlers:h,getSessionMetadata:p,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let T=(Ju=(Qu=n.launcher)==null?void 0:Qu.enabled)!=null?Ju:!0,M=(Zu=(Yu=n.launcher)==null?void 0:Yu.autoExpand)!=null?Zu:!1,k=(ef=n.autoFocusInput)!=null?ef:!1,x=M,C=T,w=(rf=(tf=n.layout)==null?void 0:tf.header)==null?void 0:rf.layout,E=!1,H=()=>zo(n),I=()=>T||H(),L=H()?!1:T?M:!0,O=!1,$=null,te=()=>{O=!0,$&&clearTimeout($),$=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},xe=ib(n,S,te),Je=(of=(nf=n.features)==null?void 0:nf.showReasoning)!=null?of:!0,we=(sf=(af=n.features)==null?void 0:af.showToolCalls)!=null?sf:!0,De=(df=(lf=n.features)==null?void 0:lf.showEventStreamToggle)!=null?df:!1,Ae=(pf=(cf=n.features)==null?void 0:cf.scrollToBottom)!=null?pf:{},qe=(ff=(uf=n.features)==null?void 0:uf.scrollBehavior)!=null?ff:{},J=`${(gf=typeof n.persistState=="object"?(mf=n.persistState)==null?void 0:mf.keyPrefix:void 0)!=null?gf:"persona-"}event-stream`,re=De?new si(J):null,Q=(bf=(xf=(hf=n.features)==null?void 0:hf.eventStream)==null?void 0:xf.maxEvents)!=null?bf:2e3,ge=De?new ai(Q,re):null,Z=De?new ii:null,G=null,pe=!1,ke=null,le=0;re==null||re.open().then(()=>ge==null?void 0:ge.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ne={onCopy:c=>{var g,y;a.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;a.emit("message:feedback",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.messageId,c.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},de=(yf=n.statusIndicator)!=null?yf:{},Et=c=>{var g,y,A,W;return c==="idle"?(g=de.idleText)!=null?g:Kr.idle:c==="connecting"?(y=de.connectingText)!=null?y:Kr.connecting:c==="connected"?(A=de.connectedText)!=null?A:Kr.connected:c==="error"?(W=de.errorText)!=null?W:Kr.error:Kr[c]};function wt(c,g,y,A){if(A==="idle"&&y.idleLink){c.textContent="";let W=document.createElement("a");W.href=y.idleLink,W.target="_blank",W.rel="noopener noreferrer",W.textContent=g,W.style.color="inherit",W.style.textDecoration="none",c.appendChild(W)}else c.textContent=g}let{wrapper:We,panel:he,pillRoot:at}=Px(n),Re=Rx(n,I()),{container:j,body:ue,messagesWrapper:nt,suggestions:Rt,textarea:ee,sendButton:Ge,sendButtonWrapper:Fr,composerForm:Bt,statusText:or,introTitle:hr,introSubtitle:sn,closeButton:F,iconHolder:fe,headerTitle:Ie,headerSubtitle:Xe,header:Fe,footer:Ne,actionsRow:Ye,leftActions:At,rightActions:Xt}=Re,ar=Re.setSendButtonMode,K=Re.micButton,mt=Re.micButtonWrapper,it=Re.attachmentButton,ye=Re.attachmentButtonWrapper,ie=Re.attachmentInput,st=Re.attachmentPreviewsContainer;j.classList.add("persona-relative"),ue.classList.add("persona-relative");let pr=12,pt=()=>{var c;return(c=Ae.label)!=null?c:""},yr=()=>{var c;return(c=Ae.iconName)!=null?c:"arrow-down"},Rr=()=>Ae.enabled!==!1,ut=()=>{var c;return(c=qe.mode)!=null?c:"follow"},Lt=()=>{var c;return(c=qe.anchorTopOffset)!=null?c:16},tt=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");tt.type="button",tt.style.display="none",tt.setAttribute("data-persona-scroll-to-bottom","true");let zt=v("span","persona-flex persona-items-center"),vr=v("span",""),sr=v("span","");sr.setAttribute("data-persona-scroll-to-bottom-count",""),sr.style.display="none",tt.append(zt,vr,sr),j.appendChild(tt);let ur=v("div","persona-stream-anchor-spacer");ur.setAttribute("aria-hidden","true"),ur.setAttribute("data-persona-anchor-spacer",""),ur.style.flexShrink="0",ur.style.pointerEvents="none",ur.style.height="0px",ue.appendChild(ur);let Mr=()=>{let g=Ne.style.display==="none"?0:Ne.offsetHeight;tt.style.bottom=`${g+pr}px`};Mr();let un=()=>{let c=!!pt();tt.setAttribute("aria-label",pt()||"Jump to latest"),tt.title=pt(),tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),zt.innerHTML="";let g=Me(yr(),"14px","currentColor",2);g?(zt.appendChild(g),zt.style.display=""):zt.style.display="none",vr.textContent=pt(),vr.style.display=c?"":"none"};un();let St=null,qr=null,xr=o.find(c=>c.renderHeader);if(xr!=null&&xr.renderHeader){let c=xr.renderHeader({config:n,defaultRenderer:()=>{let g=Co({config:n,showClose:I()});return ya(j,g,n),g.header},onClose:()=>jt(!1,"user")});if(c){let g=j.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Fe=c)}}let Mn=()=>{var g,y,A,W;if(!ge)return;if(pe=!0,!G&&ge&&(G=Vx({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>ln(),config:n,plugins:o,getThroughput:()=>{var _;return(_=Z==null?void 0:Z.getMetric())!=null?_:{status:"idle"}}})),G&&(ue.style.display="none",(g=Ne.parentNode)==null||g.insertBefore(G.element,Ne),G.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${an.actionIconColor}`;let _=(W=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:W.toggleButtonActive;_&&_.split(/\s+/).forEach(U=>U&&yt.classList.add(U))}let c=()=>{if(!pe)return;let _=Date.now();_-le>=200&&(G==null||G.update(),le=_),ke=requestAnimationFrame(c)};le=0,ke=requestAnimationFrame(c),cn(),a.emit("eventStream:opened",{timestamp:Date.now()})},ln=()=>{var c,g,y;if(pe){if(pe=!1,G&&G.element.remove(),ue.style.display="",yt){yt.style.boxShadow="";let A=(y=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(W=>W&&yt.classList.remove(W))}ke!==null&&(cancelAnimationFrame(ke),ke=null),cn(),a.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(De){let c=(Cf=(vf=n.features)==null?void 0:vf.eventStream)==null?void 0:Cf.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:"");yt=v("button",g),yt.style.width="28px",yt.style.height="28px",yt.style.color=an.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let y=Me("activity","18px","currentColor",1.5);y&&yt.appendChild(y);let A=Re.clearChatButtonWrapper,W=Re.closeButtonWrapper,_=A||W;_&&_.parentNode===Fe?Fe.insertBefore(yt,_):Fe.appendChild(yt),yt.addEventListener("click",()=>{pe?ln():Mn()})}let Gn=c=>{var A,W,_;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(y,U):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=v("input");U.type="file",U.accept=((A=g.allowedTypes)!=null?A:yo).join(","),U.multiple=((W=g.maxFiles)!=null?W:4)>1,U.style.display="none",U.setAttribute("aria-label",(_=g.buttonTooltipText)!=null?_:"Attach files"),c.appendChild(U)}},kn=o.find(c=>c.renderComposer);if(kn!=null&&kn.renderComposer){let c=n.composer,g=kn.renderComposer({config:n,defaultRenderer:()=>Ja({config:n}).footer,onSubmit:y=>{var U;if(!q||q.isStreaming())return;let A=y.trim(),W=(U=St==null?void 0:St.hasAttachments())!=null?U:!1;if(!A&&!W)return;z();let _;W&&(_=[],_.push(...St.getContentParts()),A&&_.push($s(A))),q.sendMessage(A,{contentParts:_}),W&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ie==null||ie.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((wf=n.voiceRecognition)==null?void 0:wf.enabled)===!0?()=>{qr==null||qr()}:void 0});g&&(Ne.replaceWith(g),Ne=g)}let _e=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),W=c.querySelector("[data-persona-composer-mic]"),_=c.querySelector("[data-persona-composer-status]");g&&(Bt=g),y&&(ee=y),A&&(Ge=A),W&&(K=W,mt=W.parentElement),_&&(or=_);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Rt=U);let V=c.querySelector(".persona-attachment-button");V&&(it=V,ye=V.parentElement),ie=c.querySelector('input[type="file"]'),st=c.querySelector(".persona-attachment-previews");let N=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(Ye=N)};Gn(Ne),_e(Ne);let R=(kf=(Af=n.layout)==null?void 0:Af.contentMaxWidth)!=null?kf:H()?(Mf=(Tf=(Sf=n.launcher)==null?void 0:Sf.composerBar)==null?void 0:Tf.contentMaxWidth)!=null?Mf:"720px":void 0;if(R&&(nt.style.maxWidth=R,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),R&&Bt&&!H()&&(Bt.style.maxWidth=R,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),R&&Rt&&!H()&&(Rt.style.maxWidth=R,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),R&&st&&!H()&&(st.style.maxWidth=R,st.style.marginLeft="auto",st.style.marginRight="auto"),(Ef=n.attachments)!=null&&Ef.enabled&&ie&&st){St=ha.fromConfig(n.attachments),St.setPreviewsContainer(st),ie.addEventListener("change",y=>{let A=y.target;St==null||St.handleFileSelect(A.files),A.value=""});let c=n.attachments.dropOverlay,g=lb(c);j.appendChild(g)}(()=>{var A,W;let c=(W=(A=n.layout)==null?void 0:A.slots)!=null?W:{},g=_=>{switch(_){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Rt;case"composer":return Bt;case"footer-bottom":return or;default:return null}},y=(_,U)=>{var V;switch(_){case"header-left":case"header-center":case"header-right":if(_==="header-left")Fe.insertBefore(U,Fe.firstChild);else if(_==="header-right")Fe.appendChild(U);else{let N=Fe.querySelector(".persona-flex-col");N?(V=N.parentNode)==null||V.insertBefore(U,N.nextSibling):Fe.appendChild(U)}break;case"body-top":{let N=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(U):ue.insertBefore(U,ue.firstChild);break}case"body-bottom":ue.appendChild(U);break;case"footer-top":Rt.replaceWith(U);break;case"footer-bottom":or.replaceWith(U);break;default:break}};for(let[_,U]of Object.entries(c))if(U)try{let V=U({config:n,defaultContent:()=>g(_)});V&&y(_,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${_}":`,V)}})();let Ee=c=>{var U,V;let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!A)return;let W=A.getAttribute("data-message-id");if(!W)return;let _=y.getAttribute("data-bubble-type");if(_==="reasoning")Za.has(W)?Za.delete(W):Za.add(W),Bx(W,A);else if(_==="tool")es.has(W)?es.delete(W):es.add(W),Dx(W,A,n);else if(_==="approval"){let N=n.approval!==!1?n.approval:void 0,Ce=((U=N==null?void 0:N.detailsDisplay)!=null?U:"collapsed")==="expanded",me=(V=$l.get(W))!=null?V:Ce;$l.set(W,!me),_x(W,A,n)}so.delete(W)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Ee(c))}),nt.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Ee(c))});let Ot=new Map;nt.addEventListener("click",c=>{var U;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let W=A.getAttribute("data-actions-for");if(!W)return;let _=y.getAttribute("data-action");if(_==="copy"){let N=q.getMessages().find(Ce=>Ce.id===W);if(N&&ne.onCopy){let Ce=N.content||"";navigator.clipboard.writeText(Ce).then(()=>{y.classList.add("persona-message-action-success");let me=Me("check",14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ae=Me("copy",14,"currentColor",2);ae&&(y.innerHTML="",y.appendChild(ae))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ne.onCopy(N)}}else if(_==="upvote"||_==="downvote"){let N=((U=Ot.get(W))!=null?U:null)===_,Ce=_==="upvote"?"thumbs-up":"thumbs-down";if(N){Ot.delete(W),y.classList.remove("persona-message-action-active");let me=Me(Ce,14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me))}else{let me=_==="upvote"?"downvote":"upvote",ae=A.querySelector(`[data-action="${me}"]`);if(ae){ae.classList.remove("persona-message-action-active");let Qe=Me(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(ae.innerHTML="",ae.appendChild(Qe))}Ot.set(W,_),y.classList.add("persona-message-action-active");let Te=Me(Ce,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(Te)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Se=q.getMessages().find(ct=>ct.id===W);Se&&ne.onFeedback&&ne.onFeedback({type:_,messageId:Se.id,message:Se})}}}),nt.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let W=A.getAttribute("data-message-id");if(!W)return;let _=y.getAttribute("data-approval-action");if(!_)return;let U=_==="approve"?"approved":"denied",N=q.getMessages().find(me=>me.id===W);if(!(N!=null&&N.approval))return;let Ce=A.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?q.resolveWebMcpApproval(W,U):q.resolveApproval(N.approval,U)});let et=null,Nt=null,Yt={artifacts:[],selectedId:null},lr=!1,vt={current:null};nt.addEventListener("click",c=>{var ae,Te,Ve,Se,ct;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Ve=(Te=(ae=n.features)==null?void 0:ae.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:Ve.call(Te,{type:"download",artifactId:A}))===!0)return;let _=q.getArtifactById(A),U=_==null?void 0:_.markdown,V=(_==null?void 0:_.title)||"artifact";if(!U){let Qe=y.closest("[data-open-artifact]"),ht=Qe==null?void 0:Qe.closest("[data-message-id]"),xt=ht==null?void 0:ht.getAttribute("data-message-id");if(xt){let Pe=q.getMessages().find(Ke=>Ke.id===xt);if(Pe!=null&&Pe.rawContent)try{let Ke=JSON.parse(Pe.rawContent);U=(Se=Ke==null?void 0:Ke.props)==null?void 0:Se.markdown,V=((ct=Ke==null?void 0:Ke.props)==null?void 0:ct.title)||V}catch{}}}if(!U)return;let N=new Blob([U],{type:"text/markdown"}),Ce=URL.createObjectURL(N),me=document.createElement("a");me.href=Ce,me.download=`${V}.md`,me.click(),URL.revokeObjectURL(Ce)}),nt.addEventListener("click",c=>{var _,U,V;let y=c.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((V=(U=(_=n.features)==null?void 0:_.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:V.call(U,{type:"open",artifactId:A}))===!0||(c.preventDefault(),c.stopPropagation(),lr=!1,q.selectArtifact(A),mn())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let zr=Re.composerOverlay,$t=(c,g,y)=>{var V,N,Ce,me;let A=g.trim();if(!A||!vt.current)return;let W=(V=c.getAttribute("data-tool-call-id"))!=null?V:"",_=y.source==="free-text";r.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:W,answer:A,answers:y.structured,values:(N=y.values)!=null?N:y.source==="multi"?A.split(", "):[A],isFreeText:_,source:y.source},bubbles:!0,composed:!0})),Oo(zr,W);let U=vt.current.getMessages().find(ae=>{var Te;return((Te=ae.toolCall)==null?void 0:Te.id)===W});(Ce=U==null?void 0:U.agentMetadata)!=null&&Ce.awaitingLocalTool?vt.current.resolveAskUserQuestion(U,(me=y.structured)!=null?me:A):vt.current.sendMessage(A)},$r=c=>{var W;let g=vt.current;if(!g)return;let y=(W=c.getAttribute("data-tool-call-id"))!=null?W:"",A=g.getMessages().find(_=>{var U;return((U=_.toolCall)==null?void 0:U.id)===y});A&&g.persistAskUserQuestionProgress(A,{answers:Vi(c,A),currentIndex:Wn(c)})},Dn=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),oo=c=>{var W,_,U;if(((_=(W=n.features)==null?void 0:W.askUserQuestion)==null?void 0:_.groupedAutoAdvance)===!1)return;let g=Wn(c),y=qa(c);if(g>=y-1)return;let A=(U=vt.current)==null?void 0:U.getMessages().find(V=>{var N;return((N=V.toolCall)==null?void 0:N.id)===c.getAttribute("data-tool-call-id")});A&&(ji(c,A,n,g+1),$r(c))};zr.addEventListener("click",c=>{var _,U,V,N,Ce,me,ae,Te,Ve,Se,ct,Qe,ht,xt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let A=y.closest("[data-persona-ask-sheet-for]");if(!A)return;let W=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),W==="dismiss"){let Be=(_=A.getAttribute("data-tool-call-id"))!=null?_:"";r.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Oo(zr,Be);let Pe=(U=vt.current)==null?void 0:U.getMessages().find(Ke=>{var rt;return((rt=Ke.toolCall)==null?void 0:rt.id)===Be});(V=Pe==null?void 0:Pe.agentMetadata)!=null&&V.awaitingLocalTool&&((N=vt.current)==null||N.markAskUserQuestionResolved(Pe),(Ce=vt.current)==null||Ce.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(W==="pick"){let Be=y.getAttribute("data-option-label");if(!Be)return;let Pe=A.getAttribute("data-multi-select")==="true",Ke=Fo(A);if(Ke&&Pe){let rt=ca(A)[Wn(A)],It=new Set(Array.isArray(rt)?rt:[]);It.has(Be)?It.delete(Be):It.add(Be),No(A,Array.from(It)),$r(A);return}if(Ke){No(A,Be),$r(A),oo(A);return}if(Pe){let rt=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",rt?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!rt);let It=A.querySelector('[data-ask-user-action="submit-multi"]');It&&(It.disabled=Fd(A).length===0);return}$t(A,Be,{source:"pick",values:[Be]});return}if(W==="submit-multi"){let Be=Fd(A);if(Be.length===0)return;$t(A,Be.join(", "),{source:"multi",values:Be});return}if(W==="open-free-text"){let Be=A.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Pe=Be.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(W==="focus-free-text"){let Be=A.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(W==="submit-free-text"){let Be=A.querySelector('[data-ask-free-text-input="true"]'),Pe=(me=Be==null?void 0:Be.value)!=null?me:"";if(!Pe.trim())return;if(Fo(A)){No(A,Pe.trim()),$r(A),oo(A);return}$t(A,Pe,{source:"free-text"});return}if(W==="next"||W==="back"){if(!vt.current)return;let Be=(ae=A.getAttribute("data-tool-call-id"))!=null?ae:"",Pe=vt.current.getMessages().find(Oe=>{var Ue;return((Ue=Oe.toolCall)==null?void 0:Ue.id)===Be});if(!Pe)return;let Ke=A.querySelector('[data-ask-free-text-input="true"]'),rt=(Ve=(Te=Ke==null?void 0:Ke.value)==null?void 0:Te.trim())!=null?Ve:"";if(rt){let Oe=ca(A)[Wn(A)];(typeof Oe!="string"||Oe!==rt)&&No(A,rt)}let It=W==="next"?1:-1,D=Wn(A)+It;ji(A,Pe,n,D),$r(A);return}if(W==="submit-all"){if(!vt.current)return;let Be=(Se=A.getAttribute("data-tool-call-id"))!=null?Se:"",Pe=vt.current.getMessages().find(Oe=>{var Ue;return((Ue=Oe.toolCall)==null?void 0:Ue.id)===Be});if(!Pe)return;let Ke=A.querySelector('[data-ask-free-text-input="true"]'),rt=(Qe=(ct=Ke==null?void 0:Ke.value)==null?void 0:ct.trim())!=null?Qe:"";rt&&No(A,rt);let It=Vi(A,Pe);vt.current.persistAskUserQuestionProgress(Pe,{answers:It,currentIndex:Wn(A)});let D=Dn(It);$t(A,D||"(submitted)",{source:"submit-all",structured:It});return}if(W==="skip"){if(!vt.current)return;let Be=(ht=A.getAttribute("data-tool-call-id"))!=null?ht:"",Pe=vt.current.getMessages().find(Ue=>{var be;return((be=Ue.toolCall)==null?void 0:be.id)===Be});if(!Pe)return;let Ke=Fo(A),rt=Wn(A),It=qa(A),D=rt>=It-1;if(!Ke){r.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Oo(zr,Be),(xt=Pe.agentMetadata)!=null&&xt.awaitingLocalTool&&(vt.current.markAskUserQuestionResolved(Pe),vt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}No(A,"");let Oe=A.querySelector('[data-ask-free-text-input="true"]');if(Oe&&(Oe.value=""),D){let Ue=Vi(A,Pe),be=Dn(Ue);$t(A,be||"(skipped)",{source:"submit-all",structured:Ue});return}ji(A,Pe,n,rt+1),$r(A);return}}),zr.addEventListener("keydown",c=>{var _;if(c.key!=="Enter")return;let y=c.target;if(!((_=y.matches)!=null&&_.call(y,'[data-ask-free-text-input="true"]')))return;let A=y.closest("[data-persona-ask-sheet-for]");if(!A)return;c.preventDefault();let W=y.value;if(W.trim()){if(Fo(A)){No(A,W.trim()),$r(A),oo(A);return}$t(A,W,{source:"free-text"})}});let Ao=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 y=zr.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let A=Number(c.key),_=y.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",Ao);let fn=null,Vt=null,Qr=null,En=null,So=()=>{};function ao(){En==null||En(),En=null}let To=()=>{var U;if(!fn||!Vt)return;let c=r.classList.contains("persona-artifact-appearance-seamless"),y=((U=r.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||r.classList.contains("persona-artifact-narrow-host")||y){Vt.style.removeProperty("position"),Vt.style.removeProperty("left"),Vt.style.removeProperty("top"),Vt.style.removeProperty("bottom"),Vt.style.removeProperty("width"),Vt.style.removeProperty("z-index");return}let A=fn.firstElementChild;if(!A||A===Vt)return;let W=10;Vt.style.position="absolute",Vt.style.top="0",Vt.style.bottom="0",Vt.style.width=`${W}px`,Vt.style.zIndex="5";let _=A.offsetWidth-W/2;Vt.style.left=`${Math.max(0,_)}px`},Kn=()=>{},mn=()=>{var y,A,W,_,U;if(!et||!Bn(n))return;Gl(r,n),Kl(r,n),Kn();let c=(_=(W=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:W.narrowHostMaxWidth)!=null?_:520,g=he.getBoundingClientRect().width||0;r.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),et.update(Yt),lr?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),(U=et.backdrop)==null||U.classList.add("persona-hidden")):Yt.artifacts.length>0&&(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)),So()};if(Bn(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(j),et=Kx(n,{onSelect:y=>{var A;return(A=vt.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{lr=!0,mn()}}),et.element.classList.add("persona-hidden"),fn=g,g.appendChild(c),g.appendChild(et.element),et.backdrop&&he.appendChild(et.backdrop),he.appendChild(g),So=()=>{var A,W,_,U;if(!fn||!et)return;if(!(((_=(W=(A=n.features)==null?void 0:A.artifacts)==null?void 0:W.layout)==null?void 0:_.resizable)===!0)){Qr==null||Qr(),Qr=null,ao(),Vt&&(Vt.remove(),Vt=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!Vt){let V=v("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 N=r.ownerDocument,Ce=(U=N.defaultView)!=null?U:window,me=ae=>{var ht,xt;if(!et||ae.button!==0||r.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;ae.preventDefault(),ao();let Te=ae.clientX,Ve=et.element.getBoundingClientRect().width,Se=(xt=(ht=n.features)==null?void 0:ht.artifacts)==null?void 0:xt.layout,ct=Be=>{let Pe=fn.getBoundingClientRect().width,Ke=r.classList.contains("persona-artifact-appearance-seamless"),rt=Ke?0:Yx(fn,Ce),It=Ke?0:V.getBoundingClientRect().width||6,D=Ve-(Be.clientX-Te),Oe=Zx(D,Pe,rt,It,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);et.element.style.width=`${Oe}px`,et.element.style.maxWidth="none",To()},Qe=()=>{N.removeEventListener("pointermove",ct),N.removeEventListener("pointerup",Qe),N.removeEventListener("pointercancel",Qe),En=null;try{V.releasePointerCapture(ae.pointerId)}catch{}};En=Qe,N.addEventListener("pointermove",ct),N.addEventListener("pointerup",Qe),N.addEventListener("pointercancel",Qe);try{V.setPointerCapture(ae.pointerId)}catch{}};V.addEventListener("pointerdown",me),Vt=V,fn.insertBefore(V,et.element),Qr=()=>{V.removeEventListener("pointerdown",me)}}if(Vt){let V=Yt.artifacts.length>0&&!lr;Vt.classList.toggle("persona-hidden",!V),To()}},Kn=()=>{var Ce,me,ae,Te,Ve,Se,ct,Qe,ht,xt,Be,Pe,Ke,rt;if(!T||!et||((me=(Ce=n.launcher)==null?void 0:Ce.sidebarMode)!=null?me:!1)||Pr(n)&&Sn(n).reveal==="emerge")return;let A=(ae=r.ownerDocument.defaultView)!=null?ae:window,W=(Ve=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?Ve:!0,_=(ct=(Se=n.launcher)==null?void 0:Se.mobileBreakpoint)!=null?ct:640;if(W&&A.innerWidth<=_||!Jx(n,T))return;let U=(xt=(ht=(Qe=n.launcher)==null?void 0:Qe.width)!=null?ht:n.launcherWidth)!=null?xt:An,V=(rt=(Ke=(Pe=(Be=n.features)==null?void 0:Be.artifacts)==null?void 0:Pe.layout)==null?void 0:Ke.expandedPanelWidth)!=null?rt:"min(720px, calc(100vw - 24px))";Yt.artifacts.length>0&&!lr?(he.style.width=V,he.style.maxWidth=V):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Nt=new ResizeObserver(()=>{mn()}),Nt.observe(he))}else he.appendChild(j),H()&&at&&(Re.peekBanner&&at.appendChild(Re.peekBanner),at.appendChild(Ne));r.appendChild(We),at&&r.appendChild(at);let Fn=()=>{var Oe,Ue,be,Qt,Gt,dr,Wt,ir,bn,kr,ot,_t,Lr,In,yn,Qo,Jo,Ba,Da,mr,Yo,Wo,Bo,uo,Zo,qn,dt,Hr;if(H()){he.style.width="100%",he.style.maxWidth="100%";let er=(Ue=(Oe=n.launcher)==null?void 0:Oe.composerBar)!=null?Ue:{},Jt=We.dataset.state==="expanded",kt=(be=er.expandedSize)!=null?be:"anchored";if(!(Jt&&kt!=="fullscreen")){j.style.background="",j.style.border="",j.style.borderRadius="",j.style.overflow="",j.style.boxShadow="";return}let Ft=(Gt=(Qt=n.theme)==null?void 0:Qt.components)==null?void 0:Gt.panel,jr=Xa(n),Jr=(Zr,ea)=>{var Cs;return Zr==null||Zr===""?ea:(Cs=Ga(jr,Zr))!=null?Cs:Zr},eo="1px solid var(--persona-border)",Nr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Yr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";j.style.background="var(--persona-surface, #ffffff)",j.style.border=Jr(Ft==null?void 0:Ft.border,eo),j.style.borderRadius=Jr(Ft==null?void 0:Ft.borderRadius,Yr),j.style.boxShadow=Jr(Ft==null?void 0:Ft.shadow,Nr),j.style.overflow="hidden";return}let c=Pr(n),g=(Wt=(dr=n.launcher)==null?void 0:dr.sidebarMode)!=null?Wt:!1,y=c||g||((bn=(ir=n.launcher)==null?void 0:ir.fullHeight)!=null?bn:!1),A=((kr=n.launcher)==null?void 0:kr.enabled)===!1,W=(_t=(ot=n.theme)==null?void 0:ot.components)==null?void 0:_t.panel,_=Xa(n),U=(er,Jt)=>{var kt;return er==null||er===""?Jt:(kt=Ga(_,er))!=null?kt:er},V=(Lr=r.ownerDocument.defaultView)!=null?Lr:window,N=(yn=(In=n.launcher)==null?void 0:In.mobileFullscreen)!=null?yn:!0,Ce=(Jo=(Qo=n.launcher)==null?void 0:Qo.mobileBreakpoint)!=null?Jo:640,me=V.innerWidth<=Ce,ae=N&&me&&T,Te=(Da=(Ba=n.launcher)==null?void 0:Ba.position)!=null?Da:"bottom-left",Ve=Te==="bottom-left"||Te==="top-left",Se=(Yo=(mr=n.launcher)==null?void 0:mr.zIndex)!=null?Yo:Xr,ct=g||ae?"none":"1px solid var(--persona-border)",Qe=ae?"none":g?Ve?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ae&&(Qe="none",ct="none");let ht=g||ae?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",xt=U(W==null?void 0:W.border,ct),Be=U(W==null?void 0:W.shadow,Qe),Pe=U(W==null?void 0:W.borderRadius,ht),Ke=ue.scrollTop;r.style.cssText="",We.style.cssText="",he.style.cssText="",j.style.cssText="",ue.style.cssText="",Ne.style.cssText="";let rt=()=>{var Jt;if(Ke<=0)return;((Jt=ue.ownerDocument.defaultView)!=null?Jt:window).requestAnimationFrame(()=>{if(ue.scrollTop===Ke)return;let kt=ue.scrollHeight-ue.clientHeight;kt<=0||(ue.scrollTop=Math.min(Ke,kt))})};if(ae){We.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),We.style.cssText=`
|
|
81
78
|
position: fixed !important;
|
|
82
79
|
inset: 0 !important;
|
|
83
80
|
width: 100% !important;
|
|
@@ -87,9 +84,9 @@ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
87
84
|
padding: 0 !important;
|
|
88
85
|
display: flex !important;
|
|
89
86
|
flex-direction: column !important;
|
|
90
|
-
z-index: ${
|
|
87
|
+
z-index: ${Se} !important;
|
|
91
88
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
92
|
-
`,
|
|
89
|
+
`,he.style.cssText=`
|
|
93
90
|
position: relative !important;
|
|
94
91
|
display: flex !important;
|
|
95
92
|
flex-direction: column !important;
|
|
@@ -102,7 +99,7 @@ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
102
99
|
padding: 0 !important;
|
|
103
100
|
box-shadow: none !important;
|
|
104
101
|
border-radius: 0 !important;
|
|
105
|
-
`,
|
|
102
|
+
`,j.style.cssText=`
|
|
106
103
|
display: flex !important;
|
|
107
104
|
flex-direction: column !important;
|
|
108
105
|
flex: 1 1 0% !important;
|
|
@@ -113,20 +110,20 @@ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
113
110
|
overflow: hidden !important;
|
|
114
111
|
border-radius: 0 !important;
|
|
115
112
|
border: none !important;
|
|
116
|
-
`,
|
|
113
|
+
`,ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Ne.style.flexShrink="0",E=!0,rt();return}let It=(Bo=(Wo=n==null?void 0:n.launcher)==null?void 0:Wo.width)!=null?Bo:n==null?void 0:n.launcherWidth,D=It!=null?It:An;if(!g&&!c)A&&y?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=D,he.style.maxWidth=D);else if(c)if(Sn(n).reveal==="emerge"){let Jt=Sn(n).width;he.style.width=Jt,he.style.maxWidth=Jt}else he.style.width="100%",he.style.maxWidth="100%";if(Kn(),he.style.boxShadow=Be,he.style.borderRadius=Pe,j.style.border=xt,j.style.borderRadius=Pe,c&&!ae&&(W==null?void 0:W.border)===void 0&&(j.style.border="none",Sn(n).side==="right"?j.style.borderLeft="1px solid var(--persona-border)":j.style.borderRight="1px solid var(--persona-border)"),y&&(r.style.display="flex",r.style.flexDirection="column",r.style.height="100%",r.style.minHeight="0",A&&(r.style.width="100%"),We.style.display="flex",We.style.flexDirection="column",We.style.flex="1 1 0%",We.style.minHeight="0",We.style.maxHeight="100%",We.style.height="100%",A&&(We.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Ne.style.flexShrink="0"),We.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!A&&!c&&((uo=jn[Te])!=null?uo:jn["bottom-right"]).split(" ").forEach(Jt=>We.classList.add(Jt)),g){let er=(qn=(Zo=n.launcher)==null?void 0:Zo.sidebarWidth)!=null?qn:"420px";We.style.cssText=`
|
|
117
114
|
position: fixed !important;
|
|
118
115
|
top: 0 !important;
|
|
119
116
|
bottom: 0 !important;
|
|
120
|
-
width: ${
|
|
117
|
+
width: ${er} !important;
|
|
121
118
|
height: 100vh !important;
|
|
122
119
|
max-height: 100vh !important;
|
|
123
120
|
margin: 0 !important;
|
|
124
121
|
padding: 0 !important;
|
|
125
122
|
display: flex !important;
|
|
126
123
|
flex-direction: column !important;
|
|
127
|
-
z-index: ${
|
|
128
|
-
${
|
|
129
|
-
`,
|
|
124
|
+
z-index: ${Se} !important;
|
|
125
|
+
${Ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
126
|
+
`,he.style.cssText=`
|
|
130
127
|
position: relative !important;
|
|
131
128
|
display: flex !important;
|
|
132
129
|
flex-direction: column !important;
|
|
@@ -137,9 +134,9 @@ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
137
134
|
min-height: 0 !important;
|
|
138
135
|
margin: 0 !important;
|
|
139
136
|
padding: 0 !important;
|
|
140
|
-
box-shadow: ${
|
|
141
|
-
border-radius: ${
|
|
142
|
-
`,
|
|
137
|
+
box-shadow: ${Be} !important;
|
|
138
|
+
border-radius: ${Pe} !important;
|
|
139
|
+
`,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),j.style.cssText=`
|
|
143
140
|
display: flex !important;
|
|
144
141
|
flex-direction: column !important;
|
|
145
142
|
flex: 1 1 0% !important;
|
|
@@ -148,29 +145,29 @@ _Details: ${r.message}_`:n}var Xs=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
148
145
|
min-height: 0 !important;
|
|
149
146
|
max-height: 100% !important;
|
|
150
147
|
overflow: hidden !important;
|
|
151
|
-
border-radius: ${
|
|
152
|
-
border: ${
|
|
153
|
-
`,
|
|
148
|
+
border-radius: ${Pe} !important;
|
|
149
|
+
border: ${xt} !important;
|
|
150
|
+
`,Ne.style.cssText=`
|
|
154
151
|
flex-shrink: 0 !important;
|
|
155
152
|
border-top: none !important;
|
|
156
153
|
padding: 8px 16px 12px 16px !important;
|
|
157
|
-
`}if(!A&&!c){let 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)&>){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:
|
|
159
|
-
`)}}];function
|
|
160
|
-
${
|
|
154
|
+
`}if(!A&&!c){let er="max-height: -moz-available !important; max-height: stretch !important;",Jt=g?"":"padding-top: 1.25em !important;",kt=g?"":`z-index: ${(Hr=(dt=n.launcher)==null?void 0:dt.zIndex)!=null?Hr:Xr} !important;`;We.style.cssText+=er+Jt+kt}rt()};Fn(),_o(r,n),Gl(r,n),Kl(r,n);let Tt=[];Tt.push(()=>{document.removeEventListener("keydown",Ao)});let Cr=null,wr=null;Tt.push(()=>{Cr==null||Cr(),Cr=null,wr==null||wr(),wr=null}),Nt&&Tt.push(()=>{Nt==null||Nt.disconnect(),Nt=null}),Tt.push(()=>{Qr==null||Qr(),Qr=null,ao(),Vt&&(Vt.remove(),Vt=null),et==null||et.element.style.removeProperty("width"),et==null||et.element.style.removeProperty("maxWidth")}),De&&Tt.push(()=>{ke!==null&&(cancelAnimationFrame(ke),ke=null),G==null||G.destroy(),G=null,ge==null||ge.destroy(),ge=null,re=null});let gn=null,Mo=()=>{gn&&(gn(),gn=null),n.colorScheme==="auto"&&(gn=Tl(()=>{_o(r,n)}))};Mo(),Tt.push(()=>{gn&&(gn(),gn=null)});let ve=(Lf=n.features)==null?void 0:Lf.streamAnimation;if(ve!=null&&ve.type&&ve.type!=="none"){let c=Ys(ve.type,ve.plugins);c&&(Xp(c,r),Tt.push(()=>Mx(r)))}let On=Ux(Rt),Ln=null,q,Sa=c=>{var A,W;if(!q)return;let g=c!=null?c:q.getMessages(),y=((W=(A=n.features)==null?void 0:A.suggestReplies)==null?void 0:W.enabled)!==!1?Ki(g):null;y?On.render(y,q,ee,g,n.suggestionChipsConfig,{agentPushed:!0}):g.some(_=>_.role==="user")?On.render([],q,ee,g):On.render(n.suggestionChips,q,ee,g,n.suggestionChipsConfig)},Xn=!1,so=xx(),io=new Map,Qn=new Map,Nn=new Map,as=0,hn=El(),xn=0,_n=null,Un=!1,Vo=!1,lo=0,Vr=null,Jn=null,Ta=!1,jo=!1,Ma=null,fi=4,ka=24,mi=80,Ea=new Map,Pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ss=(Rf=(Pf=n.voiceRecognition)==null?void 0:Pf.autoResume)!=null?Rf:!1,Pn=c=>{a.emit("voice:state",{active:Pt.active,source:c,timestamp:Date.now()})},dn=()=>{f(c=>({...c,voiceState:{active:Pt.active,timestamp:Date.now(),manuallyDeactivated:Pt.manuallyDeactivated}}))},gi=()=>{var A,W;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let c=fu(d.voiceState),g=!!c.active,y=Number((W=c.timestamp)!=null?W:0);Pt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<RC&&setTimeout(()=>{var _,U;Pt.active||(Pt.manuallyDeactivated=!1,((U=(_=n.voiceRecognition)==null?void 0:_.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{Pt.active=q.isVoiceActive(),Pn("restore"),q.isVoiceActive()&&bs()}):fr("restore"))},1e3)},hi=()=>q?sb(q.getMessages()).filter(c=>!c.__skipPersist):[];function La(c){if(!(i!=null&&i.save))return;let y={messages:c?sb(c):q?hi():[],metadata:d,artifacts:Yt.artifacts,selectedArtifactId:Yt.selectedId};try{let A=i.save(y);A instanceof Promise&&A.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let co=null,is=()=>We.querySelector("#persona-scroll-container")||ue,ko=()=>{co!==null&&(cancelAnimationFrame(co),co=null),Un=!1},ls=()=>{_n!==null&&(cancelAnimationFrame(_n),_n=null),Vo=!1,ko()},ds=()=>{lo>0?(sr.textContent=String(lo),sr.style.display="",tt.setAttribute("aria-label",`${pt()||"Jump to latest"} (${lo} new)`)):(sr.textContent="",sr.style.display="none",tt.setAttribute("aria-label",pt()||"Jump to latest"))},cs=()=>{lo!==0&&(lo=0,ds())},ps=()=>ut()==="follow"?!hn.isFollowing():!xa(ue,ka),cn=()=>{if(!Rr()||pe){tt.parentNode&&tt.remove(),tt.style.display="none";return}tt.parentNode!==j&&j.appendChild(tt),Mr();let g=vo(ue)>0&&ps();g||cs(),tt.style.display=g?"":"none"},Pa=()=>{hn.pause()&&(ls(),cn())},Yn=()=>{hn.resume(),cs(),cn()},Zn=(c=!1)=>{ut()==="follow"&&hn.isFollowing()&&(!c&&!Xn||(_n!==null&&(cancelAnimationFrame(_n),_n=null),Vo=!0,_n=requestAnimationFrame(()=>{_n=null,Vo=!1,hn.isFollowing()&&xi(is(),c?220:140)})))},us=(c,g,y,A=()=>!0)=>{let W=c.scrollTop,_=g(),U=_-W;ko();let V=performance.now();Un=!0;let N=me=>1-Math.pow(1-me,3),Ce=me=>{if(!A()){ko();return}let ae=g();ae!==_&&(_=ae,U=_-W);let Te=me-V,Ve=Math.min(Te/y,1),Se=N(Ve),ct=W+U*Se;c.scrollTop=ct,xn=c.scrollTop,Ve<1?co=requestAnimationFrame(Ce):(c.scrollTop=_,xn=c.scrollTop,co=null,Un=!1)};co=requestAnimationFrame(Ce)},xi=(c,g=500)=>{let y=vo(c)-c.scrollTop;if(Math.abs(y)<1){xn=c.scrollTop;return}if(Math.abs(y)>=mi){ko(),Un=!0,c.scrollTop=vo(c),xn=c.scrollTop,Un=!1;return}us(c,()=>vo(c),g,()=>hn.isFollowing())},fs=()=>{let c=is();Un=!0,c.scrollTop=vo(c),xn=c.scrollTop,Un=!1,cn()},ms=c=>{ur.style.height=`${Math.max(0,Math.round(c))}px`,Vr&&(Vr.spacerHeight=Math.max(0,c))},Go=()=>{Jn!==null&&(cancelAnimationFrame(Jn),Jn=null),ko(),Vr=null,ur.style.height="0px"},bi=c=>{Jn!==null&&cancelAnimationFrame(Jn),Jn=requestAnimationFrame(()=>{var Ce;Jn=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),y=ue.querySelector(`[data-message-id="${g}"]`);if(!y)return;let A=0,W=y;for(;W&&W!==ue;)A+=W.offsetTop,W=W.offsetParent;let _=(Ce=Vr==null?void 0:Vr.spacerHeight)!=null?Ce:0,U=ue.scrollHeight-_,{targetScrollTop:V,spacerHeight:N}=wx({anchorOffsetTop:A,topOffset:Lt(),viewportHeight:ue.clientHeight,contentHeight:U});Vr={initialSpacerHeight:N,contentHeightAtAnchor:U,spacerHeight:N},ms(N),us(ue,()=>V,220)})},yi=()=>{if(ut()==="follow"){if(!hn.isFollowing()||xa(ue,1))return;Zn(!Xn);return}if(Vr&&Vr.initialSpacerHeight>0){let c=ue.scrollHeight-Vr.spacerHeight,g=Ax({initialSpacerHeight:Vr.initialSpacerHeight,contentHeightAtAnchor:Vr.contentHeightAtAnchor,currentContentHeight:c});g!==Vr.spacerHeight&&ms(g)}cn()},vi=c=>{let g=ut();g==="follow"?(Yn(),Zn(!0)):g==="anchor-top"&&bi(c)},Ci=c=>{let g=new Map;c.forEach(y=>{let A=Ea.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&(a.emit("assistant:message",y),!jo&&ut()!=="anchor-top"&&ps()&&(lo+=1,ds(),cn())),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&a.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&a.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):a.emit("approval:requested",{approval:y.approval,message:y}))}),Ea.clear(),g.forEach((y,A)=>{Ea.set(A,y)})},Ko=(c,g,y)=>{var xt,Be,Pe,Ke,rt,It;let A=document.createElement("div"),_=(()=>{var Oe;let D=o.find(Ue=>Ue.renderLoadingIndicator);if(D!=null&&D.renderLoadingIndicator)return D.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),U=(D,Oe)=>Oe==null?!1:typeof Oe=="string"?(D.textContent=Oe,!0):(D.appendChild(Oe),!0),V=new Set,N=new Set,Ce=o.some(D=>D.renderAskUserQuestion),me=[],ae=[],Te=n.enableComponentStreaming!==!1,Ve=o.some(D=>D.renderApproval)&&n.approval!==!1,Se=[];if(g.forEach(D=>{var ot,_t,Lr,In,yn,Qo,Jo,Ba,Da,mr,Yo,Wo,Bo,uo,Zo,qn;V.add(D.id);let Oe=Ce&&ho(D),Ue=Ve&&D.variant==="approval"&&!!D.approval,be=!Oe&&D.role==="assistant"&&!D.variant&&Te&&Yl(D);if(!Ue&&Nn.has(D.id)){let dt=c.querySelector(`#wrapper-${D.id}`);dt==null||dt.removeAttribute("data-preserve-runtime"),Nn.delete(D.id)}if(!be&&Qn.has(D.id)){let dt=c.querySelector(`#wrapper-${D.id}`);dt==null||dt.removeAttribute("data-preserve-runtime"),Qn.delete(D.id)}let Qt=ho(D)?`:${(ot=D.agentMetadata)!=null&&ot.askUserQuestionAnswered?"a":"u"}:${(_t=D.agentMetadata)!=null&&_t.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Gt=hx(D,as)+Qt,dr=Oe||Ue||be?null:bx(so,D.id,Gt);if(dr){A.appendChild(dr.cloneNode(!0)),ho(D)&&((Lr=D.toolCall)!=null&&Lr.id)&&((In=D.agentMetadata)==null?void 0:In.awaitingLocalTool)===!0&&!((yn=D.agentMetadata)!=null&&yn.askUserQuestionAnswered)&&(N.add(D.toolCall.id),za(D,n,Re.composerOverlay));return}let Wt=null,ir=o.find(dt=>!!(D.variant==="reasoning"&&dt.renderReasoning||D.variant==="tool"&&dt.renderToolCall||!D.variant&&dt.renderMessage)),bn=(Qo=n.layout)==null?void 0:Qo.messages;if(ho(D)&&((Jo=D.agentMetadata)==null?void 0:Jo.askUserQuestionAnswered)===!0){io.delete(D.id);let dt=c.querySelector(`#wrapper-${D.id}`);dt==null||dt.removeAttribute("data-preserve-runtime");return}if(_s(D)&&((Da=(Ba=n.features)==null?void 0:Ba.suggestReplies)==null?void 0:Da.enabled)!==!1)return;if(ho(D)&&((Yo=(mr=n.features)==null?void 0:mr.askUserQuestion)==null?void 0:Yo.enabled)!==!1){let dt=o.find(Hr=>typeof Hr.renderAskUserQuestion=="function");if(dt&&vt.current){let Hr=io.get(D.id),er=Hr!==Gt,Jt=null;if(er){let{payload:Ft,complete:jr}=xo(D),Jr=D.id,eo=()=>{var Nr;return(Nr=vt.current)==null?void 0:Nr.getMessages().find(Yr=>Yr.id===Jr)};Jt=dt.renderAskUserQuestion({message:D,payload:Ft,complete:jr,resolve:Nr=>{var Zr;let Yr=eo();Yr&&((Zr=vt.current)==null||Zr.resolveAskUserQuestion(Yr,Nr))},dismiss:()=>{var Yr,Zr,ea;let Nr=eo();(Yr=Nr==null?void 0:Nr.agentMetadata)!=null&&Yr.awaitingLocalTool&&((Zr=vt.current)==null||Zr.markAskUserQuestionResolved(Nr),(ea=vt.current)==null||ea.resolveAskUserQuestion(Nr,"(dismissed)"))},config:n})}let kt=Hr!=null;if(er&&Jt===null&&!kt){((Wo=D.agentMetadata)==null?void 0:Wo.awaitingLocalTool)===!0&&!((Bo=D.agentMetadata)!=null&&Bo.askUserQuestionAnswered)&&(N.add(D.toolCall.id),za(D,n,Re.composerOverlay));return}let gr=document.createElement("div");gr.className="persona-flex",gr.id=`wrapper-${D.id}`,gr.setAttribute("data-wrapper-id",D.id),gr.setAttribute("data-ask-plugin-stub","true"),gr.setAttribute("data-preserve-runtime","true"),A.appendChild(gr),me.push({messageId:D.id,fingerprint:Gt,bubble:Jt});return}else{((uo=D.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((Zo=D.agentMetadata)!=null&&Zo.askUserQuestionAnswered)&&(N.add(D.toolCall.id),za(D,n,Re.composerOverlay));return}}else if(Ue){let dt=o.find(kt=>typeof kt.renderApproval=="function"),er=Nn.get(D.id)!==Gt,Jt=null;if(er&&(dt!=null&&dt.renderApproval)){let kt=D.id,gr=(Ft,jr)=>{var eo,Nr,Yr;let Jr=(eo=vt.current)==null?void 0:eo.getMessages().find(Zr=>Zr.id===kt);Jr!=null&&Jr.approval&&(Jr.approval.toolType==="webmcp"?(Nr=vt.current)==null||Nr.resolveWebMcpApproval(Jr.id,Ft):(Yr=vt.current)==null||Yr.resolveApproval(Jr.approval,Ft,jr))};Jt=dt.renderApproval({message:D,defaultRenderer:()=>Vl(D,n),config:n,approve:Ft=>gr("approved",Ft),deny:Ft=>gr("denied",Ft)})}if(er&&Jt===null){let kt=c.querySelector(`#wrapper-${D.id}`);kt==null||kt.removeAttribute("data-preserve-runtime"),Nn.delete(D.id),Wt=Vl(D,n)}else{let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${D.id}`,kt.setAttribute("data-wrapper-id",D.id),kt.setAttribute("data-approval-plugin-stub","true"),kt.setAttribute("data-preserve-runtime","true"),A.appendChild(kt),Se.push({messageId:D.id,fingerprint:Gt,bubble:Jt});return}}else if(ir)if(D.variant==="reasoning"&&D.reasoning&&ir.renderReasoning){if(!Je)return;Wt=ir.renderReasoning({message:D,defaultRenderer:()=>au(D,n),config:n})}else if(D.variant==="tool"&&D.toolCall&&ir.renderToolCall){if(!we)return;Wt=ir.renderToolCall({message:D,defaultRenderer:()=>su(D,n),config:n})}else ir.renderMessage&&(Wt=ir.renderMessage({message:D,defaultRenderer:()=>{let dt=Ya(D,y,bn,n.messageActions,ne,{loadingIndicatorRenderer:_,widgetConfig:n});return D.role!=="user"&&cu(dt,D,n,q),dt},config:n}));if(!Wt&&be){let dt=Zl(D);if(dt){let Hr=Qn.get(D.id),er=Hr!==Gt,Jt=n.wrapComponentDirectiveInBubble!==!1,kt=null;if(er){let gr=Jl(dt,{config:n,message:D,transform:y});if(gr)if(Jt){let Ft=document.createElement("div");if(Ft.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(" "),Ft.id=`bubble-${D.id}`,Ft.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let jr=document.createElement("div");jr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",jr.innerHTML=y({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ft.appendChild(jr)}Ft.appendChild(gr),kt=Ft}else{let Ft=document.createElement("div");if(Ft.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ft.id=`bubble-${D.id}`,Ft.setAttribute("data-message-id",D.id),Ft.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let jr=document.createElement("div");jr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",jr.innerHTML=y({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ft.appendChild(jr)}Ft.appendChild(gr),kt=Ft}}if(kt||Hr!=null){let gr=document.createElement("div");gr.className="persona-flex",gr.id=`wrapper-${D.id}`,gr.setAttribute("data-wrapper-id",D.id),gr.setAttribute("data-component-directive-stub","true"),gr.setAttribute("data-preserve-runtime","true"),Jt||gr.classList.add("persona-w-full"),A.appendChild(gr),ae.push({messageId:D.id,fingerprint:Gt,bubble:kt});return}}}if(!Wt)if(D.variant==="reasoning"&&D.reasoning){if(!Je)return;Wt=au(D,n)}else if(D.variant==="tool"&&D.toolCall){if(!we)return;Wt=su(D,n)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;Wt=Vl(D,n)}else{let dt=(qn=n.layout)==null?void 0:qn.messages;dt!=null&&dt.renderUserMessage&&D.role==="user"?Wt=dt.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):dt!=null&&dt.renderAssistantMessage&&D.role==="assistant"?Wt=dt.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):Wt=Ya(D,y,dt,n.messageActions,ne,{loadingIndicatorRenderer:_,widgetConfig:n}),D.role!=="user"&&Wt&&cu(Wt,D,n,q)}let kr=document.createElement("div");kr.className="persona-flex",kr.id=`wrapper-${D.id}`,kr.setAttribute("data-wrapper-id",D.id),D.role==="user"&&kr.classList.add("persona-justify-end"),(Wt==null?void 0:Wt.getAttribute("data-persona-component-directive"))==="true"&&kr.classList.add("persona-w-full"),kr.appendChild(Wt),yx(so,D.id,Gt,kr),A.appendChild(kr)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Ue=Oe.getAttribute("data-persona-ask-sheet-for");Ue&&!N.has(Ue)&&Oo(Re.composerOverlay,Ue)}),(Be=(xt=n.features)==null?void 0:xt.toolCallDisplay)!=null&&Be.grouped){let D=[],Oe=[];g.forEach(Ue=>{if(Ue.variant==="tool"&&Ue.toolCall&&we){Oe.push(Ue);return}Oe.length>1&&D.push(Oe),Oe=[]}),Oe.length>1&&D.push(Oe),D.forEach((Ue,be)=>{var ot,_t;let Qt=Ue.map(Lr=>Array.from(A.children).find(In=>In instanceof HTMLElement&&In.getAttribute("data-wrapper-id")===Lr.id)).filter(Lr=>!!Lr);if(Qt.length<2)return;let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id=`wrapper-tool-group-${be}-${Ue[0].id}`,Gt.setAttribute("data-wrapper-id",`tool-group-${be}-${Ue[0].id}`);let dr=document.createElement("div");dr.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",dr.setAttribute("data-persona-tool-group","true");let Wt=document.createElement("div");Wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ir=`Called ${Ue.length} tools`,bn=(_t=(ot=n.toolCall)==null?void 0:ot.renderGroupedSummary)==null?void 0:_t.call(ot,{messages:Ue,toolCalls:Ue.map(Lr=>Lr.toolCall).filter(Lr=>!!Lr),defaultSummary:ir,config:n});U(Wt,bn)||(Wt.textContent=ir);let kr=document.createElement("div");kr.className="persona-tool-group-stack persona-flex persona-flex-col",dr.append(Wt,kr),Gt.appendChild(dr),Qt[0].before(Gt),Qt.forEach((Lr,In)=>{let yn=document.createElement("div");yn.className="persona-tool-group-item persona-relative",yn.setAttribute("data-persona-tool-group-item","true"),In<Qt.length-1&&yn.setAttribute("data-persona-tool-group-connector","true"),yn.appendChild(Lr),kr.appendChild(yn)})})}vx(so,V);let ct=g.some(D=>D.role==="assistant"&&D.streaming),Qe=g[g.length-1],ht=(Qe==null?void 0:Qe.role)==="assistant"&&!Qe.streaming&&Qe.variant!=="approval";if(Xn&&g.some(D=>D.role==="user")&&!ct&&!ht){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:va},Oe=o.find(be=>be.renderLoadingIndicator),Ue=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Ue=Oe.renderLoadingIndicator(D)),Ue===null&&((Pe=n.loadingIndicator)!=null&&Pe.render)&&(Ue=n.loadingIndicator.render(D)),Ue===null&&(Ue=va()),Ue){let be=document.createElement("div"),Qt=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;be.className=Qt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),be.setAttribute("data-typing-indicator","true"),be.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",be.appendChild(Ue);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-typing-indicator",Gt.setAttribute("data-wrapper-id","typing-indicator"),Gt.appendChild(be),A.appendChild(Gt)}}if(!Xn&&g.length>0){let D=g[g.length-1],Oe={config:n,lastMessage:D,messageCount:g.length},Ue=o.find(Qt=>Qt.renderIdleIndicator),be=null;if(Ue!=null&&Ue.renderIdleIndicator&&(be=Ue.renderIdleIndicator(Oe)),be===null&&((rt=n.loadingIndicator)!=null&&rt.renderIdle)&&(be=n.loadingIndicator.renderIdle(Oe)),be){let Qt=document.createElement("div"),Gt=((It=n.loadingIndicator)==null?void 0:It.showBubble)!==!1;Qt.className=Gt?["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(" "),Qt.setAttribute("data-idle-indicator","true"),Qt.appendChild(be);let dr=document.createElement("div");dr.className="persona-flex",dr.id="wrapper-idle-indicator",dr.setAttribute("data-wrapper-id","idle-indicator"),dr.appendChild(Qt),A.appendChild(dr)}}if(Ml(c,A),me.length>0)for(let{messageId:D,fingerprint:Oe,bubble:Ue}of me){let be=c.querySelector(`#wrapper-${D}`);be&&Ue!==null&&(be.replaceChildren(Ue),be.setAttribute("data-bubble-fp",Oe),io.set(D,Oe))}if(io.size>0)for(let D of io.keys())V.has(D)||io.delete(D);if(ae.length>0)for(let{messageId:D,fingerprint:Oe,bubble:Ue}of ae){let be=c.querySelector(`#wrapper-${D}`);be&&Ue!==null&&(be.replaceChildren(Ue),be.setAttribute("data-bubble-fp",Oe),Qn.set(D,Oe))}if(Qn.size>0)for(let D of Qn.keys())V.has(D)||Qn.delete(D);if(Se.length>0)for(let{messageId:D,fingerprint:Oe,bubble:Ue}of Se){let be=c.querySelector(`#wrapper-${D}`);be&&Ue!==null&&(be.replaceChildren(Ue),be.setAttribute("data-bubble-fp",Oe),Nn.set(D,Oe))}if(Nn.size>0)for(let D of Nn.keys())V.has(D)||Nn.delete(D)},Eo=null,wi=()=>{var y;if(Eo)return;let c=A=>{let W=A.composedPath();W.includes(We)||at&&W.includes(at)||jt(!1,"user")};Eo=c,((y=r.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},gs=()=>{var g;if(!Eo)return;((g=r.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Eo,!0),Eo=null};Tt.push(()=>gs());let Lo=null,Ai=()=>{var y;if(Lo)return;let c=A=>{A.key==="Escape"&&(A.isComposing||jt(!1,"user"))};Lo=c,((y=r.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},hs=()=>{var g;if(!Lo)return;((g=r.ownerDocument)!=null?g:document).removeEventListener("keydown",Lo,!0),Lo=null};Tt.push(()=>hs());let Po=!1,xs=new Set,Si=()=>{var g,y,A,W;let c=(A=(y=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:A.streamAnimation;return c||((W=n.features)==null?void 0:W.streamAnimation)},po=()=>{var ht,xt,Be,Pe;if(!H())return;let c=Re.peekBanner,g=Re.peekTextNode;if(!c||!g)return;if(L){c.classList.remove("persona-pill-peek--visible");return}let y=(ht=q==null?void 0:q.getMessages())!=null?ht:[],A;for(let Ke=y.length-1;Ke>=0;Ke--){let rt=y[Ke];if(rt.role==="assistant"&&rt.content){A=rt;break}}if(!A){c.classList.remove("persona-pill-peek--visible");return}let W=A.content,_=!!A.streaming,U=Si(),V=Rl(U),N=V.type!=="none"?Ys(V.type,U==null?void 0:U.plugins):null,Ce=((xt=N==null?void 0:N.isAnimating)==null?void 0:xt.call(N,A))===!0,me=N!==null&&(_||Ce);me&&N&&!xs.has(N.name)&&(Xp(N,r),xs.add(N.name));let ae=me&&(N!=null&&N.containerClass)?N.containerClass:null,Te=(Be=g.dataset.personaPeekStreamClass)!=null?Be:null;Te&&Te!==ae&&(g.classList.remove(Te),delete g.dataset.personaPeekStreamClass),ae&&Te!==ae&&(g.classList.add(ae),g.dataset.personaPeekStreamClass=ae),me?(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 Ve=me?Il(W,V.buffer,N,A,_):W;if(me&&V.placeholder==="skeleton"&&_&&(!Ve||!Ve.trim())){let Ke=document.createElement("div"),rt=ei();rt.classList.add("persona-pill-peek__skeleton"),Ke.appendChild(rt),Ml(g,Ke)}else{let Ke=Math.max(0,Ve.length-100),rt=Ve.length>100?Ve.slice(-100):Ve,It=la(rt);if(!me||!N){let D=Ve.length>100?`\u2026${rt}`:rt;g.textContent!==D&&(g.textContent=D)}else{let D=It;(N.wrap==="char"||N.wrap==="word")&&(D=Zs(It,N.wrap,`peek-${A.id}`,{skipTags:N.skipTags,startIndex:Ke}));let Oe=document.createElement("div");if(Oe.innerHTML=D,N.useCaret&&rt.length>0){let Ue=Hl(),be=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),Qt=be[be.length-1];Qt!=null&&Qt.parentNode?Qt.parentNode.insertBefore(Ue,Qt.nextSibling):Oe.appendChild(Ue)}Ml(g,Oe),(Pe=N.onAfterRender)==null||Pe.call(N,{container:g,bubble:c,messageId:A.id,message:A,speed:V.speed,duration:V.duration})}}let Qe=Xn||Po;c.classList.toggle("persona-pill-peek--visible",Qe)};if(H()){let c=Re.peekBanner;if(c){let A=W=>{W.preventDefault(),W.stopPropagation(),jt(!0,"user")};c.addEventListener("pointerdown",A),Tt.push(()=>{c.removeEventListener("pointerdown",A)})}let g=()=>{Po||(Po=!0,po())},y=()=>{Po&&(Po=!1,po())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",y),Tt.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",y)}),at&&(at.addEventListener("pointerenter",g),at.addEventListener("pointerleave",y),Tt.push(()=>{at.removeEventListener("pointerenter",g),at.removeEventListener("pointerleave",y)}))}let Ti=c=>{var Te,Ve,Se,ct,Qe,ht,xt,Be;let g=(Ve=(Te=n.launcher)==null?void 0:Te.composerBar)!=null?Ve:{},y=(Se=g.expandedSize)!=null?Se:"anchored",A=(ct=g.bottomOffset)!=null?ct:"16px",W=g.collapsedMaxWidth,_=(Qe=g.expandedMaxWidth)!=null?Qe:"880px",U=(ht=g.expandedTopOffset)!=null?ht:"5vh",V=(xt=g.modalMaxWidth)!=null?xt:"880px",N=(Be=g.modalMaxHeight)!=null?Be:"min(90vh, 800px)",Ce="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ae=We.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",at){let Pe=at.style;Pe.bottom=A,Pe.width=W!=null?W:""}if(c&&y!=="fullscreen"){if(y==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=V,ae.maxWidth=Ce,ae.maxHeight=N,ae.height=N;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${A} + ${me})`,ae.top=U,ae.width=_,ae.maxWidth=Ce}},Ro=()=>{var N,Ce,me,ae,Te,Ve,Se,ct;if(!I())return;if(H()){let ht=(me=((Ce=(N=n.launcher)==null?void 0:N.composerBar)!=null?Ce:{}).expandedSize)!=null?me:"anchored",xt=L?"expanded":"collapsed";We.dataset.state=xt,We.dataset.expandedSize=ht,at&&(at.dataset.state=xt,at.dataset.expandedSize=ht),We.style.removeProperty("display"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ti(L),j.style.display=L?"flex":"none",Fn(),L?(wi(),Ai()):(gs(),hs()),po();return}let c=Pr(n),g=(ae=r.ownerDocument.defaultView)!=null?ae:window,y=(Ve=(Te=n.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Ve:640,A=(ct=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?ct:!0,W=g.innerWidth<=y,_=A&&W&&T,U=Sn(n).reveal;L?(We.style.removeProperty("display"),We.style.display=c?"flex":"",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),Ar?Ar.element.style.display="none":Sr&&(Sr.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!_?(We.style.removeProperty("display"),We.style.display="flex",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.setProperty("display","none","important"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.display="",We.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),Ar?Ar.element.style.display=c?"none":"":Sr&&(Sr.style.display=c?"none":""))},jt=(c,g="user")=>{var _,U;if(!I()||L===c)return;let y=L;L=c,Ro();let A=(()=>{var Se,ct,Qe,ht,xt,Be,Pe,Ke,rt,It;let V=(ct=(Se=n.launcher)==null?void 0:Se.sidebarMode)!=null?ct:!1,N=(Qe=r.ownerDocument.defaultView)!=null?Qe:window,Ce=(xt=(ht=n.launcher)==null?void 0:ht.mobileFullscreen)!=null?xt:!0,me=(Pe=(Be=n.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Pe:640,ae=N.innerWidth<=me,Te=Pr(n)&&Ce&&ae,Ve=H()&&((It=(rt=(Ke=n.launcher)==null?void 0:Ke.composerBar)==null?void 0:rt.expandedSize)!=null?It:"fullscreen")==="fullscreen";return V||Ce&&ae&&T||Te||Ve})();if(L&&A){if(!Cr){let V=r.getRootNode(),N=V instanceof ShadowRoot?V.host:r.closest(".persona-host");N&&(Cr=Qp(N,(U=(_=n.launcher)==null?void 0:_.zIndex)!=null?U:Xr))}wr||(wr=Jp(r.ownerDocument))}else L||(Cr==null||Cr(),Cr=null,wr==null||wr(),wr=null);L&&(ys(),ut()==="follow"?Zn(!0):fs());let W={open:L,source:g,timestamp:Date.now()};L&&!y?a.emit("widget:opened",W):!L&&y&&a.emit("widget:closed",W),a.emit("widget:state",{open:L,launcherEnabled:T,voiceActive:Pt.active,streaming:q.isStreaming()})},Ra=c=>{ar(c?"stop":"send"),K&&(K.disabled=c),On.buttons.forEach(g=>{g.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Ia=()=>{Pt.active||ee&&ee.focus()};a.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Ia(),200)});let Xo=()=>{var y,A,W,_,U,V,N,Ce,me,ae,Te;hr.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",sn.textContent=(_=(W=n.copy)==null?void 0:W.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",ee.placeholder=(V=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?V:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let Ve=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;c.style.display=Ve?"":"none",Ve?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(Ce=n.sendButton)==null?void 0:Ce.useIcon)!=null&&me)&&!(q!=null&&q.isStreaming())&&(Ge.textContent=(Te=(ae=n.copy)==null?void 0:ae.sendButtonLabel)!=null?Te:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let je=null,P=()=>{je==null&&(je=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(je),je=null;return}let g=Date.now();c.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=Qi(g-A))})},100))};if(q=new ja(n,{onMessagesChanged(c){var A;Ko(nt,c,xe),P(),Sa(c),Zn(!Xn),Ci(c);let g=[...c].reverse().find(W=>W.role==="user");c.length===0&&Go(),!Ta||jo?(Ta=!0,Ma=(A=g==null?void 0:g.id)!=null?A:null):g&&g.id!==Ma&&(Ma=g.id,vi(g.id));let y=Pt.lastUserMessageId;g&&g.id!==y&&(Pt.lastUserMessageId=g.id,a.emit("user:message",g)),Pt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),La(c),po()},onStatusChanged(c){var A;let g=(A=n.statusIndicator)!=null?A:{};wt(or,(W=>{var _,U,V,N;return W==="idle"?(_=g.idleText)!=null?_:Kr.idle:W==="connecting"?(U=g.connectingText)!=null?U:Kr.connecting:W==="connected"?(V=g.connectedText)!=null?V:Kr.connected:W==="error"?(N=g.errorText)!=null?N:Kr.error:Kr[W]})(c),g,c)},onStreamingChanged(c){Xn=c,Ra(c),q&&Ko(nt,q.getMessages(),xe),c||Zn(!0),po()},onVoiceStatusChanged(c){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":Io(),Xb();break;case"speaking":Io(),Qb();break;default:c==="idle"&&q.isBargeInActive()?(Io(),bs(),K==null||K.setAttribute("aria-label","End voice session")):(Pt.active=!1,Io(),Pn("system"),dn());break}},onArtifactsState(c){Yt=c,mn(),La()}}),vt.current=q,Ta=!0,((Hf=(If=n.voiceRecognition)==null?void 0:If.provider)==null?void 0:Hf.type)==="runtype")try{q.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&q.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(ge||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var y;(y=n.onSSEEvent)==null||y.call(n,c,g),Z==null||Z.processEvent(c,g),ge==null||ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,A;if(c){if(c.metadata&&(d=fu(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length){jo=!0;try{q.hydrateMessages(c.messages)}finally{jo=!1}}(y=c.artifacts)!=null&&y.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 z=()=>{var g,y,A;!H()||L||!((A=(y=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||A)||jt(!0,"auto")},B=c=>{var W;if(c.preventDefault(),q.isStreaming()){q.cancel(),Z==null||Z.reset(),G==null||G.update();return}let g=ee.value.trim(),y=(W=St==null?void 0:St.hasAttachments())!=null?W:!1;if(!g&&!y)return;z();let A;y&&(A=[],A.push(...St.getContentParts()),g&&A.push($s(g))),ee.value="",ee.style.height="auto",Le(),q.sendMessage(g,{contentParts:A}),y&&St.clearAttachments()},oe=()=>{var c;return((c=n.features)==null?void 0:c.composerHistory)!==!1},ce={...kl},X=!1,Le=()=>{ce={...kl}},$e=()=>q.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),gt=c=>{if(!ee)return;X=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),X=!1;let g=ee.value.length;ee.setSelectionRange(g,g)},lt=()=>{X||Le()},qt=c=>{if(ee){if(oe()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ee.selectionStart===0&&ee.selectionEnd===0,y=gx({direction:c.key==="ArrowUp"?"up":"down",history:$e(),currentValue:ee.value,atStart:g,state:ce});if(ce=y.state,y.handled){c.preventDefault(),y.value!==void 0&>(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(q.isStreaming()){c.preventDefault();return}Le(),c.preventDefault(),Ge.click()}}},Zt=c=>{c.key!=="Escape"||c.isComposing||q.isStreaming()&&c.composedPath().includes(j)&&(q.cancel(),Z==null||Z.reset(),G==null||G.update(),Le(),c.preventDefault(),c.stopImmediatePropagation())},Ir=async c=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!St)return;let g=HC(c.clipboardData);g.length!==0&&(c.preventDefault(),await St.handleFiles(g))},ft=null,Mt=!1,br=null,Ze=null,_r=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fr=(c="user")=>{var _,U,V,N,Ce,me,ae;if(Mt||q.isStreaming())return;let g=_r();if(!g)return;ft=new g;let A=(U=((_=n.voiceRecognition)!=null?_:{}).pauseDuration)!=null?U:2e3;ft.continuous=!0,ft.interimResults=!0,ft.lang="en-US";let W=ee.value;ft.onresult=Te=>{let Ve="",Se="";for(let Qe=0;Qe<Te.results.length;Qe++){let ht=Te.results[Qe],xt=ht[0].transcript;ht.isFinal?Ve+=xt+" ":Se=xt}let ct=W+Ve+Se;ee.value=ct,br&&clearTimeout(br),(Ve||Se)&&(br=window.setTimeout(()=>{let Qe=ee.value.trim();Qe&&ft&&Mt&&(Or(),ee.value="",ee.style.height="auto",q.sendMessage(Qe,{viaVoice:!0}))},A))},ft.onerror=Te=>{Te.error!=="no-speech"&&Or()},ft.onend=()=>{if(Mt){let Te=ee.value.trim();Te&&Te!==W.trim()&&(ee.value="",ee.style.height="auto",q.sendMessage(Te,{viaVoice:!0})),Or()}};try{if(ft.start(),Mt=!0,Pt.active=!0,c!=="system"&&(Pt.manuallyDeactivated=!1),Pn(c),dn(),K){let Te=(V=n.voiceRecognition)!=null?V:{};Ze={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(N=Te.iconName)!=null?N:"mic",iconSize:parseFloat((ae=(me=Te.iconSize)!=null?me:(Ce=n.sendButton)==null?void 0:Ce.size)!=null?ae:"40")||24};let Ve=Te.recordingBackgroundColor,Se=Te.recordingIconColor,ct=Te.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Ve!=null?Ve:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let Qe=K.querySelector("svg");Qe&&Qe.setAttribute("stroke",Se)}ct&&(K.style.borderColor=ct),K.setAttribute("aria-label","Stop voice recognition")}}catch{Or("system")}},Or=(c="user")=>{if(Mt){if(Mt=!1,br&&(clearTimeout(br),br=null),ft){try{ft.stop()}catch{}ft=null}if(Pt.active=!1,Pn(c),dn(),K){if(K.classList.remove("persona-voice-recording"),Ze){K.style.backgroundColor=Ze.backgroundColor,K.style.color=Ze.color,K.style.borderColor=Ze.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",Ze.color||"currentColor"),Ze=null}K.setAttribute("aria-label","Start voice recognition")}}},Kb=(c,g)=>{var ht,xt,Be,Pe,Ke,rt,It,D;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((ht=c==null?void 0:c.provider)==null?void 0:ht.type)==="runtype";if(!(y||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 V=(xt=c==null?void 0:c.iconName)!=null?xt:"mic",N=(Be=g==null?void 0:g.size)!=null?Be:"40px",Ce=(Pe=c==null?void 0:c.iconSize)!=null?Pe:N,me=parseFloat(Ce)||24,ae=(Ke=c==null?void 0:c.backgroundColor)!=null?Ke:g==null?void 0:g.backgroundColor,Te=(rt=c==null?void 0:c.iconColor)!=null?rt:g==null?void 0:g.textColor;U.style.width=Ce,U.style.height=Ce,U.style.minWidth=Ce,U.style.minHeight=Ce,U.style.fontSize="18px",U.style.lineHeight="1",Te?U.style.color=Te:U.style.color="var(--persona-text, #111827)";let Se=Me(V,me,Te||"currentColor",1.5);Se?U.appendChild(Se):U.textContent="\u{1F3A4}",ae?U.style.backgroundColor=ae: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 ct=(It=c==null?void 0:c.tooltipText)!=null?It:"Start voice recognition";if(((D=c==null?void 0:c.showTooltip)!=null?D:!1)&&ct){let Oe=v("div","persona-send-button-tooltip");Oe.textContent=ct,_.appendChild(Oe)}return{micButton:U,micButtonWrapper:_}},id=()=>{var g,y,A,W,_;if(!K||Ze)return;let c=(g=n.voiceRecognition)!=null?g:{};Ze={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((_=(W=c.iconSize)!=null?W:(A=n.sendButton)==null?void 0:A.size)!=null?_:"40")||24}},ld=(c,g)=>{var _,U,V,N,Ce;if(!K)return;let y=K.querySelector("svg");y&&y.remove();let A=(Ce=Ze==null?void 0:Ze.iconSize)!=null?Ce:parseFloat((N=(V=(_=n.voiceRecognition)==null?void 0:_.iconSize)!=null?V:(U=n.sendButton)==null?void 0:U.size)!=null?N:"40")||24,W=Me(c,A,g,1.5);W&&K.appendChild(W)},Mi=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},bs=()=>{var W;if(!K)return;id();let c=(W=n.voiceRecognition)!=null?W:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,A=c.recordingBorderColor;if(Mi(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let _=K.querySelector("svg");_&&_.setAttribute("stroke",y)}A&&(K.style.borderColor=A),K.setAttribute("aria-label","Stop voice recognition")},Xb=()=>{var V,N,Ce,me,ae,Te,Ve,Se;if(!K)return;id();let c=(V=n.voiceRecognition)!=null?V:{},g=q.getVoiceInterruptionMode(),y=(N=c.processingIconName)!=null?N:"loader",A=(me=(Ce=c.processingIconColor)!=null?Ce:Ze==null?void 0:Ze.color)!=null?me:"",W=(Te=(ae=c.processingBackgroundColor)!=null?ae:Ze==null?void 0:Ze.backgroundColor)!=null?Te:"",_=(Se=(Ve=c.processingBorderColor)!=null?Ve:Ze==null?void 0:Ze.borderColor)!=null?Se:"";Mi(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=W,K.style.borderColor=_;let U=A||"currentColor";K.style.color=U,ld(y,U),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},Qb=()=>{var Ce,me,ae,Te,Ve,Se,ct,Qe,ht,xt,Be,Pe;if(!K)return;id();let c=(Ce=n.voiceRecognition)!=null?Ce:{},g=q.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(me=c.speakingIconName)!=null?me:y,W=(Se=c.speakingIconColor)!=null?Se:g==="barge-in"?(Te=(ae=c.recordingIconColor)!=null?ae:Ze==null?void 0:Ze.color)!=null?Te:"":(Ve=Ze==null?void 0:Ze.color)!=null?Ve:"",_=(ht=c.speakingBackgroundColor)!=null?ht:g==="barge-in"?(ct=c.recordingBackgroundColor)!=null?ct:"var(--persona-voice-recording-bg, #ef4444)":(Qe=Ze==null?void 0:Ze.backgroundColor)!=null?Qe:"",U=(Pe=c.speakingBorderColor)!=null?Pe:g==="barge-in"?(xt=c.recordingBorderColor)!=null?xt:"":(Be=Ze==null?void 0:Ze.borderColor)!=null?Be:"";Mi(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=_,K.style.borderColor=U;let V=W||"currentColor";K.style.color=V,ld(A,V);let N=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",N),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},Io=()=>{var c,g,y;K&&(Mi(),Ze&&(K.style.backgroundColor=(c=Ze.backgroundColor)!=null?c:"",K.style.color=(g=Ze.color)!=null?g:"",K.style.borderColor=(y=Ze.borderColor)!=null?y:"",ld(Ze.iconName,Ze.color||"currentColor"),Ze=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ki=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=q.getVoiceStatus(),A=q.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{Pt.active=!1,Pt.manuallyDeactivated=!0,dn(),Pn("user"),Io()});return}q.toggleVoice().then(()=>{Pt.active=q.isVoiceActive(),Pt.manuallyDeactivated=!q.isVoiceActive(),dn(),Pn("user"),q.isVoiceActive()?bs():Io()});return}if(Mt){let y=ee.value.trim();Pt.manuallyDeactivated=!0,dn(),Or("user"),y&&(ee.value="",ee.style.height="auto",q.sendMessage(y))}else Pt.manuallyDeactivated=!1,dn(),fr("user")};qr=ki,K&&(K.addEventListener("click",ki),Tt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Io()):Or("system"),K&&K.removeEventListener("click",ki)}));let Jb=a.on("assistant:complete",()=>{ss&&(Pt.active||Pt.manuallyDeactivated||ss==="assistant"&&!Pt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Pt.active&&!Pt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{Pt.active=q.isVoiceActive(),Pn("auto"),q.isVoiceActive()&&bs()}):fr("auto"))},600))});Tt.push(Jb);let Yb=a.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Tt.push(Yb);let Ha=()=>{jt(!L,"user")},Ar=null,Sr=null;if(T&&!H()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>ni(n,Ha).element,onToggle:Ha});g&&(Sr=g)}Sr||(Ar=ni(n,Ha))}Ar?r.appendChild(Ar.element):Sr&&r.appendChild(Sr),Ro(),Sa(),Xo(),Ra(q.isStreaming()),ut()==="follow"?Zn(!0):fs(),gi(),k&&(!T||H()?setTimeout(()=>Ia(),0):L&&setTimeout(()=>Ia(),200));let ys=()=>{var N,Ce,me,ae,Te,Ve,Se,ct,Qe,ht,xt,Be,Pe,Ke,rt,It,D,Oe,Ue,be,Qt,Gt;if(H()){Mr(),Ro();return}let c=Pr(n),g=(Ce=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?Ce:!1,y=c||g||((ae=(me=n.launcher)==null?void 0:me.fullHeight)!=null?ae:!1),A=(Te=r.ownerDocument.defaultView)!=null?Te:window,W=(Se=(Ve=n.launcher)==null?void 0:Ve.mobileFullscreen)!=null?Se:!0,_=(Qe=(ct=n.launcher)==null?void 0:ct.mobileBreakpoint)!=null?Qe:640,U=A.innerWidth<=_,V=W&&U&&T;try{if(V){Fn(),_o(r,n);return}if(E&&(E=!1,Fn(),_o(r,n)),!T&&!c){he.style.height="",he.style.width="";return}if(!g&&!c){let dr=(xt=(ht=n==null?void 0:n.launcher)==null?void 0:ht.width)!=null?xt:n==null?void 0:n.launcherWidth,Wt=dr!=null?dr:An;he.style.width=Wt,he.style.maxWidth=Wt}if(Kn(),!y){let dr=A.innerHeight,Wt=64,ir=(Pe=(Be=n.launcher)==null?void 0:Be.heightOffset)!=null?Pe:0,bn=Math.max(200,dr-Wt),kr=Math.min(640,bn),ot=Math.max(200,kr-ir);he.style.height=`${ot}px`}}finally{if(Mr(),Ro(),L&&T){let Wt=((Ke=r.ownerDocument.defaultView)!=null?Ke:window).innerWidth<=((It=(rt=n.launcher)==null?void 0:rt.mobileBreakpoint)!=null?It:640),ir=(Oe=(D=n.launcher)==null?void 0:D.sidebarMode)!=null?Oe:!1,bn=(be=(Ue=n.launcher)==null?void 0:Ue.mobileFullscreen)!=null?be:!0,kr=Pr(n)&&bn&&Wt,ot=ir||bn&&Wt&&T||kr;if(ot&&!wr){let _t=r.getRootNode(),Lr=_t instanceof ShadowRoot?_t.host:r.closest(".persona-host");Lr&&!Cr&&(Cr=Qp(Lr,(Gt=(Qt=n.launcher)==null?void 0:Qt.zIndex)!=null?Gt:Xr)),wr=Jp(r.ownerDocument)}else ot||(Cr==null||Cr(),Cr=null,wr==null||wr(),wr=null)}}};ys();let Pu=(Wf=r.ownerDocument.defaultView)!=null?Wf:window;if(Pu.addEventListener("resize",ys),Tt.push(()=>Pu.removeEventListener("resize",ys)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Mr()});c.observe(Ne),Tt.push(()=>c.disconnect())}xn=ue.scrollTop;let Ru=vo(ue),Zb=()=>{let c=ue.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:ue.ownerDocument.getSelection()},dd=()=>Cx(Zb(),ue),Iu=()=>{let c=ue.scrollTop,g=vo(ue),y=g<Ru;if(Ru=g,ut()!=="follow"){xn=c,cn();return}let{action:A,nextLastScrollTop:W}=Ll({following:hn.isFollowing(),currentScrollTop:c,lastScrollTop:xn,nearBottom:xa(ue,ka),userScrollThreshold:fi,isAutoScrolling:Un||Vo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(xn=W,A==="resume"){dd()||Yn();return}A==="pause"&&Pa()};if(ue.addEventListener("scroll",Iu,{passive:!0}),Tt.push(()=>ue.removeEventListener("scroll",Iu)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yi()});c.observe(nt),c.observe(ue),Tt.push(()=>c.disconnect())}let Hu=()=>{ut()==="follow"&&hn.isFollowing()&&dd()&&Pa()},Wu=ue.ownerDocument;Wu.addEventListener("selectionchange",Hu),Tt.push(()=>{Wu.removeEventListener("selectionchange",Hu)});let Bu=c=>{if(ut()!=="follow")return;let g=Pl({following:hn.isFollowing(),deltaY:c.deltaY,nearBottom:xa(ue,ka),resumeWhenNearBottom:!0});g==="pause"?Pa():g==="resume"&&!dd()&&Yn()};ue.addEventListener("wheel",Bu,{passive:!0}),Tt.push(()=>ue.removeEventListener("wheel",Bu)),tt.addEventListener("click",()=>{Go(),ue.scrollTop=ue.scrollHeight,xn=ue.scrollTop,Yn(),Zn(!0),cn()}),Tt.push(()=>tt.remove()),Tt.push(()=>{ls(),Go()});let Du=()=>{F&&(Ln&&(F.removeEventListener("click",Ln),Ln=null),I()?(F.style.display="",Ln=()=>{jt(!1,"user")},F.addEventListener("click",Ln)):F.style.display="none")};Du(),(()=>{let{clearChatButton:c}=Re;c&&c.addEventListener("click",()=>{q.clearMessages(),so.clear(),Yn(),Oo(Re.composerOverlay);try{localStorage.removeItem(ns),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ns}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ns)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},S.syncFromMetadata(),ge==null||ge.clear(),Z==null||Z.reset(),G==null||G.update()})})(),Bt&&Bt.addEventListener("submit",B),ee==null||ee.addEventListener("keydown",qt),ee==null||ee.addEventListener("input",lt),ee==null||ee.addEventListener("paste",Ir);let Fu=(Bf=r.ownerDocument)!=null?Bf:document;Fu.addEventListener("keydown",Zt,!0);let Ou="persona-attachment-drop-active",vs=0,cd=()=>{vs=0,j.classList.remove(Ou)},Wa=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&St!==null},Nu=c=>{!rd(c.dataTransfer)||!Wa()||(vs++,vs===1&&j.classList.add(Ou))},_u=c=>{!rd(c.dataTransfer)||!Wa()||(vs--,vs<=0&&cd())},Uu=c=>{!rd(c.dataTransfer)||!Wa()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},qu=c=>{var y;if(!rd(c.dataTransfer)||!Wa())return;c.preventDefault(),c.stopPropagation(),cd();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&St.handleFiles(g)},Ho=!0;j.addEventListener("dragenter",Nu,Ho),j.addEventListener("dragleave",_u,Ho),r.addEventListener("dragover",Uu,Ho),r.addEventListener("drop",qu,Ho);let Ei=r.ownerDocument,zu=c=>{Wa()&&c.preventDefault()},$u=c=>{Wa()&&c.preventDefault()};Ei.addEventListener("dragover",zu),Ei.addEventListener("drop",$u),Tt.push(()=>{Bt&&Bt.removeEventListener("submit",B),ee==null||ee.removeEventListener("keydown",qt),ee==null||ee.removeEventListener("input",lt),ee==null||ee.removeEventListener("paste",Ir),Fu.removeEventListener("keydown",Zt,!0)}),Tt.push(()=>{j.removeEventListener("dragenter",Nu,Ho),j.removeEventListener("dragleave",_u,Ho),r.removeEventListener("dragover",Uu,Ho),r.removeEventListener("drop",qu,Ho),Ei.removeEventListener("dragover",zu),Ei.removeEventListener("drop",$u),cd()}),Tt.push(()=>{q.cancel()}),Ar?Tt.push(()=>{Ar==null||Ar.destroy()}):Sr&&Tt.push(()=>{Sr==null||Sr.remove()});let Er={update(c){var jr,Jr,eo,Nr,Yr,Zr,ea,Cs,qf,zf,$f,Vf,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,bm,ym,vm,Cm,wm,Am,Sm,Tm,Mm,km,Em,Lm,Pm,Rm,Im,Hm,Wm,Bm,Dm,Fm,Om,Nm,_m,Um,qm,zm,$m,Vm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,ng,og,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,bg,yg,vg,Cg,wg,Ag,Sg,Tg,Mg,kg,Eg,Lg,Pg,Rg,Ig,Hg,Wg,Bg,Dg,Fg,Og,Ng,_g;let g=n.toolCall,y=n.messageActions,A=(jr=n.layout)==null?void 0:jr.messages,W=n.colorScheme,_=n.loadingIndicator,U=n.iterationDisplay,V=(Jr=n.features)==null?void 0:Jr.showReasoning,N=(eo=n.features)==null?void 0:eo.showToolCalls,Ce=(Nr=n.features)==null?void 0:Nr.toolCallDisplay,me=(Yr=n.features)==null?void 0:Yr.reasoningDisplay;n={...n,...c},Fn(),_o(r,n),Gl(r,n),Kl(r,n),mn(),n.colorScheme!==W&&Mo();let ae=li.getForInstance(n.plugins);o.length=0,o.push(...ae),T=(ea=(Zr=n.launcher)==null?void 0:Zr.enabled)!=null?ea:!0,M=(qf=(Cs=n.launcher)==null?void 0:Cs.autoExpand)!=null?qf:!1,Je=($f=(zf=n.features)==null?void 0:zf.showReasoning)!=null?$f:!0,we=(jf=(Vf=n.features)==null?void 0:Vf.showToolCalls)!=null?jf:!0,Ae=(Kf=(Gf=n.features)==null?void 0:Gf.scrollToBottom)!=null?Kf:{};let Te=ut();qe=(Qf=(Xf=n.features)==null?void 0:Xf.scrollBehavior)!=null?Qf:{},Te!==ut()&&(Go(),Yn()),un(),cn();let Ve=De;if(De=(Yf=(Jf=n.features)==null?void 0:Jf.showEventStreamToggle)!=null?Yf:!1,De&&!Ve){if(ge||(re=new si(J),ge=new ai(Q,re),Z=Z!=null?Z:new ii,re.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),q.setSSEEventCallback((Y,Dt)=>{var tr;(tr=n.onSSEEvent)==null||tr.call(n,Y,Dt),Z==null||Z.processEvent(Y,Dt),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(Dt)})})),!yt&&Fe){let Y=(em=(Zf=n.features)==null?void 0:Zf.eventStream)==null?void 0:em.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"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");yt=v("button",Dt),yt.style.width="28px",yt.style.height="28px",yt.style.color=an.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let tr=Me("activity","18px","currentColor",1.5);tr&&yt.appendChild(tr);let bt=Re.clearChatButtonWrapper,Ut=Re.closeButtonWrapper,Wr=bt||Ut;Wr&&Wr.parentNode===Fe?Fe.insertBefore(yt,Wr):Fe.appendChild(yt),yt.addEventListener("click",()=>{pe?ln():Mn()})}}else!De&&Ve&&(ln(),yt&&(yt.remove(),yt=null),ge==null||ge.clear(),re==null||re.destroy(),ge=null,re=null,Z==null||Z.reset(),Z=null);if(((tm=n.launcher)==null?void 0:tm.enabled)===!1&&Ar&&(Ar.destroy(),Ar=null),((rm=n.launcher)==null?void 0:rm.enabled)===!1&&Sr&&(Sr.remove(),Sr=null),((nm=n.launcher)==null?void 0:nm.enabled)!==!1&&!Ar&&!Sr){let Y=o.find(Dt=>Dt.renderLauncher);if(Y!=null&&Y.renderLauncher){let Dt=Y.renderLauncher({config:n,defaultRenderer:()=>ni(n,Ha).element,onToggle:Ha});Dt&&(Sr=Dt,r.appendChild(Sr))}Sr||(Ar=ni(n,Ha),r.appendChild(Ar.element))}Ar&&Ar.update(n),Ie&&((om=n.launcher)==null?void 0:om.title)!==void 0&&(Ie.textContent=n.launcher.title),Xe&&((am=n.launcher)==null?void 0:am.subtitle)!==void 0&&(Xe.textContent=n.launcher.subtitle);let Se=(sm=n.layout)==null?void 0:sm.header;if((Se==null?void 0:Se.layout)!==w&&Fe){let Y=Se?Qa(n,Se,{showClose:I(),onClose:()=>jt(!1,"user")}):Co({config:n,showClose:I(),onClose:()=>jt(!1,"user")});Fe.replaceWith(Y.header),Fe=Y.header,fe=Y.iconHolder,Ie=Y.headerTitle,Xe=Y.headerSubtitle,F=Y.closeButton,w=Se==null?void 0:Se.layout}else if(Se&&(fe&&(fe.style.display=Se.showIcon===!1?"none":""),Ie&&(Ie.style.display=Se.showTitle===!1?"none":""),Xe&&(Xe.style.display=Se.showSubtitle===!1?"none":""),F&&(F.style.display=Se.showCloseButton===!1?"none":""),Re.clearChatButtonWrapper)){let Y=Se.showClearChat;if(Y!==void 0){Re.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:Dt}=Re;Dt&&!Dt.classList.contains("persona-absolute")&&(Y?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"))}}let Qe=((im=n.layout)==null?void 0:im.showHeader)!==!1;Fe&&(Fe.style.display=Qe?"":"none");let ht=((lm=n.layout)==null?void 0:lm.showFooter)!==!1;Ne&&(Ne.style.display=ht?"":"none"),Mr(),cn(),T!==C?T?jt(M,"auto"):(L=!0,Ro()):M!==x&&jt(M,"auto"),x=M,C=T,ys(),Du();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ke=JSON.stringify(n.messageActions)!==JSON.stringify(y),rt=JSON.stringify((dm=n.layout)==null?void 0:dm.messages)!==JSON.stringify(A),It=((cm=n.loadingIndicator)==null?void 0:cm.render)!==(_==null?void 0:_.render)||((pm=n.loadingIndicator)==null?void 0:pm.renderIdle)!==(_==null?void 0:_.renderIdle)||((um=n.loadingIndicator)==null?void 0:um.showBubble)!==(_==null?void 0:_.showBubble),D=n.iterationDisplay!==U,Oe=((mm=(fm=n.features)==null?void 0:fm.showReasoning)!=null?mm:!0)!==(V!=null?V:!0)||((hm=(gm=n.features)==null?void 0:gm.showToolCalls)!=null?hm:!0)!==(N!=null?N:!0)||JSON.stringify((xm=n.features)==null?void 0:xm.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((bm=n.features)==null?void 0:bm.reasoningDisplay)!==JSON.stringify(me);(Pe||Ke||rt||It||D||Oe)&&q&&(as++,Ko(nt,q.getMessages(),xe));let be=(ym=n.launcher)!=null?ym:{},Qt=(vm=be.headerIconHidden)!=null?vm:!1,Gt=(wm=(Cm=n.layout)==null?void 0:Cm.header)==null?void 0:wm.showIcon,dr=Qt||Gt===!1,Wt=be.headerIconName,ir=(Am=be.headerIconSize)!=null?Am:"48px";if(fe){let Y=j.querySelector(".persona-border-b-persona-divider"),Dt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(dr)fe.style.display="none",Y&&Dt&&!Y.contains(Dt)&&Y.insertBefore(Dt,Y.firstChild);else{if(fe.style.display="",fe.style.height=ir,fe.style.width=ir,Y&&Dt&&(Y.contains(fe)?fe.nextSibling!==Dt&&(fe.remove(),Y.insertBefore(fe,Dt)):Y.insertBefore(fe,Dt)),Wt){let bt=parseFloat(ir)||24,Ut=Me(Wt,bt*.6,"#ffffff",2);Ut?fe.replaceChildren(Ut):fe.textContent=(Sm=be.agentIconText)!=null?Sm:"\u{1F4AC}"}else if(be.iconUrl){let bt=fe.querySelector("img");if(bt)bt.src=be.iconUrl,bt.style.height=ir,bt.style.width=ir;else{let Ut=document.createElement("img");Ut.src=be.iconUrl,Ut.alt="",Ut.className="persona-rounded-xl persona-object-cover",Ut.style.height=ir,Ut.style.width=ir,fe.replaceChildren(Ut)}}else{let bt=fe.querySelector("svg"),Ut=fe.querySelector("img");(bt||Ut)&&fe.replaceChildren(),fe.textContent=(Tm=be.agentIconText)!=null?Tm:"\u{1F4AC}"}let tr=fe.querySelector("img");tr&&(tr.style.height=ir,tr.style.width=ir)}}let bn=(km=(Mm=n.layout)==null?void 0:Mm.header)==null?void 0:km.showTitle,kr=(Lm=(Em=n.layout)==null?void 0:Em.header)==null?void 0:Lm.showSubtitle;if(Ie&&(Ie.style.display=bn===!1?"none":""),Xe&&(Xe.style.display=kr===!1?"none":""),F){((Rm=(Pm=n.layout)==null?void 0:Pm.header)==null?void 0:Rm.showCloseButton)===!1?F.style.display="none":F.style.display="";let Dt=(Im=be.closeButtonSize)!=null?Im:"32px",tr=(Hm=be.closeButtonPlacement)!=null?Hm:"inline";F.style.height=Dt,F.style.width=Dt;let{closeButtonWrapper:bt}=Re,Ut=tr==="top-right",Wr=bt==null?void 0:bt.classList.contains("persona-absolute");if(bt&&Ut!==Wr)if(bt.remove(),Ut)bt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(bt);else{let Ct=(Bm=(Wm=be.clearChat)==null?void 0:Wm.placement)!=null?Bm:"inline",Br=(Fm=(Dm=be.clearChat)==null?void 0:Dm.enabled)!=null?Fm:!0;bt.className=Br&&Ct==="inline"?"":"persona-ml-auto";let pn=j.querySelector(".persona-border-b-persona-divider");pn&&pn.appendChild(bt)}if(F.style.color=be.closeButtonColor||an.actionIconColor,be.closeButtonBackgroundColor?(F.style.backgroundColor=be.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),be.closeButtonBorderWidth||be.closeButtonBorderColor){let Ct=be.closeButtonBorderWidth||"0px",Br=be.closeButtonBorderColor||"transparent";F.style.border=`${Ct} solid ${Br}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");be.closeButtonBorderRadius?(F.style.borderRadius=be.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),be.closeButtonPaddingX?(F.style.paddingLeft=be.closeButtonPaddingX,F.style.paddingRight=be.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),be.closeButtonPaddingY?(F.style.paddingTop=be.closeButtonPaddingY,F.style.paddingBottom=be.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Gr=(Om=be.closeButtonIconName)!=null?Om:"x",zn=(Nm=be.closeButtonIconText)!=null?Nm:"\xD7";F.innerHTML="";let en=Me(Gr,"28px","currentColor",1);en?F.appendChild(en):F.textContent=zn;let Tr=(_m=be.closeButtonTooltipText)!=null?_m:"Close chat",vn=(Um=be.closeButtonShowTooltip)!=null?Um:!0;if(F.setAttribute("aria-label",Tr),bt&&(bt._cleanupTooltip&&(bt._cleanupTooltip(),delete bt._cleanupTooltip),vn&&Tr)){let Ct=null,Br=()=>{if(Ct||!F)return;let ta=F.ownerDocument,ws=ta.body;if(!ws)return;Ct=ro(ta,"div","persona-clear-chat-tooltip"),Ct.textContent=Tr;let As=ro(ta,"div");As.className="persona-clear-chat-tooltip-arrow",Ct.appendChild(As);let ra=F.getBoundingClientRect();Ct.style.position="fixed",Ct.style.zIndex=String(Uo),Ct.style.left=`${ra.left+ra.width/2}px`,Ct.style.top=`${ra.top-8}px`,Ct.style.transform="translate(-50%, -100%)",ws.appendChild(Ct)},pn=()=>{Ct&&Ct.parentNode&&(Ct.parentNode.removeChild(Ct),Ct=null)};bt.addEventListener("mouseenter",Br),bt.addEventListener("mouseleave",pn),F.addEventListener("focus",Br),F.addEventListener("blur",pn),bt._cleanupTooltip=()=>{pn(),bt&&(bt.removeEventListener("mouseenter",Br),bt.removeEventListener("mouseleave",pn)),F&&(F.removeEventListener("focus",Br),F.removeEventListener("blur",pn))}}}let{clearChatButton:ot,clearChatButtonWrapper:_t}=Re;if(ot){let Y=(qm=be.clearChat)!=null?qm:{},Dt=(zm=Y.enabled)!=null?zm:!0,tr=(Vm=($m=n.layout)==null?void 0:$m.header)==null?void 0:Vm.showClearChat,bt=tr!==void 0?tr:Dt,Ut=(jm=Y.placement)!=null?jm:"inline";if(_t){_t.style.display=bt?"":"none";let{closeButtonWrapper:Wr}=Re;!H()&&Wr&&!Wr.classList.contains("persona-absolute")&&(bt?Wr.classList.remove("persona-ml-auto"):Wr.classList.add("persona-ml-auto"));let Gr=Ut==="top-right",zn=_t.classList.contains("persona-absolute");if(!H()&&Gr!==zn&&bt){if(_t.remove(),Gr)_t.className="persona-absolute persona-top-4 persona-z-50",_t.style.right="48px",j.style.position="relative",j.appendChild(_t);else{_t.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",_t.style.right="";let Tr=j.querySelector(".persona-border-b-persona-divider"),vn=Re.closeButtonWrapper;Tr&&vn&&vn.parentElement===Tr?Tr.insertBefore(_t,vn):Tr&&Tr.appendChild(_t)}let en=Re.closeButtonWrapper;en&&!en.classList.contains("persona-absolute")&&(Gr?en.classList.add("persona-ml-auto"):en.classList.remove("persona-ml-auto"))}}if(bt){if(!H()){let Ct=(Gm=Y.size)!=null?Gm:"32px";ot.style.height=Ct,ot.style.width=Ct}let Wr=(Km=Y.iconName)!=null?Km:"refresh-cw",Gr=(Xm=Y.iconColor)!=null?Xm:"";ot.style.color=Gr||an.actionIconColor,ot.innerHTML="";let zn=H()?"14px":"20px",en=Me(Wr,zn,"currentColor",2);if(en&&ot.appendChild(en),Y.backgroundColor?(ot.style.backgroundColor=Y.backgroundColor,ot.classList.remove("hover:persona-bg-gray-100")):(ot.style.backgroundColor="",ot.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let Ct=Y.borderWidth||"0px",Br=Y.borderColor||"transparent";ot.style.border=`${Ct} solid ${Br}`,ot.classList.remove("persona-border-none")}else ot.style.border="",ot.classList.add("persona-border-none");Y.borderRadius?(ot.style.borderRadius=Y.borderRadius,ot.classList.remove("persona-rounded-full")):(ot.style.borderRadius="",ot.classList.add("persona-rounded-full")),Y.paddingX?(ot.style.paddingLeft=Y.paddingX,ot.style.paddingRight=Y.paddingX):(ot.style.paddingLeft="",ot.style.paddingRight=""),Y.paddingY?(ot.style.paddingTop=Y.paddingY,ot.style.paddingBottom=Y.paddingY):(ot.style.paddingTop="",ot.style.paddingBottom="");let Tr=(Qm=Y.tooltipText)!=null?Qm:"Clear chat",vn=(Jm=Y.showTooltip)!=null?Jm:!0;if(ot.setAttribute("aria-label",Tr),_t&&(_t._cleanupTooltip&&(_t._cleanupTooltip(),delete _t._cleanupTooltip),vn&&Tr)){let Ct=null,Br=()=>{if(Ct||!ot)return;let ta=ot.ownerDocument,ws=ta.body;if(!ws)return;Ct=ro(ta,"div","persona-clear-chat-tooltip"),Ct.textContent=Tr;let As=ro(ta,"div");As.className="persona-clear-chat-tooltip-arrow",Ct.appendChild(As);let ra=ot.getBoundingClientRect();Ct.style.position="fixed",Ct.style.zIndex=String(Uo),Ct.style.left=`${ra.left+ra.width/2}px`,Ct.style.top=`${ra.top-8}px`,Ct.style.transform="translate(-50%, -100%)",ws.appendChild(Ct)},pn=()=>{Ct&&Ct.parentNode&&(Ct.parentNode.removeChild(Ct),Ct=null)};_t.addEventListener("mouseenter",Br),_t.addEventListener("mouseleave",pn),ot.addEventListener("focus",Br),ot.addEventListener("blur",pn),_t._cleanupTooltip=()=>{pn(),_t&&(_t.removeEventListener("mouseenter",Br),_t.removeEventListener("mouseleave",pn)),ot&&(ot.removeEventListener("focus",Br),ot.removeEventListener("blur",pn))}}}}let Lr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[di],In=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[wa.message,wa.messageAndClick];S=ci({parsers:Lr,handlers:In,getSessionMetadata:p,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),xe=ib(n,S,te),q.updateConfig(n),Ko(nt,q.getMessages(),xe),Sa(),Xo(),Ra(q.isStreaming());let yn=((Ym=n.voiceRecognition)==null?void 0:Ym.enabled)===!0,Qo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Jo=((eg=(Zm=n.voiceRecognition)==null?void 0:Zm.provider)==null?void 0:eg.type)==="runtype";if(yn&&(Qo||Jo))if(!K||!mt){let Y=Kb(n.voiceRecognition,n.sendButton);Y&&(K=Y.micButton,mt=Y.micButtonWrapper,Xt.insertBefore(mt,Fr),K.addEventListener("click",ki),K.disabled=q.isStreaming())}else{let Y=(tg=n.voiceRecognition)!=null?tg:{},Dt=(rg=n.sendButton)!=null?rg:{},tr=(ng=Y.iconName)!=null?ng:"mic",bt=(og=Dt.size)!=null?og:"40px",Ut=(ag=Y.iconSize)!=null?ag:bt,Wr=parseFloat(Ut)||24;K.style.width=Ut,K.style.height=Ut,K.style.minWidth=Ut,K.style.minHeight=Ut;let Gr=(ig=(sg=Y.iconColor)!=null?sg:Dt.textColor)!=null?ig:"currentColor";K.innerHTML="";let zn=Me(tr,Wr,Gr,2);zn?K.appendChild(zn):K.textContent="\u{1F3A4}";let en=(lg=Y.backgroundColor)!=null?lg:Dt.backgroundColor;en?K.style.backgroundColor=en:K.style.backgroundColor="",Gr?K.style.color=Gr:K.style.color="var(--persona-text, #111827)",Y.borderWidth?(K.style.borderWidth=Y.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Y.borderColor?K.style.borderColor=Y.borderColor:K.style.borderColor="",Y.paddingX?(K.style.paddingLeft=Y.paddingX,K.style.paddingRight=Y.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Y.paddingY?(K.style.paddingTop=Y.paddingY,K.style.paddingBottom=Y.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Tr=mt==null?void 0:mt.querySelector(".persona-send-button-tooltip"),vn=(dg=Y.tooltipText)!=null?dg:"Start voice recognition";if(((cg=Y.showTooltip)!=null?cg:!1)&&vn)if(Tr)Tr.textContent=vn,Tr.style.display="";else{let Br=document.createElement("div");Br.className="persona-send-button-tooltip",Br.textContent=vn,mt==null||mt.insertBefore(Br,K)}else Tr&&(Tr.style.display="none");mt.style.display="",K.disabled=q.isStreaming()}else K&&mt&&(mt.style.display="none",((ug=(pg=n.voiceRecognition)==null?void 0:pg.provider)==null?void 0:ug.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():Mt&&Or());if(((fg=n.attachments)==null?void 0:fg.enabled)===!0)if(!ye||!it){let Y=(mg=n.attachments)!=null?mg:{},tr=(hg=((gg=n.sendButton)!=null?gg:{}).size)!=null?hg:"40px";st||(st=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),st.style.display="none",Bt.insertBefore(st,ee)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((xg=Y.allowedTypes)!=null?xg:yo).join(","),ie.multiple=((bg=Y.maxFiles)!=null?bg:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Bt.insertBefore(ie,ee)),ye=v("div","persona-send-button-wrapper"),it=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(yg=Y.buttonTooltipText)!=null?yg:"Attach file");let bt=(vg=Y.buttonIconName)!=null?vg:"paperclip",Ut=tr,Wr=parseFloat(Ut)||40,Gr=Math.round(Wr*.6);it.style.width=Ut,it.style.height=Ut,it.style.minWidth=Ut,it.style.minHeight=Ut,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let zn=Me(bt,Gr,"currentColor",1.5);zn?it.appendChild(zn):it.textContent="\u{1F4CE}",it.addEventListener("click",vn=>{vn.preventDefault(),ie==null||ie.click()}),ye.appendChild(it);let en=(Cg=Y.buttonTooltipText)!=null?Cg:"Attach file",Tr=v("div","persona-send-button-tooltip");Tr.textContent=en,ye.appendChild(Tr),At.append(ye),!St&&ie&&st&&(St=ha.fromConfig(Y),St.setPreviewsContainer(st),ie.addEventListener("change",async()=>{St&&(ie!=null&&ie.files)&&(await St.handleFileSelect(ie.files),ie.value="")})),j.querySelector(".persona-attachment-drop-overlay")||j.appendChild(lb(Y.dropOverlay))}else{ye.style.display="";let Y=(wg=n.attachments)!=null?wg:{};ie&&(ie.accept=((Ag=Y.allowedTypes)!=null?Ag:yo).join(","),ie.multiple=((Sg=Y.maxFiles)!=null?Sg:4)>1),St&&St.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ye&&(ye.style.display="none"),St&&St.clearAttachments(),(Tg=j.querySelector(".persona-attachment-drop-overlay"))==null||Tg.remove();let mr=(Mg=n.sendButton)!=null?Mg:{},Yo=(kg=mr.useIcon)!=null?kg:!1,Wo=(Eg=mr.iconText)!=null?Eg:"\u2191",Bo=mr.iconName,uo=(Lg=mr.tooltipText)!=null?Lg:"Send message",Zo=(Pg=mr.showTooltip)!=null?Pg:!1,qn=(Rg=mr.size)!=null?Rg:"40px",dt=mr.backgroundColor,Hr=mr.textColor;if(Yo){if(Ge.style.width=qn,Ge.style.height=qn,Ge.style.minWidth=qn,Ge.style.minHeight=qn,Ge.style.fontSize="18px",Ge.style.lineHeight="1",Ge.innerHTML="",Hr?Ge.style.color=Hr:Ge.style.color="var(--persona-button-primary-fg, #ffffff)",Bo){let Y=parseFloat(qn)||24,Dt=(Hr==null?void 0:Hr.trim())||"currentColor",tr=Me(Bo,Y,Dt,2);tr?Ge.appendChild(tr):Ge.textContent=Wo}else Ge.textContent=Wo;Ge.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",dt?(Ge.style.backgroundColor=dt,Ge.classList.remove("persona-bg-persona-primary")):(Ge.style.backgroundColor="",Ge.classList.add("persona-bg-persona-primary"))}else Ge.textContent=(Hg=(Ig=n.copy)==null?void 0:Ig.sendButtonLabel)!=null?Hg:"Send",Ge.style.width="",Ge.style.height="",Ge.style.minWidth="",Ge.style.minHeight="",Ge.style.fontSize="",Ge.style.lineHeight="",Ge.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",dt?(Ge.style.backgroundColor=dt,Ge.classList.remove("persona-bg-persona-accent")):Ge.classList.add("persona-bg-persona-accent"),Hr?Ge.style.color=Hr:Ge.classList.add("persona-text-white");mr.borderWidth?(Ge.style.borderWidth=mr.borderWidth,Ge.style.borderStyle="solid"):(Ge.style.borderWidth="",Ge.style.borderStyle=""),mr.borderColor?Ge.style.borderColor=mr.borderColor:Ge.style.borderColor="",mr.paddingX?(Ge.style.paddingLeft=mr.paddingX,Ge.style.paddingRight=mr.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),mr.paddingY?(Ge.style.paddingTop=mr.paddingY,Ge.style.paddingBottom=mr.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let er=Fr==null?void 0:Fr.querySelector(".persona-send-button-tooltip");if(Zo&&uo)if(er)er.textContent=uo,er.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=uo,Fr==null||Fr.insertBefore(Y,Ge)}else er&&(er.style.display="none");let Jt=(Og=(Wg=n.layout)==null?void 0:Wg.contentMaxWidth)!=null?Og:H()?(Fg=(Dg=(Bg=n.launcher)==null?void 0:Bg.composerBar)==null?void 0:Dg.contentMaxWidth)!=null?Fg:"720px":void 0;Jt?(nt.style.maxWidth=Jt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",Bt&&(Bt.style.maxWidth=Jt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Rt&&(Rt.style.maxWidth=Jt,Rt.style.marginLeft="auto",Rt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""),Rt&&(Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight=""));let kt=(Ng=n.statusIndicator)!=null?Ng:{},gr=(_g=kt.visible)!=null?_g:!0;if(or.style.display=gr?"":"none",q){let Y=q.getStatus();wt(or,(tr=>{var bt,Ut,Wr,Gr;return tr==="idle"?(bt=kt.idleText)!=null?bt:Kr.idle:tr==="connecting"?(Ut=kt.connectingText)!=null?Ut:Kr.connecting:tr==="connected"?(Wr=kt.connectedText)!=null?Wr:Kr.connected:tr==="error"?(Gr=kt.errorText)!=null?Gr:Kr.error:Kr[tr]})(Y),kt,Y)}or.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ft=kt.align==="left"?"persona-text-left":kt.align==="center"?"persona-text-center":"persona-text-right";or.classList.add(Ft)},open(){I()&&jt(!0,"api")},close(){I()&&jt(!1,"api")},toggle(){I()&&jt(!L,"api")},clearChat(){lr=!1,q.clearMessages(),so.clear(),Yn();try{localStorage.removeItem(ns),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ns}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ns)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(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},S.syncFromMetadata(),ge==null||ge.clear(),Z==null||Z.reset(),G==null||G.update()},setMessage(c){return!ee||q.isStreaming()?!1:(!L&&I()&&jt(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ee.value.trim();return g?(!L&&I()&&jt(!0,"system"),ee.value="",ee.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return q.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(q.isVoiceActive()||(!L&&I()&&jt(!0,"system"),Pt.manuallyDeactivated=!1,dn(),q.toggleVoice().then(()=>{Pt.active=q.isVoiceActive(),Pn("user"),q.isVoiceActive()&&bs()})),!0):Mt?!0:_r()?(!L&&I()&&jt(!0,"system"),Pt.manuallyDeactivated=!1,dn(),fr("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(()=>{Pt.active=!1,Pt.manuallyDeactivated=!0,dn(),Pn("user"),Io()}),!0):!1:Mt?(Pt.manuallyDeactivated=!0,dn(),Or("user"),!0):!1},injectMessage(c){return!L&&I()&&jt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!L&&I()&&jt(!0,"system");let g=q.injectAssistantMessage(c);return O&&(O=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!L&&I()&&jt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!L&&I()&&jt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!L&&I()&&jt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!L&&I()&&jt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!L&&I()&&jt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){ge&&(Z==null||Z.processEvent(c.type,c.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!De||!ge||Mn()},hideEventStream(){pe&&ln()},isEventStreamVisible(){return pe},showArtifacts(){Bn(n)&&(lr=!1,mn(),et==null||et.setMobileOpen(!0))},hideArtifacts(){Bn(n)&&(lr=!0,mn())},upsertArtifact(c){return Bn(n)?(lr=!1,q.upsertArtifact(c)):null},selectArtifact(c){Bn(n)&&q.selectArtifact(c)},clearArtifacts(){Bn(n)&&q.clearArtifacts()},getArtifacts(){var c;return(c=q==null?void 0:q.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=q==null?void 0:q.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!L&&!H()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,g,y){let W=q.getMessages().find(_=>{var U;return _.variant==="approval"&&((U=_.approval)==null?void 0:U.id)===c});if(!(W!=null&&W.approval))throw new Error(`Approval not found: ${c}`);if(W.approval.toolType==="webmcp"){q.resolveWebMcpApproval(W.id,g);return}return q.resolveApproval(W.approval,g,y)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return I()&&L},isVoiceActive(){return Pt.active},getState(){return{open:I()&&L,launcherEnabled:T,voiceActive:Pt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!L&&I()&&jt(!0,"system");let g=nt.querySelector(".persona-feedback-container");g&&g.remove();let y=ed({onSubmit:async(A,W)=>{var _;q.isClientTokenMode()&&await q.submitCSATFeedback(A,W),(_=c==null?void 0:c.onSubmit)==null||_.call(c,A,W)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!L&&I()&&jt(!0,"system");let g=nt.querySelector(".persona-feedback-container");g&&g.remove();let y=td({onSubmit:async(A,W)=>{var _;q.isClientTokenMode()&&await q.submitNPSFeedback(A,W),(_=c==null?void 0:c.onSubmit)==null||_.call(c,A,W)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return q.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return q.submitNPSFeedback(c,g)},destroy(){je!=null&&(clearInterval(je),je=null),Tt.forEach(c=>c()),We.remove(),at==null||at.remove(),Ar==null||Ar.destroy(),Sr==null||Sr.remove(),Ln&&F.removeEventListener("click",Ln)}};if((((Df=t==null?void 0:t.debugTools)!=null?Df:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Er,getMessages:Er.getMessages,getStatus:Er.getStatus,getMetadata:Er.getPersistentMetadata,updateMetadata:Er.updatePersistentMetadata,clearHistory:()=>Er.clearChat(),setVoiceActive:y=>y?Er.startVoiceRecognition():Er.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Tt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=r.getAttribute("data-persona-instance")||r.id||"persona-"+Math.random().toString(36).slice(2,8),g=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Er.focusInput()};if(window.addEventListener("persona:focusInput",g),Tt.push(()=>{window.removeEventListener("persona:focusInput",g)}),De){let V=Ce=>{let me=Ce.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&Er.showEventStream()},N=Ce=>{let me=Ce.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&Er.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",N),Tt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",N)})}let y=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Er.showArtifacts()},A=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Er.hideArtifacts()},W=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==c||N!=null&&N.artifact&&Er.upsertArtifact(N.artifact)},_=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==c||typeof(N==null?void 0:N.id)=="string"&&Er.selectArtifact(N.id)},U=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Er.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",_),window.addEventListener("persona:clearArtifacts",U),Tt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",_),window.removeEventListener("persona:clearArtifacts",U)})}let Rn=WC(n.persistState);if(Rn&&I()){let c=BC(Rn.storage),g=`${Rn.keyPrefix}widget-open`,y=`${Rn.keyPrefix}widget-voice`,A=`${Rn.keyPrefix}widget-voice-mode`;if(c){let W=((Ff=Rn.persist)==null?void 0:Ff.openState)&&c.getItem(g)==="true",_=((Of=Rn.persist)==null?void 0:Of.voiceState)&&c.getItem(y)==="true",U=((Nf=Rn.persist)==null?void 0:Nf.voiceState)&&c.getItem(A)==="true";if(W&&setTimeout(()=>{Er.open(),setTimeout(()=>{var V;if(_||U)Er.startVoiceRecognition();else if((V=Rn.persist)!=null&&V.focusInput){let N=r.querySelector("textarea");N&&N.focus()}},100)},0),(_f=Rn.persist)!=null&&_f.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(Uf=Rn.persist)!=null&&Uf.voiceState&&(a.on("voice:state",V=>{c.setItem(y,V.active?"true":"false")}),a.on("user:message",V=>{c.setItem(A,V.viaVoice?"true":"false")})),Rn.clearOnChatClear){let V=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(A)},N=()=>V();window.addEventListener("persona:clear-chat",N),Tt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return u&&I()&&setTimeout(()=>{Er.open()},0),po(),Er};var DC=(r,e)=>{let t=r.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},FC=(r,e)=>{if(e===!1){r.style.maxHeight="";return}r.style.maxHeight="100vh",r.style.maxHeight=e},OC=(r,e)=>{e===!1?(r.style.position="relative",r.style.top=""):(r.style.position="sticky",r.style.top="0")},NC=(r,e)=>{let t=r.parentElement;if(!t)return;let n=r.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!o||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},db=(r,e)=>{var n,o;let t=(o=(n=e==null?void 0:e.launcher)==null?void 0:n.enabled)!=null?o:!0;r.className="persona-host",r.style.height=t?"":"100%",r.style.display=t?"":"flex",r.style.flexDirection=t?"":"column",r.style.flex=t?"":"1 1 auto",r.style.minHeight=t?"":"0"},xu=r=>{r.style.position="",r.style.top="",r.style.bottom="",r.style.left="",r.style.right="",r.style.zIndex="",r.style.transform="",r.style.pointerEvents=""},cb=r=>{r.style.inset="",r.style.width="",r.style.height="",r.style.maxWidth="",r.style.maxHeight="",r.style.minWidth="",xu(r)},mu=r=>{r.style.transition=""},gu=r=>{r.style.display="",r.style.flexDirection="",r.style.flex="",r.style.minHeight="",r.style.minWidth="",r.style.width="",r.style.height="",r.style.alignItems="",r.style.transition="",r.style.transform=""},hu=r=>{r.style.width="",r.style.maxWidth="",r.style.minWidth="",r.style.flex="1 1 auto"},od=(r,e)=>{r.style.width="",r.style.minWidth="",r.style.maxWidth="",r.style.boxSizing="",e.style.alignItems=""},_C=(r,e,t,n,o)=>{o?t.parentElement!==e&&(r.replaceChildren(),e.replaceChildren(t,n),r.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),r.appendChild(t),r.appendChild(n))},UC=(r,e,t,n,o,a)=>{let s=a?e:r;o==="left"?s.firstElementChild!==n&&s.replaceChildren(n,t):s.lastElementChild!==n&&s.replaceChildren(t,n)},pb=(r,e,t,n,o,a,s)=>{var b,h,S,T,M,k;let i=Sn(a),d=i.reveal==="push";_C(r,e,t,n,d),UC(r,e,t,n,i.side,d),r.dataset.personaHostLayout="docked",r.dataset.personaDockSide=i.side,r.dataset.personaDockOpen=s?"true":"false",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.height="100%",r.style.minHeight="0",r.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=r.ownerDocument.defaultView,u=(h=(b=a==null?void 0:a.launcher)==null?void 0:b.mobileFullscreen)!=null?h:!0,m=(T=(S=a==null?void 0:a.launcher)==null?void 0:S.mobileBreakpoint)!=null?T:640,p=l!=null?l.innerWidth<=m:!1;if(u&&p&&s){r.dataset.personaDockMobileFullscreen="true",r.removeAttribute("data-persona-dock-reveal"),gu(e),mu(n),cb(n),hu(t),od(o,n),r.style.display="flex",r.style.flexDirection="column",r.style.alignItems="stretch",r.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((k=(M=a==null?void 0:a.launcher)==null?void 0:M.zIndex)!=null?k:Xr),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(r.removeAttribute("data-persona-dock-mobile-fullscreen"),cb(n),FC(n,i.maxHeight),i.reveal==="overlay"){r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="hidden",r.dataset.personaDockReveal="overlay",gu(e),mu(n),hu(t),od(o,n);let x=i.animate?"transform 180ms ease":"none",C=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=s?"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=x,n.style.transform=w,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="hidden",r.dataset.personaDockReveal="push",mu(n),xu(n),od(o,n);let x=DC(i.width,r.clientWidth),C=Math.max(0,r.clientWidth),w=i.animate?"transform 180ms ease":"none",E=i.side==="right"?s?`translateX(-${x}px)`:"translateX(0)":s?"translateX(0)":`translateX(-${x}px)`;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${C+x}px`,e.style.transition=w,e.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${C}px`,t.style.maxWidth=`${C}px`,t.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.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="",gu(e),xu(n),hu(t),od(o,n);let x=i.reveal==="emerge";x?r.dataset.personaDockReveal="emerge":r.removeAttribute("data-persona-dock-reveal");let C=s?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!s;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${C}`,n.style.width=C,n.style.maxWidth=C,n.style.minWidth=C,n.style.minHeight="0",OC(n,i.maxHeight),n.style.overflow=x||E?"hidden":"visible",n.style.transition=w,x&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},qC=(r,e)=>{let t=r.ownerDocument.createElement("div");return db(t,e),r.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){db(t,n)},destroy(){t.remove()}}},zC=(r,e)=>{var k,x,C,w;let{ownerDocument:t}=r,n=r.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=r.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=r.nextSibling,s=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),m=(x=(k=e==null?void 0:e.launcher)==null?void 0:k.enabled)==null||x?(w=(C=e==null?void 0:e.launcher)==null?void 0:C.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),n.insertBefore(s,r),d.appendChild(r);let p=null,f=()=>{p==null||p.disconnect(),p=null},b=()=>{f(),Sn(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{pb(s,i,d,l,u,e,m)}),p.observe(s))},h=!1,S=()=>{pb(s,i,d,l,u,e,m),b(),m&&!h&&s.dataset.personaDockMobileFullscreen!=="true"&&(h=!0,NC(s,Sn(e)))},T=s.ownerDocument.defaultView,M=()=>{S()};return T==null||T.addEventListener("resize",M),Sn(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),S(),{mode:"docked",host:u,shell:s,syncWidgetState(E){let H=E.launcherEnabled?E.open:!0;m!==H&&(m=H,S())},updateConfig(E){var H,I;e=E,((I=(H=e==null?void 0:e.launcher)==null?void 0:H.enabled)!=null?I:!0)===!1&&(m=!0),S()},destroy(){T==null||T.removeEventListener("resize",M),f(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(r,a):n.appendChild(r)),s.remove()}}},pi=(r,e)=>Pr(e)?zC(r,e):qC(r,e);var bu={},ub=!1,$C=r=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof r=="string"){let e=document.querySelector(r);if(!e)throw new Error(`Chat widget target "${r}" was not found`);return e}return r},VC=()=>{try{if(typeof bu!="undefined"&&bu.url)return new URL("../widget.css",bu.url).href}catch{}return null},fb=(r,e)=>{let t=VC(),n=()=>{if(!(r instanceof ShadowRoot)||r.querySelector("link[data-persona]"))return;let o=e.head.querySelector("link[data-persona]");if(!o)return;let a=o.cloneNode(!0);r.insertBefore(a,r.firstChild)};if(r instanceof ShadowRoot)if(t){let o=e.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.insertBefore(o,r.firstChild)}else n();else if(!e.head.querySelector("link[data-persona]")&&t){let a=e.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),e.head.appendChild(a)}},mb=r=>{let e=$C(r.target),t=r.useShadowDom===!0,n=e.ownerDocument,o=r.config,a=pi(e,o),s,i=[],d=(S,T)=>{var C,w;let k=!((w=(C=T==null?void 0:T.launcher)==null?void 0:C.enabled)!=null?w:!0)||Pr(T),x=n.createElement("div");if(x.setAttribute("data-persona-root","true"),k&&(x.style.height="100%",x.style.display="flex",x.style.flexDirection="column",x.style.flex="1",x.style.minHeight="0"),t){let E=S.attachShadow({mode:"open"});E.appendChild(x),fb(E,n)}else S.appendChild(x),fb(S,n);return e.id&&x.setAttribute("data-persona-instance",e.id),x},l=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(S=>S()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},m=()=>{let S=d(a.host,o);s=nd(S,o,{debugTools:r.debugTools}),u()},p=()=>{i.forEach(S=>S()),i=[],s.destroy()};m(),r.onChatReady?r.onChatReady():r.onReady&&(ub||(ub=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),r.onReady());let f=S=>{p(),a.destroy(),a=pi(e,S),o=S,m()},b={update(S){var w,E,H,I,L,O;let T={...o,...S,launcher:{...(w=o==null?void 0:o.launcher)!=null?w:{},...(E=S==null?void 0:S.launcher)!=null?E:{},dock:{...(I=(H=o==null?void 0:o.launcher)==null?void 0:H.dock)!=null?I:{},...(O=(L=S==null?void 0:S.launcher)==null?void 0:L.dock)!=null?O:{}}}},M=Pr(o),k=Pr(T),x=zo(o),C=zo(T);if(M!==k||x!==C){f(T);return}o=T,a.updateConfig(o),s.update(S),l()},destroy(){p(),a.destroy(),r.windowKey&&typeof window!="undefined"&&delete window[r.windowKey]}},h=new Proxy(b,{get(S,T,M){if(T==="host")return a.host;if(T in S)return Reflect.get(S,T,M);let k=s[T];return typeof k=="function"?k.bind(s):k}});return r.windowKey&&typeof window!="undefined"&&(window[r.windowKey]=h),h};var yb=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),jC=new Set(["button","a","input","select","textarea","details","summary"]),GC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yu=/\b(product|card|item|listing|result)\b/i,Cu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,KC=3e3,XC=100;function vb(r){let e=typeof r.className=="string"?r.className:"";if(yu.test(e)||r.id&&yu.test(r.id))return!0;for(let t=0;t<r.attributes.length;t++){let n=r.attributes[t];if(n.name.startsWith("data-")&&yu.test(n.value))return!0}return!1}function Cb(r){var e;return Cu.test(((e=r.textContent)!=null?e:"").trim())}function wb(r){var t;let e=r.querySelectorAll("a[href]");for(let n=0;n<e.length;n++){let o=(t=e[n].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function QC(r){return!!r.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function gb(r){let e=r.match(Cu);return e?e[0]:null}function hb(r){var n,o,a;let e=(n=r.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:r.querySelector("a[href]");if(e&&((o=e.textContent)!=null&&o.trim())){let s=e.getAttribute("href");return{title:e.textContent.trim(),href:s&&s!=="#"?s:null}}let t=r.querySelector("h1, h2, h3, h4, h5, h6");return(a=t==null?void 0:t.textContent)!=null&&a.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function JC(r){let e=[],t=n=>{let o=n.trim();o&&!e.includes(o)&&e.push(o)};return r.querySelectorAll("button").forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),r.querySelectorAll('[role="button"]').forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),r.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;t((o=n.value)!=null?o:"")}),e.slice(0,6)}var YC="commerce-card",ZC="result-card";function xb(r){return!vb(r)||!Cb(r)||!wb(r)&&!QC(r)?0:5200}function bb(r){var n;return!vb(r)||Cb(r)||!wb(r)||((n=r.textContent)!=null?n:"").trim().length<20||!(!!r.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!r.querySelector(".snippet, .description, p"))?0:2800}var wu=[{id:YC,scoreElement(r){return xb(r)},shouldSuppressDescendant(r,e,t){if(e===r||!r.contains(e))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Cu.test(n)&&n.length<32)}return!0},formatSummary(r,e){var d,l,u;if(xb(r)===0)return null;let{title:t,href:n}=hb(r),o=(u=(l=gb(((d=r.textContent)!=null?d:"").trim()))!=null?l:gb(e.text))!=null?u:"",a=JC(r);return[n&&t?`[${t}](${n})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||e.text.trim().slice(0,120),`selector: ${e.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
155
|
+
`)}},{id:ZC,scoreElement(r){return bb(r)},formatSummary(r,e){if(bb(r)===0)return null;let{title:t,href:n}=hb(r);return[n&&t?`[${t}](${n})`:t||e.text.trim().slice(0,120),`selector: ${e.selector}`].filter(Boolean).join(`
|
|
156
|
+
`)}}];function ew(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function tw(r){var u,m,p,f,b,h,S,T,M,k,x,C,w;let e=(u=r.options)!=null?u:{},t=(p=(m=e.maxElements)!=null?m:r.maxElements)!=null?p:80,n=(b=(f=e.excludeSelector)!=null?f:r.excludeSelector)!=null?b:".persona-host",o=(S=(h=e.maxTextLength)!=null?h:r.maxTextLength)!=null?S:200,a=(M=(T=e.visibleOnly)!=null?T:r.visibleOnly)!=null?M:!0,s=(k=e.root)!=null?k:r.root,i=(x=e.mode)!=null?x:"structured",d=(C=e.maxCandidates)!=null?C:Math.max(500,t*10),l=(w=r.rules)!=null?w:wu;return i==="simple"&&r.rules&&r.rules.length>0?(ew(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:l}}function vu(r){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^\w-])/g,"\\$1")}var rw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function nw(r){let e=r.tagName.toLowerCase(),t=r.getAttribute("role");return e==="a"&&r.hasAttribute("href")?"navigable":e==="input"||e==="select"||e==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":e==="button"||t==="button"||jC.has(e)||t&&GC.has(t)||r.hasAttribute("tabindex")||r.hasAttribute("onclick")||r.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ab(r){if(r.hidden)return!1;try{let e=getComputedStyle(r);if(e.display==="none"||e.visibility==="hidden")return!1}catch{}return!(r.style.display==="none"||r.style.visibility==="hidden")}function ow(r){let e={},t=r.id;t&&(e.id=t);let n=r.getAttribute("href");n&&(e.href=n);let o=r.getAttribute("aria-label");o&&(e["aria-label"]=o);let a=r.getAttribute("type");a&&(e.type=a);let s=r.getAttribute("value");s&&(e.value=s);let i=r.getAttribute("name");i&&(e.name=i);let d=r.getAttribute("role");d&&(e.role=d);for(let l=0;l<r.attributes.length;l++){let u=r.attributes[l];u.name.startsWith("data-")&&(e[u.name]=u.value)}return e}function Au(r){let e=r.tagName.toLowerCase();if(r.id){let o=`#${vu(r.id)}`;try{if(r.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of rw){let a=r.getAttribute(o);if(a){let s=`${e}[${o}="${vu(a)}"]`;try{if(r.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let t=Array.from(r.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${e}.${t.map(s=>vu(s)).join(".")}`;try{if(r.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let a=r.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${e}`)).indexOf(r);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(r.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=r.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${e}`)).indexOf(r);if(a>=0)return`${e}:nth-of-type(${a+1})`}return e}function aw(r){return r==="static"?XC:KC}function Sb(r,e){var o;let t=r.tagName.toLowerCase(),n=((o=r.textContent)!=null?o:"").trim().substring(0,e);return{selector:Au(r),tagName:t,text:n,role:r.getAttribute("role"),interactivity:nw(r),attributes:ow(r)}}function sw(r,e,t,n){let o=aw(e.interactivity),a=null;for(let s of t){let i=s.scoreElement(r,e,n);i>0&&(o+=i,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function iw(r,e){var t;for(let n of r)if(e.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(e.el)&&n.formattingRule.shouldSuppressDescendant(n.el,e.el,e.enriched))return!0;return!1}function lw(r,e){let t={doc:e.ownerDocument,maxTextLength:r.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<r.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(yb.has(u)){i=s.nextNode();continue}if(r.excludeSelector)try{if(l.closest(r.excludeSelector)){i=s.nextNode();continue}}catch{}if(r.visibleOnly&&!Ab(l)){i=s.nextNode();continue}let m=Sb(l,r.maxTextLength),p=m.text.length>0,f=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(S=>S==="role");if(!p&&!f){i=s.nextNode();continue}if(n.has(m.selector)){i=s.nextNode();continue}n.add(m.selector);let{score:b,formattingRule:h}=sw(l,m,r.rules,t);o.push({el:l,domIndex:a,enriched:m,score:b,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((l,u)=>{let m=l.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return m!==p?m-p:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of o){if(d.length>=r.maxElements)break;iw(d,l)||d.push(l)}return d.sort((l,u)=>{let m=l.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return m!==p?m-p:m===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var p;let u;if((p=l.formattingRule)!=null&&p.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,t);f&&(u=f)}let m={...l.enriched};return u&&(m.formattedSummary=u),m})}function dw(r,e){let t=[],n=new Set,o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&t.length<r.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let d=a,l=d.tagName.toLowerCase();if(yb.has(l)){a=o.nextNode();continue}if(r.excludeSelector)try{if(d.closest(r.excludeSelector)){a=o.nextNode();continue}}catch{}if(r.visibleOnly&&!Ab(d)){a=o.nextNode();continue}let u=Sb(d,r.maxTextLength),m=u.text.length>0,p=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(f=>f==="role");if(!m&&!p){a=o.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}a=o.nextNode()}let s=[],i=[];for(let d of t)d.interactivity!=="static"?s.push(d):i.push(d);return[...s,...i].slice(0,r.maxElements)}function Tb(r={}){var n;let e=tw(r),t=(n=e.root)!=null?n:document.body;return t?e.mode==="simple"?dw(e,t):lw(e,t):[]}var ad=100;function Mb(r,e={}){var a;if(r.length===0)return"No page elements found.";let t=(a=e.mode)!=null?a:"structured",n=[];if(t==="structured"){let s=r.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&n.push(`Structured summaries:
|
|
157
|
+
${s.map(i=>`- ${i.split(`
|
|
161
158
|
`).join(`
|
|
162
159
|
`)}`).join(`
|
|
163
|
-
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let
|
|
164
|
-
${
|
|
165
|
-
`)}`)}if(o.navigable.length>0){let
|
|
166
|
-
${
|
|
167
|
-
`)}`)}if(o.input.length>0){let
|
|
168
|
-
${
|
|
169
|
-
`)}`)}if(o.static.length>0){let
|
|
170
|
-
${
|
|
160
|
+
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let s of r)t==="structured"&&s.formattedSummary||o[s.interactivity].push(s);if(o.clickable.length>0){let s=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,ad)}" (clickable)`);n.push(`Interactive elements:
|
|
161
|
+
${s.join(`
|
|
162
|
+
`)}`)}if(o.navigable.length>0){let s=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ad)}" (navigable)`);n.push(`Navigation links:
|
|
163
|
+
${s.join(`
|
|
164
|
+
`)}`)}if(o.input.length>0){let s=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ad)}" (input)`);n.push(`Form inputs:
|
|
165
|
+
${s.join(`
|
|
166
|
+
`)}`)}if(o.static.length>0){let s=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ad)}"`);n.push(`Content:
|
|
167
|
+
${s.join(`
|
|
171
168
|
`)}`)}return n.join(`
|
|
172
169
|
|
|
173
|
-
`)}var
|
|
170
|
+
`)}var kb="3.33.0";var Eb=kb;function Lb(){return{name:"@persona/accessibility",version:"1.0.0",transform(r){return{...r,semantic:{...r.semantic,colors:{...r.semantic.colors,interactive:{...r.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Pb(){return{name:"@persona/animations",version:"1.0.0",transform(r){return{...r,palette:{...r.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Rb(r){return{name:"@persona/brand",version:"1.0.0",transform(e){var n;let t={...e.palette};return(n=r.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:no(r.colors.primary,.95),100:no(r.colors.primary,.9),200:no(r.colors.primary,.8),300:no(r.colors.primary,.7),400:no(r.colors.primary,.6),500:r.colors.primary,600:no(r.colors.primary,.8),700:no(r.colors.primary,.7),800:no(r.colors.primary,.6),900:no(r.colors.primary,.5),950:no(r.colors.primary,.45)}}),{...e,palette:t}}}}function Ib(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(r){return{...r,palette:{...r.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(r){return{...r,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Hb(){return{name:"@persona/high-contrast",version:"1.0.0",transform(r){return{...r,semantic:{...r.semantic,colors:{...r.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function no(r,e){let t=parseInt(r.slice(1,3),16),n=parseInt(r.slice(3,5),16),o=parseInt(r.slice(5,7),16),a=Math.round(t+(255-t)*(1-e)),s=Math.round(n+(255-n)*(1-e)),i=Math.round(o+(255-o)*(1-e));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Wb(r){return{name:r.name,version:r.version,transform:r.transform||(e=>e),cssVariables:r.cssVariables,afterResolve:r.afterResolve}}var pw={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"}}},Bb={components:{panel:{borderRadius:"0",shadow:"none"}}},Su={id:"shop",label:"Shopping Assistant",config:{theme:pw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:An},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?"]}},Tu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Bb}},Mu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Bb}},ku={shop:Su,minimal:Tu,fullscreen:Mu};function Db(r){return ku[r]}var uw=`
|
|
174
171
|
@keyframes persona-stream-wipe {
|
|
175
172
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
176
173
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -206,7 +203,7 @@ ${a.join(`
|
|
|
206
203
|
mask-image: none !important;
|
|
207
204
|
}
|
|
208
205
|
}
|
|
209
|
-
`.trim(),
|
|
206
|
+
`.trim(),fw={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:uw};ba(fw);var mw=`
|
|
210
207
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
211
208
|
animation: persona-stream-glyph-cycle-fade
|
|
212
209
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -224,7 +221,7 @@ ${a.join(`
|
|
|
224
221
|
opacity: 1 !important;
|
|
225
222
|
}
|
|
226
223
|
}
|
|
227
|
-
`.trim(),
|
|
224
|
+
`.trim(),ui="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",gw=10,hw=120,Eu=120,xw=.4,bw=50,yw=r=>{var n;if(!r)return Eu;let t=((n=r.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return t?parseFloat(t[1]):Eu},$b=r=>{let e=r.closest(".persona-stream-glyph-cycle"),t=yw(e);return hw*t/Eu},Lu=r=>{let e=ui[Math.floor(Math.random()*ui.length)];return r&&e===r&&(e=ui[(ui.indexOf(e)+1)%ui.length]),e},vw=r=>{let e=r.closest(".persona-stream-glyph-cycle");if(!e)return;let t=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let o of Array.from(t)){if(o===r){n=!0;continue}n&&Math.random()<xw&&(o.textContent=Lu())}},Fb=new WeakMap,Ob=25,Nb=.5,Cw=6,_b=.25,Ub=new WeakMap,qb=new WeakMap,ww=(r,e)=>{var o;if(!r)return Ob*Nb;let t=Ub.get(r);Ub.set(r,e);let n=(o=qb.get(r))!=null?o:Ob;if(t!==void 0){let a=e-t;a>1&&(n=n*(1-_b)+a*_b,qb.set(r,n))}return Math.max(Cw,n*Nb)},os=new Map,Aw=r=>{var t;let e=r.closest("[data-message-id]");return(t=e==null?void 0:e.dataset.messageId)!=null?t:null},Sw=r=>{var e;r&&os.set(r,((e=os.get(r))!=null?e:0)+1)},Tw=r=>{var t;if(!r)return;let e=(t=os.get(r))!=null?t:0;e<=1?os.delete(r):os.set(r,e-1)},Vb=r=>{var l;if(r.dataset.glyphCycleScheduled==="true")return;let e=(l=r.textContent)!=null?l:"";if(!e||/\s/.test(e))return;r.dataset.glyphCycleScheduled="true",r.dataset.glyphCycleFinal=e,r.setAttribute("data-preserve-runtime","stream-glyph-cycle"),r.textContent=Lu();let t=Aw(r);t&&(r.dataset.glyphCycleMessageId=t),Sw(t);let n=r.closest(".persona-stream-glyph-cycle"),o=Date.now(),a=ww(n,o),s=$b(r),i=gw*s,d=o+i;if(n){let u=Fb.get(n);u!==void 0&&(d=Math.max(d,u)),Fb.set(n,d+a)}Mw(r,e,d)},Mw=(r,e,t)=>{var s;if(r.dataset.glyphCycleStarted==="true")return;r.dataset.glyphCycleStarted="true";let n=$b(r),o=(s=r.textContent)!=null?s:void 0,a=()=>{var d;if(!r.isConnected)return;if(Date.now()>=t){r.textContent=e,r.removeAttribute("data-preserve-runtime"),delete r.dataset.glyphCycleStarted,delete r.dataset.glyphCycleFinal,Tw((d=r.dataset.glyphCycleMessageId)!=null?d:null),delete r.dataset.glyphCycleMessageId;return}let i=Lu(o);r.textContent=i,o=i,vw(r),setTimeout(a,n)};setTimeout(a,n)},zb=r=>{var t;let e=(t=r.querySelectorAll)==null?void 0:t.call(r,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))Vb(n)},kw=r=>r.nodeType===1,Ew={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:mw,bufferContent(r){if(r.length<bw)return"";let e=0,t=-1,n=0;for(;n<r.length;){if(r[n]==="*"&&r[n+1]==="*"){e+=1,n+=2;continue}/\s/.test(r[n])&&e%2===0&&(t=n),n+=1}return t<0?"":r.slice(0,t)},isAnimating(r){var e;return((e=os.get(r.id))!=null?e:0)>0},onAttach(r){zb(r);let e=new MutationObserver(t=>{for(let n of t)for(let o of Array.from(n.addedNodes))kw(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?Vb(o):zb(o))});return e.observe(r,{childList:!0,subtree:!0}),()=>e.disconnect()}};ba(Ew);var jb,Gb,Aa=typeof document!="undefined"&&(Gb=(jb=document.currentScript)==null?void 0:jb.src)!=null?Gb:null;kh(()=>{let r=Aa==null?void 0:Aa.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!r||r===Aa?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Aa!=null?Aa:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(r)});return ly(Lw);})();
|
|
228
225
|
/*! Bundled license information:
|
|
229
226
|
|
|
230
227
|
dompurify/dist/purify.es.mjs:
|